I have error with type of pEventTrigger variable.
If someone has more implementation, it will be nice solution too.
The result I want to achieve is to have event viewer task in task scheduler, which must have the highest elevation and run program in custom path as action.
void TaskScheduler::RegisterTask(std::string eventID) {
HRESULT hr;
ITriggerCollection* pTriggerCollection = nullptr;
ITaskDefinition* pTask = nullptr;
IRegistrationInfo* pRegInfo = nullptr;
IEventTrigger* pEventTrigger = nullptr;
// Create a new task definition
hr = pService->NewTask(0, &pTask);
if (FAILED(hr)) {
logger.log("Failed to create task definition with HRESULT: 0x", hr);
throw std::runtime_error("Failed to create task definition.");
}
// Get the registration info
hr = pTask->get_RegistrationInfo(&pRegInfo);
if (FAILED(hr)) {
logger.log("Failed to get registration info with HRESULT: 0x", hr);
throw std::runtime_error("Failed to get registration info.");
}
// Set task description and author
pRegInfo->put_Description(_bstr_t(L"Task to monitor Event ID 106"));
pRegInfo->put_Author(_bstr_t(L"Author"));
// Get the trigger collection
hr = pTask->get_Triggers(&pTriggerCollection);
if (FAILED(hr)) {
logger.log("Failed to get trigger collection with HRESULT: 0x", hr);
throw std::runtime_error("Failed to get trigger collection.");
}
// Create an event trigger
hr = pTriggerCollection->Create(TASK_TRIGGER_EVENT, &pEventTrigger);
if (FAILED(hr)) {
logger.log("Failed to create event trigger with HRESULT: 0x", hr);
throw std::runtime_error("Failed to create event trigger.");
}
// Set the subscription for the event trigger
hr = pEventTrigger->put_Subscription(_bstr_t(("*[System[EventID=" + eventID + "]]").c_str()));
if (FAILED(hr)) {
logger.log("Failed to put_Subscription with HRESULT: 0x", hr);
throw std::runtime_error("Failed to set event subscription.");
}
// Set the trigger type to event log
hr = pEventTrigger->put_Type(TASK_TRIGGER_EVENTLOG);
if (FAILED(hr)) {
logger.log("Failed to set trigger type to event log with HRESULT: 0x", hr);
throw std::runtime_error("Failed to set trigger type to event log.");
}
// Register the task
hr = pRootFolder->RegisterTaskDefinition(_bstr_t(L"YourTaskName"), pTask, TASK_CREATE_OR_UPDATE, _variant_t(), _variant_t(), TASK_LOGON_INTERACTIVE_TOKEN, _variant_t(), NULL);
if (FAILED(hr)) {
logger.log("Failed to RegisterTaskDefinition with HRESULT: 0x", hr);
throw std::runtime_error("Failed to register task.");
}
}
New contributor
Roman Karchikyan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.