Task Scheduler API Error 80041318 - c++

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.

Related

Cant get "Description" from Win32_OperatingSystem class

I try to get Description from Win32_OperatingSystem, the main problem that i takes empty string.
I dont understand why, when i try to take something else from Win32_OperatingSystem, with type string, i can get it.
Can there be situation when Description is empty? Or its just bug in my code...?
Code:
STDMETHODIMP CSystemInfo::GetOS(CString* SystemInfo )
{
HRESULT hres;
CString tmp;
hres = GetInfo( TEXT( "Win32_OperatingSystem" ), TEXT( "Description" ), &tmp );
if( FAILED( hres ) )
{
return E_FAIL;
}
SystemInfo->SetString( tmp.GetString() );
return S_OK;
}
STDMETHODIMP CSystemInfo::GetInfo( CString className, CString propertyName, CString* info )
{
HRESULT hres;
IWbemLocator* pLoc = NULL;
IWbemServices* pSvc = NULL;
IEnumWbemClassObject* pEnumerator = NULL;
bool initialized = true;
hres = CoInitialize( NULL );
if( FAILED( hres ) )
{
return E_FAIL;
}
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
if( FAILED( hres ) && hres != RPC_E_TOO_LATE )
{
}
hres = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, ( LPVOID* )&pLoc );
if( FAILED( hres ) )
{
return E_FAIL;
}
hres = pLoc->ConnectServer(
bstr_t( L"ROOT\\CIMV2" ), // Object path of WMI namespace
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (for example, Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
if( FAILED( hres ) )
{
return E_FAIL;
}
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if( FAILED( hres ) )
{
return E_FAIL;
}
CString tmp = TEXT( "SELECT * FROM ");
tmp += className.GetString();
hres = pSvc->ExecQuery(
bstr_t( "WQL" ),
bstr_t(tmp.GetString()),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator );
if( FAILED( hres ) )
{
return E_FAIL;
}
IWbemClassObject* pclsObj = NULL;
ULONG uReturn = 0;
while( pEnumerator )
{
HRESULT hr = pEnumerator->Next( WBEM_INFINITE, 1, &pclsObj, &uReturn );
if( uReturn == 0 )
{
break;
}
VARIANT vtProp;
hr = pclsObj->Get(propertyName.GetString(), 0, &vtProp, 0, 0 );
if( FAILED( hres ) )
{
return E_FAIL;
}
info->SetString( vtProp.bstrVal );
VariantClear( &vtProp );
pclsObj->Release();
}
CoUninitialize();
return S_OK;
}
Thats how i calling my function
HRESULT hr;
CoInitialize( NULL );
CSystemInfo* cSystem = NULL;
CLSID clsid;
hr = CLSIDFromProgID( L"Server.Inproc.1" , &clsid );
if( FAILED( hr ) )
{
std::cout << "Cant get CLSID " << std::endl;
}
hr = CoCreateInstance( clsid,NULL, CLSCTX_INPROC_SERVER, IID_ISystemInfo, ( void** )&cSystem );
if( FAILED( hr ) )
{
std::cout << "Cant Create Instance" << std::endl;
}
CString tmp;
hr = cSystem->GetOS( &tmp );
std::wcout << "OS Info: \t" ;
std::wcout << tmp.GetString() << std::endl;
Also i cant get description from Win32_DesktopMonitor.
You can check whether "Description" property is present or not by executing gwmi Win32_OperatingSystem command on Windows PowerShell. I cannot find the "Description" property of Win32_OperatingSystem on my pc.

How to check trigger of a task in Task scheduler using c++?

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.

Scheduled taks doens't show up in task scheduler in Windows 7

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

returning AccessDenied in taskscheduler(boot trigger) and need run without uac?

I'm trying write the boot trigger.but the project given me Access Denied error.
when run the code in administrator level task is created.but without this, show same error.
ITrigger *pTrigger = NULL;
hr = pTriggerCollection->Create(TASK_TRIGGER_BOOT, &pTrigger);
pTriggerCollection->Release();
IBootTrigger *pBootTrigger = NULL;
hr = pTrigger->QueryInterface(IID_IBootTrigger, (void**)&pBootTrigger);
pTrigger->Release();
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))
{
pRootFolder->Release();
pTask->Release();
CoUninitialize();
return FALSE;
}

Scheduled task creation in c++ works fine in almost all platforms except on Windows 7 32 bit for Standard User

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;
}