Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch-fail with powershell and schtasks

I'm new to powershell, but I'm trying to output some simple logging in a ps I'm writing to create scheduled tasks. My code is below. It seems that it doesn't throw an exception when you get an error with schtasks. Another SO question mentioned this with fileIO actions and suggested doing "-ea stop" but that doesn't work with schtasks.

#create log file
$log = "\\servername\!incoming\Deploy\log.txt"
Clear-Content $log

#get input file list
$txtServerList = Gc "\\servername\!incoming\Deploy\serverlist.txt"
#loop through each server
ForEach($strServername In $txtServerList)
{
    try 
    {
        #install task from XML template
        schtasks /create /s $strServername /tn InventoryServer /XML "\\servername\!incoming\Deploy\TaskTemplate.xml"
        #run the task immediately
        schtasks /run /s $strServername /tn InventoryServer
    }
    catch [exception]
    {
       Add-Content -path $log -value $strServername
       #Add-Content -path $log -value $_.Exception
       #Add-Content -path $log -value $_.Exception.Message
       #Add-Content -path $log -value ""
    }
}

I verified that 'Add-Content -path "\servername!incoming\Deploy\log.txt" -value "test"'works, so like I said I'm fairly sure it's just not throwing an exception.

like image 807
THE JOATMON Avatar asked Feb 09 '12 18:02

THE JOATMON


1 Answers

In order for a Try/Catch to work, PowerShell needs a terminating exception. When running a cmdlet in a Try block you can make that happen by using -erroraction Stop (or use the -ea alias). As you already realize SCHTASKS.EXE can't do this. Without a terminating exception, the code in the Catch block will never run.

What you have to do is step out side the box, so to speak, and independently check if Schtasks failed. If so, they you can use Write-Error in your Try block.

One thing you might try is using Start-Process and look at the exit code. Anything other than 0 should be an error.

Try {
get-date
$p=Start-Process schtasks.exe -ArgumentList "/Create foo" -wait -passthru
if ($p.exitcode -ne 0) {
    write-error "I failed with error $($p.exitcode)"
}
}

Catch {
"oops"
$_.Exception
}
like image 64
Jeffery Hicks Avatar answered Sep 21 '22 17:09

Jeffery Hicks