简体   繁体   English

Powershell Foreach对象的用法

[英]powershell Foreach-Object usage

I have script: 我有脚本:

$servers = "server01", "s02", "s03"

foreach ($server in $servers) {

$server = (New-Object System.Net.NetworkInformation.Ping).send($servers)
if ($server.Status -eq "Success") {
Write-Host "$server is OK"
}
}

Error message: 错误信息:

An exception occured during a Ping request.

I need to ping each server in $servers array and display status. 我需要对$ servers数组中的每个服务器执行ping操作并显示状态。 I think, that Foreach statement is not properly used, but I'm unable to find out where is the problem. 我认为,Foreach语句未正确使用,但我无法找出问题出在哪里。 Thank you for your advice 感谢您的意见

You should not be modifying the value of $server within the foreach loop. 您不应在foreach循环中修改$server的值。 Declare a new variable (eg $result ). 声明一个新变量(例如$result )。 Also, Ping.Send takes the individual server name, not an array of server names as an argument. 同样, Ping.Send将单个服务器名称而不是服务器名称数组作为参数。 The following code should work. 下面的代码应该工作。

Finally, you will need to trap the PingException that will be thrown if the host is unreachable, or your script will print out a big red error along with the expected results. 最后,您将需要捕获如果主机不可访问会引发的PingException,否则您的脚本将打印出一个红色的大错误以及预期的结果。

$servers = "server1", "server2"

foreach ($server in $servers) {
   & {
       trap [System.Net.NetworkInformation.PingException] { continue; }
       $result = (New-Object System.Net.NetworkInformation.Ping).send($server)
       if ($result.Status -eq "Success") {
         Write-Host "$server is OK"
       }
       else {
         Write-Host "$server is NOT OK"
       }
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM