问题
Currently I start processes in PowerShell like this:
$proc = Start-Process notepad -Passthru
$proc | Export-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
to later on kill it like this:
$proc = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$proc | Stop-Process
The problem is that if the process died before I got to call $proc | Stop-Process
, I will get error in the PowerShell output. I need to disable this error and just get the Boolean value indicating if Stop-Process was successfully into a PowerShell script's variable. How can I get this info in PS?
回答1:
Use the $?
variable to determine the success or failure of your last executed command. Set $ErrorActionPreference
variable to decide how error output is handled per script, or use -ErrorAction
parameter to set it per command:
$proc = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$proc | Stop-Process -ErrorAction SilentlyContinue
if($?) {
#Success
Write-host $proc " Stopped Successfully"
}
else {
#Failure
#Use $error variable to retrieve the message
Write-Error $error[0]
}
来源:https://stackoverflow.com/questions/32017378/tell-if-stop-process-was-successful-or-not-in-powershell