Make a request from a remote computer using PowerShell
I am looking for a way to make a web request from a remote computer. There are 10 servers on the same network and I need to make a web request from each server, for example to "http://google.com". So I'm going to use PowerShell and started writing a script. But I don't know how to make a request on behalf of 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
}
}
}
+3
source to share
1 answer
use invoke-command and wrap your code in sciptblock like:
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
}
}
}
+2
source to share