2016-07-27 136 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-杰森。你的建议对我有用。 –