2013-02-24 29 views
1

我想編寫一個簡單的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 
} 

感謝

回答

2

這將評估爲true,如果該進程不存在:

(Get-Process -name Tvnserver.exe -ErrorAction SilentlyContinue) -eq $null 

,或者如果你想改變它你可以否定聲明如下:

-not ($(Get-Process -name Tvnserver.exe -ErrorAction SilentlyContinue) -eq $null) 

有一個-ErrorAction SilentlyContinue以避免在進程不存在時拋出任何錯誤,這一點很重要。

+1

對於否定條件,只需將'-eq $ null'更改爲'-ne $ null'。 – 2013-02-24 18:19:09

+0

好的,它的工作原理!非常感謝! – Daniel4711 2013-02-25 12:18:14

+0

不客氣。 – 2013-02-25 12:32:03

3

Get-Process不返回布爾值,並且進程名稱沒有擴展名列出,這就是爲什麼你的代碼不起作用。刪除擴展,要麼檢查,如果結果是$nullMusaab Al-Okaidi建議,或結果轉換爲布爾值:

if ([bool](Get-Process Tvnserver -EA SilentlyContinue)) { 
    # do some 
} else { 
    # do other 
} 

如果您不希望腳本在做任何事情的情況下該進程沒有運行:只需省略else分支。