Create a Task Schedule and check the return code in Powershell

PowerShell

 

Task Scheduler is a powerful tool. Google, for example, with Chrome, uses it as an update checker once every few hours.

If you have Chrome installed you can open up Task Scheduler and see that you have two schedules in it.

You can use it in other scenarios, like for example, as i explained in another blog post, to reduce the number of reboots in SCCM for application which require LogOff/LogOn if they have ActiveSetup implemented.

I already covered on how you create a task schedule in the above mentioned blog post, but how can you know if it executed successfully?

$user = Get-CimInstance –ClassName Win32_ComputerSystem | Select-Object UserName
$computer = $env:COMPUTERNAME
$time = (get-date).AddMinutes(1).ToString("HH:mm")
schtasks /create /s $computer /tn "MyTaskSchedule" /sc once /tr "msiexec /fus {ProductCode} /qb" /st $time /ru $user
The above code is meant to create a Task Schedule for an MSI repair on the current logged in user in 1 minute. This is named “MyTaskSchedule”
In order to wait and check if this was executed correctly (return code 0) we must adapt the code a little bit:
$user = Get-CimInstance –ClassName Win32_ComputerSystem | Select-Object UserName
$computer = $env:COMPUTERNAME
$time = (get-date).AddMinutes(1).ToString("HH:mm")
schtasks /create /s $computer /tn "MyTaskSchedule" /sc once /tr "msiexec /fus {ProductCode} /qb" /st $time /ru $user

Start-Sleep -s 90

$QueryTS = schtasks /query /tn MyTaskSchedule /v /fo list | ?{$_ -match "Last Result:\s+(.+)"}

If ($QueryTS -eq 0){
write-host "Task executed with success"
}

Let me explain a little bit. As you can see we are waiting 90 seconds in the script, because the task schedule is set to run after one minute.

Then we get the last result in the variable $QueryTS. If the result is 0 it means the repair was executed with success.

Leave a comment

Your email address will not be published. Required fields are marked *

four + 15 =