基本输出重定向

时间:2016-07-27 11:58:40

标签: powershell

我搜索并整理了一个PowerShell脚本,以检查服务器列表中的Windows服务(SNARE)是否正在运行。目前,脚本打印" Snare正在运行"如果它没有错误和"未安装/关闭电源"如果遇到错误。我也在寻找的是如果脚本没有错误结束,我可以以某种方式获取状态的输出(下面的示例)并打印" Snare停止"?

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 个答案:

答案 0 :(得分: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"
}