try-catch-fail with powershell and schtasks

后端 未结 1 1693
甜味超标
甜味超标 2021-01-05 08:38

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

1条回答
  •  走了就别回头了
    2021-01-05 09:00

    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
    }
    

    0 讨论(0)
提交回复
热议问题