On a windows 2008R2 server, I have to use the native schtasks to schedule tasks. I created the below script that first deletes any old task with the ID of Watson, and then schedules it. The only issue is cosmetic. Schtasks /DELETE will give an error of:
ERROR: The system cannot find the path specified
If the task was not originally there. Not a very friendly message. I would like to do a
schtasks /QUERY /TN $name
to find out if it is currently there, and only then delete it. But my powershell skills are not up to it. I tried a TRY block, but it does not seem to work for native applications)
Any suggestions?
start-transcript -Path install.log -Append
Write-Host "schedule.ps1 Script`r`n"
$reg = Get-Item -Path "hklm:\SOFTWARE\Draper Laboratory\EGPL\GeoLibrarian"
$path = $reg.GetValue('VHDPath').ToString()
$name = "Watson"
$bin = "powershell.exe"
$trigger = "ONCE"
$ts = New-TimeSpan -Minutes 1
$time = (get-date) + $ts
$when = "{0:HH\:mm}" -f $time
$policy ="-executionpolicy Unrestricted"
$profile = "-noprofile"
$file = "$path\setup\boot-watson.ps1"
$sixtyfour = [Environment]::Is64BitProcess
Write-Host "64-Bit Powershell: "$sixtyfour
Write-Host "PowerShell Version: "$PSVersionTable.PSVersion
Write-Host "Deleting old watson task"
schtasks /DELETE /TN $name /F 2>&1 | %{ "$_" }
Write-Host "If watson was not scheduled, ignore ERROR: The system cannot find the path specified"
Write-Host "Adding new watson start-up task"
#schtasks /CREATE /TN $name /TR "$bin $policy $profile -file $file" /SC $trigger /ST $when /RU SYSTEM /RL HIGHEST 2>&1 | %{ "$_" } | Out-Host
schtasks /CREATE /TN $name /TR "$bin $policy $profile -file $file" /SC ONSTART /RU SYSTEM /RL HIGHEST 2>&1 | %{ "$_" } | Out-Host
update:
I tried to do a /query, but if the tasks is not there, that itself dumps a lot of error text.
schtasks : ERROR: The system cannot find the file specified.
At G:\wwwroot\setup\uninstall.ps1:11 char:1
+ schtasks /QUERY /TN $name | Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (ERROR: The syst...file specified.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
You can use one of the two automatic variables that indicate the last exit code:
$LASTEXITCODE
and$?
If the
schtasks /query
succeeds,$LASTEXITCODE
will be0
and$?
will be$true
On the other hand, if the
schtasks /query
call fails,$LASTEXITCODE
will contain a non-0 exit code and$?
will evaluate to$false
:Or, using
$LASTEXITCODE
:Use output redirection to
$null
to supress the error/output fromschtasks