使用PowerShell从远程计算机发出请求

时间:2013-01-22 12:27:23

标签: networking powershell httpwebrequest

我正在寻找从远程计算机发出Web请求的方法。在一个网络中共享了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
        }
    }
}

1 个答案:

答案 0 :(得分:2)

使用invoke-command并将代码包装到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
        }
    }
}