Powershell获取进程查询
问题描述:
我想编写一个简单的If语句来检查一个进程是否存在。 如果存在,应该开始。Powershell获取进程查询
这样,但工作..;)
If ((Get-Process -Name Tvnserver.exe) -eq $True)
{
Stop-Process tnvserver
Stop-Service tvnserver
Uninstall...
Install another Piece of Software
}
Else
{
do nothing
}
感谢
答
这将评估为true,如果该进程不存在:
(Get-Process -name Tvnserver.exe -ErrorAction SilentlyContinue) -eq $null
,或者如果你想改变它你可以否定声明如下:
-not ($(Get-Process -name Tvnserver.exe -ErrorAction SilentlyContinue) -eq $null)
有一个-ErrorAction SilentlyContinue
以避免在进程不存在时抛出任何错误,这一点很重要。
答
Get-Process
不返回布尔值,并且进程名称没有扩展名列出,这就是为什么你的代码不起作用。删除扩展,要么检查,如果结果是$null
为Musaab Al-Okaidi建议,或结果转换为布尔值:
if ([bool](Get-Process Tvnserver -EA SilentlyContinue)) {
# do some
} else {
# do other
}
如果您不希望脚本在做任何事情的情况下该进程没有运行:只需省略else
分支。
对于否定条件,只需将'-eq $ null'更改为'-ne $ null'。 – 2013-02-24 18:19:09
好的,它的工作原理!非常感谢! – Daniel4711 2013-02-25 12:18:14
不客气。 – 2013-02-25 12:32:03