问题描述
目前,我在PowerShell中启动的过程如下:
Currently I start processes in PowerShell like this:
$proc = Start-Process notepad -Passthru
$proc | Export-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
稍后再杀死它:
$proc = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$proc | Stop-Process
问题是,如果进程在调用$proc | Stop-Process
之前就死了,那么PowerShell输出中将出现错误.我需要禁用此错误,而只是获取一个布尔值,该值指示Stop-Process是否已成功放入PowerShell脚本的变量中.如何在PS中获取此信息?
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?
推荐答案
使用$?
变量确定最后执行的命令的成功或失败.设置$ErrorActionPreference
变量以决定每个脚本如何处理错误输出,或者使用-ErrorAction
参数根据每个命令进行设置:
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]
}
这篇关于判断Stop-Process在PowerShell中是否成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!