I'm trying to schedule a task in Windows 7 using c++. I use the example from https://learn.microsoft.com/en-us/windows/desktop/taskschd/time-trigger-example--c--- . (just exchenged _wgetenv). My code looks like this:
/********************************************************************
This sample schedules a task to start notepad.exe 1 minute from the
time the task is registered.
********************************************************************/
#define _WIN32_DCOM
#include "pch.h"
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <comdef.h>
#include <wincred.h>
#include <stdlib.h>
// Include the task header file.
#include <taskschd.h>
#pragma comment(lib, "taskschd.lib")
#pragma comment(lib, "comsupp.lib")
#pragma comment(lib, "credui.lib")
using namespace std;
int __cdecl wmain()
{
// ------------------------------------------------------
// Initialize COM.
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
{
printf("\nCoInitializeEx failed: %x", hr);
return 1;
}
// Set general COM security levels.
hr = CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
0,
NULL);
if (FAILED(hr))
{
printf("\nCoInitializeSecurity failed: %x", hr);
CoUninitialize();
return 1;
}
// ------------------------------------------------------
// Create a name for the task.
LPCWSTR wszTaskName = L"Time Trigger Test Task";
// Get the windows directory and set the path to notepad.exe.
//wstring wstrExecutablePath = _wgetenv(L"WINDIR");
// changed compared with the example
wstring fullpath = L"WINDIR";
wchar_t *wchar_tpExecutablePath;
size_t len;
errno_t err =_wdupenv_s(&wchar_tpExecutablePath, &len, &fullpath[0]);
if (err) {
std::cout << "Failed to resolve WINDIR" << std::endl;
return -1;
}
std::wstring wstrExecutablePath(wchar_tpExecutablePath);
wstrExecutablePath += L"\\SYSTEM32\\NOTEPAD.EXE";
// ------------------------------------------------------
// Create an instance of the Task Service.
ITaskService *pService = NULL;
hr = CoCreateInstance(CLSID_TaskScheduler,
NULL,
CLSCTX_INPROC_SERVER,
IID_ITaskService,
(void**)&pService);
if (FAILED(hr))
{
printf("Failed to create an instance of ITaskService: %x", hr);
CoUninitialize();
return 1;
}
// Connect to the task service.
hr = pService->Connect(_variant_t(), _variant_t(),
_variant_t(), _variant_t());
if (FAILED(hr))
{
printf("ITaskService::Connect failed: %x", hr);
pService->Release();
CoUninitialize();
return 1;
}
// ------------------------------------------------------
// Get the pointer to the root task folder. This folder will hold the
// new task that is registered.
ITaskFolder *pRootFolder = NULL;
hr = pService->GetFolder(_bstr_t(L"\\"), &pRootFolder);
if (FAILED(hr))
{
printf("Cannot get Root folder pointer: %x", hr);
pService->Release();
CoUninitialize();
return 1;
}
// If the same task exists, remove it.
pRootFolder->DeleteTask(_bstr_t(wszTaskName), 0);
// Create the task definition object to create the task.
ITaskDefinition *pTask = NULL;
hr = pService->NewTask(0, &pTask);
pService->Release(); // COM clean up. Pointer is no longer used.
if (FAILED(hr))
{
printf("Failed to CoCreate an instance of the TaskService class: %x", hr);
pRootFolder->Release();
CoUninitialize();
return 1;
}
// ------------------------------------------------------
// Get the registration info for setting the identification.
IRegistrationInfo *pRegInfo = NULL;
hr = pTask->get_RegistrationInfo(&pRegInfo);
if (FAILED(hr))
{
printf("\nCannot get identification pointer: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
hr = pRegInfo->put_Author(_bstr_t(L"Author Name"));
pRegInfo->Release();
if (FAILED(hr))
{
printf("\nCannot put identification info: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// ------------------------------------------------------
// Create the principal for the task - these credentials
// are overwritten with the credentials passed to RegisterTaskDefinition
IPrincipal *pPrincipal = NULL;
hr = pTask->get_Principal(&pPrincipal);
if (FAILED(hr))
{
printf("\nCannot get principal pointer: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// Set up principal logon type to interactive logon
hr = pPrincipal->put_LogonType(TASK_LOGON_INTERACTIVE_TOKEN);
pPrincipal->Release();
if (FAILED(hr))
{
printf("\nCannot put principal info: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// ------------------------------------------------------
// Create the settings for the task
ITaskSettings *pSettings = NULL;
hr = pTask->get_Settings(&pSettings);
if (FAILED(hr))
{
printf("\nCannot get settings pointer: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// Set setting values for the task.
hr = pSettings->put_StartWhenAvailable(VARIANT_TRUE);
pSettings->Release();
if (FAILED(hr))
{
printf("\nCannot put setting information: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// Set the idle settings for the task.
IIdleSettings *pIdleSettings = NULL;
hr = pSettings->get_IdleSettings(&pIdleSettings);
if (FAILED(hr))
{
printf("\nCannot get idle setting information: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
hr = pIdleSettings->put_WaitTimeout(_bstr_t(L"PT5M"));
pIdleSettings->Release();
if (FAILED(hr))
{
printf("\nCannot put idle setting information: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// ------------------------------------------------------
// Get the trigger collection to insert the time trigger.
ITriggerCollection *pTriggerCollection = NULL;
hr = pTask->get_Triggers(&pTriggerCollection);
if (FAILED(hr))
{
printf("\nCannot get trigger collection: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// Add the time trigger to the task.
ITrigger *pTrigger = NULL;
hr = pTriggerCollection->Create(TASK_TRIGGER_TIME, &pTrigger);
pTriggerCollection->Release();
if (FAILED(hr))
{
printf("\nCannot create trigger: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
ITimeTrigger *pTimeTrigger = NULL;
hr = pTrigger->QueryInterface(
IID_ITimeTrigger, (void**)&pTimeTrigger);
pTrigger->Release();
if (FAILED(hr))
{
printf("\nQueryInterface call failed for ITimeTrigger: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
hr = pTimeTrigger->put_Id(_bstr_t(L"Trigger1"));
if (FAILED(hr))
printf("\nCannot put trigger ID: %x", hr);
hr = pTimeTrigger->put_EndBoundary(_bstr_t(L"2018-12-09T08:41:00"));
if (FAILED(hr))
printf("\nCannot put end boundary on trigger: %x", hr);
// Set the task to start at a certain time. The time
// format should be YYYY-MM-DDTHH:MM:SS(+-)(timezone).
// For example, the start boundary below
// is January 1st 2005 at 12:05
hr = pTimeTrigger->put_StartBoundary(_bstr_t(L"2018-12-09T08:41:00"));
pTimeTrigger->Release();
if (FAILED(hr))
{
printf("\nCannot add start boundary to trigger: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// ------------------------------------------------------
// Add an action to the task. This task will execute notepad.exe.
IActionCollection *pActionCollection = NULL;
// Get the task action collection pointer.
hr = pTask->get_Actions(&pActionCollection);
if (FAILED(hr))
{
printf("\nCannot get Task collection pointer: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// Create the action, specifying that it is an executable action.
IAction *pAction = NULL;
hr = pActionCollection->Create(TASK_ACTION_EXEC, &pAction);
pActionCollection->Release();
if (FAILED(hr))
{
printf("\nCannot create the action: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
IExecAction *pExecAction = NULL;
// QI for the executable task pointer.
hr = pAction->QueryInterface(
IID_IExecAction, (void**)&pExecAction);
pAction->Release();
if (FAILED(hr))
{
printf("\nQueryInterface call failed for IExecAction: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// Set the path of the executable to notepad.exe.
hr = pExecAction->put_Path(_bstr_t(wstrExecutablePath.c_str()));
pExecAction->Release();
if (FAILED(hr))
{
printf("\nCannot put action path: %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// ------------------------------------------------------
// Save the task in the root folder.
IRegisteredTask *pRegisteredTask = NULL;
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t(wszTaskName),
pTask,
TASK_CREATE_OR_UPDATE,
_variant_t(),
_variant_t(),
TASK_LOGON_INTERACTIVE_TOKEN,
_variant_t(L""),
&pRegisteredTask);
if (FAILED(hr))
{
printf("\nError saving the Task : %x", hr);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
printf("\n Success! Task successfully registered. ");
// Clean up.
pRootFolder->Release();
pTask->Release();
pRegisteredTask->Release();
CoUninitialize();
return 0;
}
However, the task does not show up in task scheduler, although I executed the program with admin rights. Can anybody help?
Thanks a lot
Related
I want to check the triggers for the tasks in the Task scheduler using c++.
I want to use the function HRESULT get_Type(TASK_TRIGGER_TYPE2 *pType);
to check whether the task is logon or boot triggered.
TASK_STATE taskState;
for (LONG i = 0; i < numTasks; i++)
{
IRegisteredTask* pRegisteredTask = NULL;
hr = pTaskCollection->get_Item(_variant_t(i + 1), &pRegisteredTask);
if (SUCCEEDED(hr))
{
BSTR taskName = NULL;
TASK_TRIGGER_TYPE2 *pType = NULL;
hr = pRegisteredTask->get_Name(&taskName);
if (SUCCEEDED(hr))
{
printf("\nTask Name: %S", taskName);
SysFreeString(taskName);
hr = pRegisteredTask->get_Type(*pType); //Implemented here
if (SUCCEEDED(hr))
printf("\n%s",&pType);
else
printf("\n\tCannot get the registered task state: %x", hr);
}
hr = pRegisteredTask->get_State(&taskState);
if (SUCCEEDED(hr))
printf("\n\tState: %d", taskState);
else
printf("\n\tCannot get the registered task state: %x", hr);
}
else
{
printf("\nCannot get the registered task name: %x", hr);
}
pRegisteredTask->Release();
}
else
{
printf("\nCannot get the registered task item at index=%d: %x", i + 1, hr);
}
}
On compilation, it gives me an error saying "IRegisteredTask has no member get_Type()"
Then I altered the code and added
ITrigger *trig = NULL;
trig->get_Type(&pType);
But that doesnt give me any values either
The following is code piece works fore me you can have a try:
for (LONG i = 0; i < numTasks; i++)
{
IRegisteredTask* pRegisteredTask = NULL;
hr = pTaskCollection->get_Item(_variant_t(i + 1), &pRegisteredTask);
if (SUCCEEDED(hr))
{
BSTR taskName = NULL;
hr = pRegisteredTask->get_Name(&taskName);
if (SUCCEEDED(hr))
{
printf("\nTask Name: %S", taskName);
SysFreeString(taskName);
hr = pRegisteredTask->get_State(&taskState);
if (SUCCEEDED(hr))
printf("\n\tState: %d", taskState);
else
printf("\n\tCannot get the registered task state: %x", hr);
}
else
{
printf("\nCannot get the registered task name: %x", hr);
}
ITaskDefinition* taskDef = NULL;
hr = pRegisteredTask->get_Definition(&taskDef);
if (SUCCEEDED(hr))
{
ITriggerCollection* triggers = NULL;
taskDef->get_Triggers(&triggers);
LONG trigCnt = 0;
triggers->get_Count(&trigCnt);
for (LONG i = 0; i < trigCnt; i++)
{
ITrigger* trig = NULL;
TASK_TRIGGER_TYPE2 pType = TASK_TRIGGER_EVENT;
triggers->get_Item(_variant_t(i + 1), &trig);
trig->get_Type(&pType);
DWORD errCode = GetLastError();
if(pType != NULL)
printf("\nTrigger Type : %d", pType);
}
}
else
{
printf("\nCannot get the registered task definition: %x", hr);
}
pRegisteredTask->Release();
}
else
{
printf("\nCannot get the registered task item at index=%d: %x", i + 1, hr);
}
}
Refer to "Displaying Task Names and States (C++)"
Looking at the documentation, it looks like after you have a IRegisteredTask you need to call get_Definition() to get its ITaskDefinition.
Using the ITaskDefinition, you can get the a ITriggerCollection via get_Triggers()
Then, enumerating over the ITriggerCollection, you can QueryInterface() each ITrigger to see if it supports the ILogonTrigger or IBootTrigger interfaces.
I'm working on an application which polls for the states and peak levels of audio sessions on the default audio rendering endpoint every X milliseconds, and implements some logic based on that.
It seems to run fine on Windows 10, but on Windows 7 I get occasional crashes when I change the default playback device (e.g. when I switch between my USB headset and the PC speaker).
The exact line where the crash occurs changes between runs, but it's usually when I access the IAudioSessionControl or IAudioSessionControl2 pointers to make various WASAPI calls.
What I could glean from the stack traces created by ProcDump and analyzed by WinDbg is that the COM objects representing audio sessions are destroyed when the default playback device has changed
(even though I had obtained and am still holding pointers to those objects' interfaces), and then my polling thread crashes randomly in places where I access them through the interface pointers.
I figured that maybe I'm doing something wrong, so this led me to Matthew van Eerde's
blog
and sample, where he does the same querying (and more), but for all available audio endpoints in the system.
So I modified his sample program to do it every 5 milliseconds and only for the default rendering endpoint, and I get the same occasional crashes on Windows 7.
Here is a stripped-down version of the sample, which sometimes results in crashes when switching between playback devices.
I usually get the crash within ~2 minutes of switching back-and-forth between devices. YMMV.
#include <windows.h>
#include <atlbase.h>
#include <stdio.h>
#include <mmdeviceapi.h>
#include <audiopolicy.h>
#include <endpointvolume.h>
#include <functiondiscoverykeys_devpkey.h>
#define LOG(format, ...) wprintf(format L"\n", __VA_ARGS__)
class CoUninitializeOnExit {
public:
CoUninitializeOnExit() {}
~CoUninitializeOnExit() {
CoUninitialize();
}
};
class PropVariantClearOnExit {
public:
PropVariantClearOnExit(PROPVARIANT *p) : m_p(p) {}
~PropVariantClearOnExit() {
PropVariantClear(m_p);
}
private:
PROPVARIANT *m_p;
};
int _cdecl wmain() {
HRESULT hr = S_OK;
hr = CoInitialize(NULL);
if (FAILED(hr)) {
LOG(L"CoInitialize failed: hr = 0x%08x", hr);
return -__LINE__;
}
CoUninitializeOnExit cuoe;
while (1)
{
Sleep(5);
// get default device
CComPtr<IMMDeviceEnumerator> pMMDeviceEnumerator;
hr = pMMDeviceEnumerator.CoCreateInstance(__uuidof(MMDeviceEnumerator));
if (FAILED(hr)) {
LOG(L"CoCreateInstance(IMMDeviceEnumerator) failed: hr = 0x%08x", hr);
return -__LINE__;
}
CComPtr<IMMDevice> pMMDevice;
hr = pMMDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &pMMDevice);
if (FAILED(hr)) {
LOG(L"IMMDeviceEnumerator::GetDefaultAudioEndpoint failed: hr = 0x%08x", hr);
return -__LINE__;
}
// get the name of the endpoint
CComPtr<IPropertyStore> pPropertyStore;
hr = pMMDevice->OpenPropertyStore(STGM_READ, &pPropertyStore);
if (FAILED(hr)) {
LOG(L"IMMDevice::OpenPropertyStore failed: hr = 0x%08x", hr);
return -__LINE__;
}
PROPVARIANT v; PropVariantInit(&v);
PropVariantClearOnExit pvcoe(&v);
hr = pPropertyStore->GetValue(PKEY_Device_FriendlyName, &v);
if (FAILED(hr)) {
LOG(L"IPropertyStore::GetValue(PKEY_Device_FriendlyName) failed: hr = 0x%08x", hr);
return -__LINE__;
}
if (VT_LPWSTR != v.vt) {
LOG(L"PKEY_Device_FriendlyName has unexpected vartype %u", v.vt);
return -__LINE__;
}
LOG(L"Selected playback device: %s\n", v.pwszVal);
// get a session enumerator
CComPtr<IAudioSessionManager2> pAudioSessionManager2;
hr = pMMDevice->Activate(
__uuidof(IAudioSessionManager2),
CLSCTX_ALL,
nullptr,
reinterpret_cast<void **>(&pAudioSessionManager2)
);
if (FAILED(hr)) {
LOG(L"IMMDevice::Activate(IAudioSessionManager2) failed: hr = 0x%08x", hr);
return -__LINE__;
}
CComPtr<IAudioSessionEnumerator> pAudioSessionEnumerator;
hr = pAudioSessionManager2->GetSessionEnumerator(&pAudioSessionEnumerator);
if (FAILED(hr)) {
LOG(L"IAudioSessionManager2::GetSessionEnumerator() failed: hr = 0x%08x", hr);
return -__LINE__;
}
// iterate over all the sessions
int count = 0;
hr = pAudioSessionEnumerator->GetCount(&count);
if (FAILED(hr)) {
LOG(L"IAudioSessionEnumerator::GetCount() failed: hr = 0x%08x", hr);
return -__LINE__;
}
for (int session = 0; session < count; session++) {
// get the session control
CComPtr<IAudioSessionControl> pAudioSessionControl;
hr = pAudioSessionEnumerator->GetSession(session, &pAudioSessionControl);
if (FAILED(hr)) {
LOG(L"IAudioSessionEnumerator::GetSession() failed: hr = 0x%08x", hr);
return -__LINE__;
}
AudioSessionState state;
hr = pAudioSessionControl->GetState(&state);
if (FAILED(hr)) {
LOG(L"IAudioSessionControl::GetState() failed: hr = 0x%08x", hr);
return -__LINE__;
}
CComPtr<IAudioSessionControl2> pAudioSessionControl2;
hr = pAudioSessionControl->QueryInterface(IID_PPV_ARGS(&pAudioSessionControl2));
if (FAILED(hr)) {
LOG(L"IAudioSessionControl::QueryInterface(IAudioSessionControl2) failed: hr = 0x%08x", hr);
return -__LINE__;
}
DWORD pid = 0;
hr = pAudioSessionControl2->GetProcessId(&pid);
if (FAILED(hr)) {
LOG(L"IAudioSessionControl2::GetProcessId() failed: hr = 0x%08x", hr);
return -__LINE__;
}
hr = pAudioSessionControl2->IsSystemSoundsSession();
if (FAILED(hr)) {
LOG(L"IAudioSessionControl2::IsSystemSoundsSession() failed: hr = 0x%08x", hr);
return -__LINE__;
}
bool bIsSystemSoundsSession = (S_OK == hr);
// get the current audio peak meter level for this session
CComPtr<IAudioMeterInformation> pAudioMeterInformation;
hr = pAudioSessionControl->QueryInterface(IID_PPV_ARGS(&pAudioMeterInformation));
if (FAILED(hr)) {
LOG(L"IAudioSessionControl::QueryInterface(IAudioMeterInformation) failed: hr = 0x%08x", hr);
return -__LINE__;
}
float peak = 0.0f;
hr = pAudioMeterInformation->GetPeakValue(&peak);
if (FAILED(hr)) {
LOG(L"IAudioMeterInformation::GetPeakValue() failed: hr = 0x%08x", hr);
return -__LINE__;
}
LOG(
L" Session #%d\n"
L" State: %d\n"
L" Peak value: %g\n"
L" Process ID: %u\n"
L" System sounds session: %s",
session,
state,
peak,
pid,
(bIsSystemSoundsSession ? L"yes" : L"no")
);
} // session
} // while
return 0;
}
Here is one instance of a crash dump analysis: https://pastebin.com/tvRV8ukY.
Is this an issue with the Windows 7 implementation of the Core Audio APIs, or am I doing something wrong?
Thanks.
I eventually contacted Matthew van Eerde by e-mail, and he said it does look like a race condition in Core Audio API on Windows 7, and my best bet is to file a support request to Microsoft.
Thanks for your help, Matthew!
Hi I am having an issue with the Task Scheduler API in my QT C++ program. I used the example code for a logon trigger here.
The first error I got was CoInitializeSecurity failed: RPC_E_TOO_LATE which means
CoInitializeSecurity has already been called. according to here. So I commented out the coinitializesecurity call and it fixed that.
However now I am getting the 80041318 error when trying to do the very last RegisterTaskDefinition step. I read here this means a value incorrectly formatted or out of range and also possibly an incorrect argument to pLogonTrigger. I tried commenting out the start boundary and end boundary code for the pLogonTrigger which didn't help. I also changed the changing the pLogonTrigger UserId and the userId parameter to the RegisterTaskDefinition function to my account as L"Josh". The only arguments to pLogonTrigger that are left are specified via put_Id and put_UserId.
Should I include any code if that would help and if so which code? The code is pretty much identical to the example code except for the pLogonTrigger modifications, the userId mods, and the commenting out of the cointializesecurity.
*Edited Code Added
void Replicator::taskCreate()
{
/*QProcess *taskProcess = new QProcess(this);
QString program = "schtasks.exe";
QStringList arguments;
arguments << "/create" << "/XML" << "rep.xml" << "/tn" << "task";
taskProcess->start(program, arguments);*/
// ------------------------------------------------------
// Initialize COM.
QString code;
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if( FAILED(hr) )
{
//updateStatus("\nCoInitializeEx failed: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
switch (hr)
{
case S_OK:
code = "S_OK";
break;
case S_FALSE:
code = "S_FALSE";
break;
case RPC_E_CHANGED_MODE:
code = "RPC_E_CHANGED_MODE";
break;
}
updateStatus("CoInitializeEx failed: " + QString("%1").arg(hr,8,16,QLatin1Char('0')) + code);
return;
}
// Set general COM security levels.
/* hr = CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
0,
NULL);
if( FAILED(hr) )
{
switch (hr)
{
case S_OK:
code = "S_OK";
break;
case RPC_E_TOO_LATE:
code = "RPC_E_TOO_LATE";
break;
case RPC_E_NO_GOOD_SECURITY_PACKAGES:
code = "RPC_E_NO_GOOD_SECURITY_PACKAGES";
break;
//case E_OUTOFMEMORY:
// code = "E_OUTOFMEMORY";
// break;
}
updateStatus("CoInitializeSecurity failed: " + code);
CoUninitialize();
return;
}*/
// ------------------------------------------------------
// Create a name for the task.
LPCWSTR wszTaskName = L"Jerp";
// Get the windows directory and set the path to notepad.exe.
wstring wstrExecutablePath = _wgetenv( L"WINDIR");
wstrExecutablePath += L"\\SYSTEM32\\NOTEPAD.EXE";
// ------------------------------------------------------
// Create an instance of the Task Service.
ITaskService *pService = NULL;
hr = CoCreateInstance( CLSID_TaskScheduler,
NULL,
CLSCTX_INPROC_SERVER,
IID_ITaskService,
(void**)&pService );
if (FAILED(hr))
{
updateStatus("Failed to create an instance of ITaskService: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
CoUninitialize();
return;
}
// Connect to the task service.
hr = pService->Connect(_variant_t(), _variant_t(),
_variant_t(), _variant_t());
if( FAILED(hr) )
{
updateStatus("ITaskService::Connect failed: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pService->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Get the pointer to the root task folder. This folder will hold the
// new task that is registered.
ITaskFolder *pRootFolder = NULL;
hr = pService->GetFolder( _bstr_t( L"\\") , &pRootFolder );
if( FAILED(hr) )
{
updateStatus("Cannot get Root Folder pointer: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pService->Release();
CoUninitialize();
return;
}
// If the same task exists, remove it.
pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0 );
// Create the task builder object to create the task.
ITaskDefinition *pTask = NULL;
hr = pService->NewTask( 0, &pTask );
pService->Release(); // COM clean up. Pointer is no longer used.
if (FAILED(hr))
{
updateStatus("Failed to create a task definition: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Get the registration info for setting the identification.
IRegistrationInfo *pRegInfo= NULL;
hr = pTask->get_RegistrationInfo( &pRegInfo );
if( FAILED(hr) )
{
updateStatus("Cannot get identification pointer: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
//hr = pRegInfo->put_Author(L"Author Name");
BSTR authorName = SysAllocString(L"Josh");
hr = pRegInfo->put_Author(authorName);
pRegInfo->Release();
if( FAILED(hr) )
{
updateStatus("Cannot put identification info: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Create the settings for the task
/*ITaskSettings *pSettings = NULL;
hr = pTask->get_Settings( &pSettings );
if( FAILED(hr) )
{
updateStatus("Cannot get settings pointer: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// Set setting values for the task.
hr = pSettings->put_StartWhenAvailable(VARIANT_TRUE);
pSettings->Release();
if( FAILED(hr) )
{
updateStatus("Cannot put setting info: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}*/
// ------------------------------------------------------
// Get the trigger collection to insert the logon trigger.
ITriggerCollection *pTriggerCollection = NULL;
hr = pTask->get_Triggers( &pTriggerCollection );
if( FAILED(hr) )
{
updateStatus("Cannot get trigger collection: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// Add the logon trigger to the task.
ITrigger *pTrigger = NULL;
hr = pTriggerCollection->Create( TASK_TRIGGER_LOGON, &pTrigger );
pTriggerCollection->Release();
if( FAILED(hr) )
{
updateStatus("Cannot create the trigger: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
ILogonTrigger *pLogonTrigger = NULL;
hr = pTrigger->QueryInterface(
IID_ILogonTrigger, (void**) &pLogonTrigger );
pTrigger->Release();
if( FAILED(hr) )
{
updateStatus("QueryInterface call failed for ILogonTrigger: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
hr = pLogonTrigger->put_Id( _bstr_t( L"Trigger1" ) );
if( FAILED(hr) )
updateStatus("Cannot put the trigger ID: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
// Set the task to start at a certain time. The time
// format should be YYYY-MM-DDTHH:MM:SS(+-)(timezone).
// For example, the start boundary below
// is January 1st 2005 at 12:05
/*hr = pLogonTrigger->put_StartBoundary( _bstr_t(L"2005-01-01T12:05:00") );
if( FAILED(hr) )
updateStatus("Cannot put the start boundary: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
hr = pLogonTrigger->put_EndBoundary( _bstr_t(L"2025-05-02T08:00:00") );
if( FAILED(hr) )
updateStatus("Cannot put the end boundary: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));*/
// Define the user. The task will execute when the user logs on.
// The specified user must be a user on this computer.
//hr = pLogonTrigger->put_UserId( _bstr_t( L"DOMAIN\\UserName" ) );
//hr = pLogonTrigger->put_UserId( _bstr_t( L"JOSHDESKTOP10\\Josh" ) );
hr = pLogonTrigger->put_UserId( _bstr_t( L"Josh" ) );
pLogonTrigger->Release();
if( FAILED(hr) )
{
updateStatus("Cannot add user ID to logon trigger: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Add an Action to the task. This task will execute notepad.exe.
IActionCollection *pActionCollection = NULL;
// Get the task action collection pointer.
hr = pTask->get_Actions( &pActionCollection );
if( FAILED(hr) )
{
updateStatus("Cannot get Task collection pointer: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// Create the action, specifying that it is an executable action.
IAction *pAction = NULL;
hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );
pActionCollection->Release();
if( FAILED(hr) )
{
updateStatus("Cannot create the action: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
IExecAction *pExecAction = NULL;
// QI for the executable task pointer.
hr = pAction->QueryInterface(
IID_IExecAction, (void**) &pExecAction );
pAction->Release();
if( FAILED(hr) )
{
updateStatus("QueryInterface call failed for IExecAction: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// Set the path of the executable to notepad.exe.
hr = pExecAction->put_Path( _bstr_t( wstrExecutablePath.c_str() ) );
pExecAction->Release();
if( FAILED(hr) )
{
updateStatus("Cannot set path of executable: " + QString("%1").arg(hr,8,16,QLatin1Char('0')));
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
// ------------------------------------------------------
// Save the task in the root folder.
IRegisteredTask *pRegisteredTask = NULL;
/*hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
//_variant_t(L"Builtin\\Administrators"),
_variant_t(L"Josh"),
_variant_t(),
TASK_LOGON_PASSWORD,
_variant_t(L""),
&pRegisteredTask);*/
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
//_variant_t(L"Builtin\\Administrators"),
_variant_t(),
_variant_t(),
TASK_LOGON_GROUP,
_variant_t(L""),
&pRegisteredTask);
if( FAILED(hr) )
{
switch (hr)
{
case E_ACCESSDENIED:
code = "E_ACCESSDENIED";
break;
case E_OUTOFMEMORY:
code = "E_OUTOFMEMORY";
break;
case SCHED_S_BATCH_LOGON_PROBLEM:
code = "SCHED_S_BATCH_LOGON_PROBLEM";
break;
case SCHED_S_SOME_TRIGGERS_FAILED:
code = "SCHED_S_SOME_TRIGGERS_FAILED";
break;
}
updateStatus("Error saving the Task : " + QString("%1").arg(hr,8,16,QLatin1Char('0')) + code);
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return;
}
updateStatus(" Success! Task successfully registered. " );
// Clean up
pRootFolder->Release();
pTask->Release();
pRegisteredTask->Release();
CoUninitialize();
}
Finally solved this problem after lots of troubleshooting... the answer is simple: set UserId to the appropriate user, in my case "Josh", you can use the Win32 API getusername function if you need to
hr = pLogonTrigger->put_UserId( _bstr_t( L"Josh" ) );
and then for RegisterTaskDefinition do this:
VARIANT varPassword;
varPassword.vt = VT_EMPTY;
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
_variant_t(L"Builtin\\Administrators"),
varPassword,
TASK_LOGON_GROUP,
_variant_t(L""),
&pRegisteredTask);
So the userID parameter for RegisterTaskDefinition needs to be _variant_t(L"Builtin\Administrators") and the logonType needs to be TASK_LOGON_GROUP
So the main point is the two UserId values aren't necessarily the same.
This is a sample code which creates a test task in windows task scheduler. It works fine in Windows 7 64 bit (Admin + standard Account), also on Windows 8.1 32 bit (Admin + standard user). However, when I run same code on Windows 7 32 bit Administrator user it works but fails with Non-Admin (Standard) user account.
I searched and tried almost everything I could but nothing worked.
Basically, I get error here:
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
_variant_t(),
_variant_t(),
TASK_LOGON_INTERACTIVE_TOKEN,
_variant_t(L""),
&pRegisteredTask);
hr value returned (error code) : 80070005
Here is my code:
/********************************************************************
This sample schedules a task to start notepad.exe 1 minute from the
time the task is registered.
********************************************************************/
#define _WIN32_DCOM
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <comdef.h>
#include <wincred.h>
// Include the task header file.
#include <taskschd.h>
# pragma comment(lib, "taskschd.lib")
# pragma comment(lib, "comsupp.lib")
# pragma comment(lib, "credui.lib")
//
using namespace std;
int __cdecl wmain()
{
int mystring;
printf("started");
cin>>mystring;
// ------------------------------------------------------
// Initialize COM.
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if( FAILED(hr) )
{
printf("\nCoInitializeEx failed: %x", hr );
cin>>mystring;
return 1;
}
// Set general COM security levels.
hr = CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
0,
NULL);
if( FAILED(hr) )
{
printf("\nCoInitializeSecurity failed: %x", hr );
CoUninitialize();
cin>>mystring;
return 1;
}
// ------------------------------------------------------
// Create a name for the task.
LPCWSTR wszTaskName = L"Time Trigger Test Task";
// Get the windows directory and set the path to notepad.exe.
wstring wstrExecutablePath = _wgetenv( L"WINDIR");
wstrExecutablePath += L"\\SYSTEM32\\NOTEPAD.EXE";
// ------------------------------------------------------
// Create an instance of the Task Service.
ITaskService *pService = NULL;
hr = CoCreateInstance( CLSID_TaskScheduler,
NULL,
CLSCTX_INPROC_SERVER,
IID_ITaskService,
(void**)&pService );
if (FAILED(hr))
{
printf("Failed to create an instance of ITaskService: %x", hr);
CoUninitialize();
cin>>mystring;
return 1;
}
// Connect to the task service.
hr = pService->Connect(_variant_t(), _variant_t(),
_variant_t(), _variant_t());
if( FAILED(hr) )
{
printf("ITaskService::Connect failed: %x", hr );
pService->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// ------------------------------------------------------
// Get the pointer to the root task folder. This folder will hold the
// new task that is registered.
ITaskFolder *pRootFolder = NULL;
hr = pService->GetFolder( _bstr_t( L"\\") , &pRootFolder );
if( FAILED(hr) )
{
printf("Cannot get Root folder pointer: %x", hr );
pService->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// If the same task exists, remove it.
pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0 );
// Create the task definition object to create the task.
ITaskDefinition *pTask = NULL;
hr = pService->NewTask( 0, &pTask );
pService->Release(); // COM clean up. Pointer is no longer used.
if (FAILED(hr))
{
printf("Failed to CoCreate an instance of the TaskService class: %x", hr);
pRootFolder->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// ------------------------------------------------------
// Get the registration info for setting the identification.
IRegistrationInfo *pRegInfo= NULL;
hr = pTask->get_RegistrationInfo( &pRegInfo );
if( FAILED(hr) )
{
printf("\nCannot get identification pointer: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
hr = pRegInfo->put_Author( L"Author Name" );
pRegInfo->Release();
if( FAILED(hr) )
{
printf("\nCannot put identification info: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// ------------------------------------------------------
// Create the principal for the task - these credentials
// are overwritten with the credentials passed to RegisterTaskDefinition
IPrincipal *pPrincipal = NULL;
hr = pTask->get_Principal( &pPrincipal );
if( FAILED(hr) )
{
printf("\nCannot get principal pointer: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// Set up principal logon type to interactive logon
hr = pPrincipal->put_LogonType( TASK_LOGON_INTERACTIVE_TOKEN );
pPrincipal->Release();
if( FAILED(hr) )
{
printf("\nCannot put principal info: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// ------------------------------------------------------
// Create the settings for the task
ITaskSettings *pSettings = NULL;
hr = pTask->get_Settings( &pSettings );
if( FAILED(hr) )
{
printf("\nCannot get settings pointer: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// Set setting values for the task.
hr = pSettings->put_StartWhenAvailable(VARIANT_TRUE);
pSettings->Release();
if( FAILED(hr) )
{
printf("\nCannot put setting information: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// Set the idle settings for the task.
IIdleSettings *pIdleSettings = NULL;
hr = pSettings->get_IdleSettings( &pIdleSettings );
if( FAILED(hr) )
{
printf("\nCannot get idle setting information: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
hr = pIdleSettings->put_WaitTimeout(L"PT5M");
pIdleSettings->Release();
if( FAILED(hr) )
{
printf("\nCannot put idle setting information: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// ------------------------------------------------------
// Get the trigger collection to insert the time trigger.
ITriggerCollection *pTriggerCollection = NULL;
hr = pTask->get_Triggers( &pTriggerCollection );
if( FAILED(hr) )
{
printf("\nCannot get trigger collection: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// Add the time trigger to the task.
ITrigger *pTrigger = NULL;
hr = pTriggerCollection->Create( TASK_TRIGGER_TIME, &pTrigger );
pTriggerCollection->Release();
if( FAILED(hr) )
{
printf("\nCannot create trigger: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
ITimeTrigger *pTimeTrigger = NULL;
hr = pTrigger->QueryInterface(
IID_ITimeTrigger, (void**) &pTimeTrigger );
pTrigger->Release();
if( FAILED(hr) )
{
printf("\nQueryInterface call failed for ITimeTrigger: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
hr = pTimeTrigger->put_Id( _bstr_t( L"Trigger1" ) );
if( FAILED(hr) )
printf("\nCannot put trigger ID: %x", hr);
hr = pTimeTrigger->put_EndBoundary( _bstr_t(L"2015-05-02T08:00:00") );
if( FAILED(hr) )
printf("\nCannot put end boundary on trigger: %x", hr);
// Set the task to start at a certain time. The time
// format should be YYYY-MM-DDTHH:MM:SS(+-)(timezone).
// For example, the start boundary below
// is January 1st 2005 at 12:05
hr = pTimeTrigger->put_StartBoundary( _bstr_t(L"2005-01-01T12:05:00") );
pTimeTrigger->Release();
if( FAILED(hr) )
{
printf("\nCannot add start boundary to trigger: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// ------------------------------------------------------
// Add an action to the task. This task will execute notepad.exe.
IActionCollection *pActionCollection = NULL;
// Get the task action collection pointer.
hr = pTask->get_Actions( &pActionCollection );
if( FAILED(hr) )
{
printf("\nCannot get Task collection pointer: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// Create the action, specifying that it is an executable action.
IAction *pAction = NULL;
hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );
pActionCollection->Release();
if( FAILED(hr) )
{
printf("\nCannot create the action: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
IExecAction *pExecAction = NULL;
// QI for the executable task pointer.
hr = pAction->QueryInterface(
IID_IExecAction, (void**) &pExecAction );
pAction->Release();
if( FAILED(hr) )
{
printf("\nQueryInterface call failed for IExecAction: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
// Set the path of the executable to notepad.exe.
hr = pExecAction->put_Path( _bstr_t( wstrExecutablePath.c_str() ) );
pExecAction->Release();
if( FAILED(hr) )
{
printf("\nCannot put action path: %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
// ------------------------------------------------------
// Save the task in the root folder.
IRegisteredTask *pRegisteredTask = NULL;
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
_variant_t(),
_variant_t(),
TASK_LOGON_INTERACTIVE_TOKEN,
_variant_t(L""),
&pRegisteredTask);
if( FAILED(hr) )
{
printf("\nError saving the Task : %x", hr );
pRootFolder->Release();
pTask->Release();
CoUninitialize();
cin>>mystring;
return 1;
}
printf("\n Success! Task successfully registered. " );
// Clean up.
pRootFolder->Release();
pTask->Release();
pRegisteredTask->Release();
CoUninitialize();
cin>>mystring;
return 0;
}
I am trying to write a windows Logon trigger task using C++ on Windows 7.
I am following this microsoft tutorial.
But I am facing problem in saving the task to root folder.
Here:
// ------------------------------------------------------
// Save the task in the root folder.
IRegisteredTask *pRegisteredTask = NULL;
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t( wszTaskName ),
pTask,
TASK_CREATE_OR_UPDATE,
_variant_t(L"Builtin\\Administrators"),
_variant_t(),
TASK_LOGON_GROUP,
_variant_t(L""),
&pRegisteredTask);
Where the hr is getting error : No Mapping between account names and security ids was done
I also tried replacing _variant_t(L"Builtin\\Administrators") with _variant_t(L"S-1-5-32-544") to NULL out language hard coding issue, still No luck.
How can I make it work?
A definitive solution to creation of a TaskScheduler task on Windows startup
(with Administor privileges, working for Windows 7, 8, etc. Note that this won't display an UAC popup on Windows startup "Are you sure to run this software with Admin rights?", that's why the TaskScheduler method is more interesting in this case than the good old HKEY_LOCAL_MACHINE\...\CurrentVersion\Run solution)
There are a few things to update in this tutorial
to make it work:
_variant_t(L"S-1-5-32-544") instead of _variant_t(L"Builtin\\Administrators")
_CRT_SECURE_NO_WARNINGS
In VC++, Project Properties > Configuration Properties > Linker > Manifest file > UAC Execution Level > requireAdministrator
Remove the date boundaries which are now outdated !
Replace hr = pLogonTrigger->put_UserId(_bstr_t(L"DOMAIN\\UserName")); by either a hardcoded Domain\Username, or by some Domain\Username detection code (I couldn't make it work), or just comment this line, it worked for me!
Add some code for TASK_RUNLEVEL_HIGHEST
Add some code to enable the task even if running from a laptop on batteries (default would be "don't run task if on batteries"!), and some code to prevent the .exe to be killed after some time (By default, a task will be stopped 72 hours after it starts to run), etc.
Then you'll get the famous:
Success! Task successfully registered.
Phew! After a few hours per day and some edits, now here is a working full main.cpp:
#define SECURITY_WIN32
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <comdef.h>
#include <Security.h>
#include <taskschd.h>
#pragma comment(lib, "taskschd.lib")
#pragma comment(lib, "comsupp.lib")
using namespace std;
#define TASKNAME L"Logon Trigger Test Task"
int __cdecl wmain()
{
// Get the windows directory and set the path to notepad.exe.
wstring wstrExecutablePath = _wgetenv(L"WINDIR");
wstrExecutablePath += L"\\SYSTEM32\\NOTEPAD.EXE";
// Initialize COM
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr)) return 1;
// Set general COM security levels.
hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL);
if (FAILED(hr)) goto cleanup0;
// Create an instance of the Task Service.
ITaskService *pService = NULL;
hr = CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void**)&pService);
if (FAILED(hr)) goto cleanup0;
// Connect to the task service.
hr = pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());
if (FAILED(hr)) goto cleanup1;
// Get the pointer to the root task folder. This folder will hold the new task that is registered.
ITaskFolder *pRootFolder = NULL;
hr = pService->GetFolder(_bstr_t(L"\\"), &pRootFolder);
if (FAILED(hr)) goto cleanup1;
// If the same task exists, remove it.
pRootFolder->DeleteTask(_bstr_t(TASKNAME), 0);
// Create the task builder object to create the task.
ITaskDefinition *pTask = NULL;
hr = pService->NewTask(0, &pTask);
// COM clean up. Pointer is no longer used.
pService->Release();
if (FAILED(hr)) { pRootFolder->Release(); CoUninitialize(); return 1; }
// Get the registration info for setting the identification.
IRegistrationInfo *pRegInfo = NULL;
hr = pTask->get_RegistrationInfo(&pRegInfo);
if (FAILED(hr)) goto cleanup2;
hr = pRegInfo->put_Author(L"Author Name");
pRegInfo->Release();
if (FAILED(hr)) goto cleanup2;
// Create the settings for the task
ITaskSettings *pSettings = NULL;
hr = pTask->get_Settings(&pSettings);
if (FAILED(hr)) goto cleanup2;
// Set setting values for the task.
pSettings->put_DisallowStartIfOnBatteries(VARIANT_FALSE);
pSettings->put_StopIfGoingOnBatteries(VARIANT_FALSE);
pSettings->put_ExecutionTimeLimit(_bstr_t(L"PT0S"));
pSettings->Release();
if (FAILED(hr)) goto cleanup2;
// Get the trigger collection to insert the logon trigger.
ITriggerCollection *pTriggerCollection = NULL;
hr = pTask->get_Triggers(&pTriggerCollection);
if (FAILED(hr)) goto cleanup2;
// Add the logon trigger to the task.
ITrigger *pTrigger = NULL;
hr = pTriggerCollection->Create(TASK_TRIGGER_LOGON, &pTrigger);
pTriggerCollection->Release();
if (FAILED(hr)) goto cleanup2;
ILogonTrigger *pLogonTrigger = NULL;
hr = pTrigger->QueryInterface(IID_ILogonTrigger, (void**)&pLogonTrigger);
pTrigger->Release();
if (FAILED(hr)) goto cleanup2;
hr = pLogonTrigger->put_Id(_bstr_t(L"Trigger1"));
if (FAILED(hr)) goto cleanup2;
// Define the user. The task will execute when the user logs on. The specified user must be a user on this computer.
//hr = pLogonTrigger->put_UserId(_bstr_t(L"DOMAIN\\UserName"));
pLogonTrigger->Release();
if (FAILED(hr)) goto cleanup2;
IPrincipal *pPrincipal;
hr = pTask->get_Principal(&pPrincipal);
if (FAILED(hr)) goto cleanup2;
hr = pPrincipal->put_RunLevel(TASK_RUNLEVEL_HIGHEST);
if (FAILED(hr)) goto cleanup2;
// Add an Action to the task. This task will execute .exe
IActionCollection *pActionCollection = NULL;
// Get the task action collection pointer.
hr = pTask->get_Actions(&pActionCollection);
if (FAILED(hr)) goto cleanup2;
// Create the action, specifying that it is an executable action.
IAction *pAction = NULL;
hr = pActionCollection->Create(TASK_ACTION_EXEC, &pAction);
pActionCollection->Release();
if (FAILED(hr)) goto cleanup2;
// QI for the executable task pointer.
IExecAction *pExecAction = NULL;
hr = pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction);
pAction->Release();
if (FAILED(hr)) goto cleanup2;
// Set the path of the executable.
hr = pExecAction->put_Path(_bstr_t(wstrExecutablePath.c_str()));
pExecAction->Release();
if (FAILED(hr)) goto cleanup2;
// Save the task in the root folder.
IRegisteredTask *pRegisteredTask = NULL;
hr = pRootFolder->RegisterTaskDefinition(_bstr_t(TASKNAME), pTask, TASK_CREATE_OR_UPDATE, _variant_t(L"S-1-5-32-544"), _variant_t(), TASK_LOGON_GROUP, _variant_t(L""), &pRegisteredTask); //_variant_t(L"Builtin\\Administrators"),
if (FAILED(hr)) goto cleanup2;
printf("Success! Task successfully registered.");
getchar();
pRootFolder->Release();
pTask->Release();
pRegisteredTask->Release();
CoUninitialize();
return 0;
cleanup0:
CoUninitialize();
return 1;
cleanup1:
pService->Release();
CoUninitialize();
return 1;
cleanup2:
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return 1;
}
I suspect the demo code you have is XP-era, and hasn't been updated to match the Vista/Win7 rules.
I updated the sample to set the LUA settings after setting the logon trigger, and it seems to work:
hr = pLogonTrigger->put_UserId(_bstr_t(L"DOMAIN\username"));
if (FAILED(hr))
{
printf("\nCannot add user ID to logon trigger: %x", hr);
CoUninitialize();
return 1;
}
//*** NEW**** Set the LUA settings
CComPtr<IPrincipal> pPrincipal;
hr = pTask->get_Principal(&pPrincipal);
if (SUCCEEDED(hr))
{
hr = pPrincipal->put_RunLevel(TASK_RUNLEVEL_LUA);
}
if (SUCCEEDED(hr))
{
hr = pPrincipal->put_GroupId(_bstr_t(L"Builtin\\Administrators"));
}
if (FAILED(hr))
{
printf("\nCannot set runlevel/groupid: %x", hr);
CoUninitialize();
return 1;
}
If you need it to run on XP, then it's likely that the get_Principal call will fail, so let that failure through.