3

我正在寻找一种从远程计算机发出网络请求的方法。一个网络中有 10 台服务器共享,我需要从每台服务器发出 Web 请求,例如向“http://google.com”发出请求。因此,我将使用 PowerShell 并开始编写脚本。但我不知道如何代表 server1、server2.. server10 发出请求

$hosts = @("server1Ip", "server2Ip", ..,"server10Ip");
$url = "http://google.com"
$hLen = $hosts.Length;

for ($i=0; $i -lt $hLen; $i++)
{
    try 
    {
        Write-Host "Pinging web address for server: $url ..."
        $request = [System.Net.WebRequest]::Create($url)
        $response = $request.GetResponse()
        Write-Host "Web Request Succeeded."   
    } catch 
    {
        Write-Host ("Web Request FAILED!!! The error was '{0}'." -f $_)
    } finally 
    {
        if ($response) 
        {
            $response.Close()
            Remove-Variable response
        }
    }
}
4

1 回答 1

3

使用调用命令并将您的代码包装到 sciptblock 中,例如:

icm -computername $hosts -scriptBlock{
try 
    {
        Write-Host "Pinging web address for server: $url ..."
        $request = [System.Net.WebRequest]::Create("http://google.com")
        $response = $request.GetResponse()
        Write-Host "Web Request Succeeded."   
    } catch 
    {
        Write-Host ("Web Request FAILED!!! The error was '{0}'." -f $_)
    } finally 
    {
        if ($response) 
        {
            $response.Close()
            Remove-Variable response
        }
    }
}
于 2013-01-22T12:40:37.960 回答