Try-catch-fail with powershell and schtasks

I'm new to powershell, but I'm trying to output some simple ps entries that I write to create scheduled tasks. My code is below. This does not seem to throw an exception when you get an error message with schtasks. Another SO question mentioned this with fileIO actions and suggested doing "-ea stop", but this does not 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 checked that "Add-Content -path" \ servername! incoming \ Deploy \ log.txt "-value" test "works, so, as I said, I'm sure it just does not throw an exception.

+6
source share
1 answer

For Try / Catch to work, PowerShell needs a final exception. When you run the cmdlet in the Try block, you can do this using -erroraction Stop (or use the -ea alias). As you already understand, SCHTASKS.EXE cannot do this. Without a final exception, the code in the Catch block will never run.

What you need to do is go out of the box, so to speak, and independently check if Schtasks has worked. If so, you can use Write-Error in your Try block.

One thing you can try is to use the Start-Process and see the exit code. Any error other than 0 must 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 } 
+9
source

Source: https://habr.com/ru/post/908069/


All Articles