2016-07-27 150 views
0

我搜索並放在一起的PowerShell腳本來檢查服務器列表中是否運行Windows服務(SNARE)。此時,如果腳本沒有錯誤,腳本將打印「Snare正在運行」,如果遇到錯誤,腳本會顯示「未安裝/關閉」。我還在尋找的是,如果腳本不會以錯誤結尾,我能以某種方式獲取狀態的輸出(下例)並打印「Snare is stopped」?基本輸出重定向

Status Name    DisplayName 
------ ----    ----------- 
Stopped SNARE    SNARE
#Powershell 
$serverList = gc Final.txt 
$collection = $() 
foreach ($server in $serverList) { 
    $status = @{ 
    "ServerName" = $server 
    "TimeStamp" = (Get-Date -f s) 
    } 
    if (Get-Service -Name SNARE -ComputerName $server -EA SilentlyContinue) { 
    $status["Results"] = "Snare is running" 
    } else { 
    $status["Results"] = "Not installed/Powered off" 
    } 
    New-Object -TypeName PSObject -Property $status -OutVariable serverStatus 
} 

回答

1

Get-Service輸出分配給一個變量,並抓住​​從該Status屬性:

if (($snare = Get-Service -Name SNARE -ComputerName $server -EA SilentlyContinue)) 
{ 
    $status["Results"] = "Snare is running" 
    $status["Status"] = $snare.Status 
} 
else 
{ 
    $status["Results"] = "Not installed/Powered off" 
    $status["Status"] = "Unknown" 
} 
+0

謝謝@馬蒂亞斯-R-傑森。你的建議對我有用。 –