处理多个服务器的服务状态脚本,几乎相似的服务名称,无法正常工作

时间:2016-09-23 16:18:25

标签: powershell

我有一个脚本,它将查询服务器列表以查找特定服务是否正在运行。服务器上的服务名称具有共同的前缀,因此使用" SAM *"

如果仅适用于1台服务器,这样可以正常工作,但是如果它超过2则结果没有任何价值,并且代码运行与服务器数量相同的数字时间。这方面的一些专业知识..我是新的脚本

$machineName = get-content -path "C:\serverlist.txt"


foreach ($machine in $machineName) { 

     $serviceStatus = get-service -ComputerName $machineName -Name "SAM*"

     if ($serviceStatus.status -eq "Running") {

         Write-Host $machineName `t $serviceStatus.name `t $serviceStatus.status 
         $svcName = $serviceStatus.name 
         $svcState = $serviceStatus.status

     } else { 
         Write-Host $machineName `t $serviceStatus.name `t $serviceStatus.status 
         $svcName = $serviceStatus.name 
         $svcState = $serviceStatus.status

     }           

   } 

2 个答案:

答案 0 :(得分:0)

您正在循环中调用完整集合$ machinename而不是单个$ machine。

$machineName = get-content -path "C:\serverlist.txt"


foreach ($machine in $machinename) { 

 $serviceStatus = get-service -ComputerName $machine -Name "SAM*"

 if ($serviceStatus.status -eq "Running") {

     Write-Host $machine `t $serviceStatus.name `t $serviceStatus.status 
     $svcName = $serviceStatus.name 
     $svcState = $serviceStatus.status

 } else { 
     Write-Host $machine `t $serviceStatus.name `t $serviceStatus.status 
     $svcName = $serviceStatus.name 
     $svcState = $serviceStatus.status

 }           

} 

编辑:或者,您可以更改列表的变量名称,然后更改单个对象

$machineList = get-content -path "C:\serverlist.txt"


foreach ($machinename in $machineList) { 

答案 1 :(得分:0)

请在代码中将$ machineName更改为$ machine,如下所示:

$serviceStatus = get-service -ComputerName $machine -Name "SAM*"