11 min read
At the end of this Invoke-WebRequest PowerShell proxy guide, you will know:
Let’s dive in!
In this guide, you will learn how to use the invoke-command to execute PowerShell commands and scripts on remote computers.
Table of contents:
Let’s get started.

Using a proxy with Invoke-WebRequest ensures that my requests appear to come from the proxy server’s IP address, adding a layer of privacy and protection. This guide will show you how to use Invoke-WebRequest with a proxy, step by step.
I’m trying to capture the contents of the warning stream when I do an invoke-command and can’t seem to get it – everything I do, the warning goes through to the console instead of into my variable.
Here’s the basic snippet to start with:
Invoke-Command -ComputerName $remoteServer { Write-Warning 'Test'
}as expected, this yields
WARNING: Testbut then I try to intercept and nothing works:
Do you want to run a PowerShell command on a remote computer or server? Then you don’t need to open a remote desktop connection, because you can just use the PowerShell Invoke-Command for that.
Invoke-Command allows you to run PowerShell commands and scripts on one or more remote computers. while redirecting the results to your own console. This makes it a great cmdlet to manage remote devices quickly.
In this article
In this article, we are going to take a look at what is required to use Invoke-Command and how to use the cmdlet.
Prerequisites to Get Started with a Proxy in PowerShell
A proxy acts as an intermediary between a client and the destination server. It intercepts your requests, forwards them to the server, receives the responses from the server, and sends them back to you. This way, the destination server will see the requests as coming from the IP and location of the chosen proxy server and not from you.
To get started using a PowerShell proxy with Invoke-WebRequest, you need to understand what a proxy server URL looks like.
This is the URL of a PowerShell Invoke-WebRequest proxy:
<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]That consists of:
- <PROTOCOL>: The protocol to use to connect to the proxy server.
- <HOST>: The IP address or URL of the proxy server’s hostname.
- <PORT>: The port number the proxy server listens to.
- <USERNAME>: The optional username to specify when proxy authentication is required.
- <PASSWORD>: The optional password to specify when proxy authentication is required.
Invoke-WebRequest : This operation is not supported for a relative URI.
As for proxy protocols, the most popular ones are HTTP, HTTPS, and SOCKS. Invoke-WebRequest in PowerShell 5.1 only supports HTTP while in PowerShell 7.x it also supports HTTPS and SOCKS.
Time to retrieve a valid HTTP proxy!
You can find one for free online, as below:
Protocol: HTTP; IP Address: 190.6.23.219; Port: 999http://190.6.23.219:999Warning
Opting for free proxies is okay for learning purposes, but you cannot rely on them in real-world scenarios. Free proxies are unreliable, error-prone, slow, data-greedy, and short-lived. Do not use them!
The solution? Premium proxies from Bright Data, the best provider in the market. Subscribe and try our reliable proxies for free.
http://admin-4521:@rUuH3tJqf45.103.203.109:9571
131 times
I have a windows service(.net framework) project where I am running a powershell script. When I run the same code in the console app, there is no problem. but here I get the error “The type arguments for method ‘PowerShell.Invoke()’ cannot be inferred from the usage. Try specifying the type arguments explicitly.”
{ private Thread workerThread; private bool running; private static readonly ILog log = LogManager.GetLogger(typeof(Service1)); public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { running = true; workerThread = new Thread(WorkerThreadProc); workerThread.Start(); } protected override void OnStop() { running = false; workerThread.Join(); } private static void WorkerThreadProc() { bool running = true; using (var runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); while (running) { try { string powerShellCommand = "Get-Process"; string output = RunPowerShellCommand(powerShellCommand); string directoryPath = @"C:\HttpConnector\Output"; string fileName = "PsOutput.txt"; string filePath = Path.Combine(directoryPath, fileName); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } WriteToFile(filePath, output); } catch (Exception ex) { log.Error("Hata oluştu.", ex); } TimeSpan interval = TimeSpan.FromMinutes(1); Thread.Sleep(interval); } runspace.Close(); } } private static string RunPowerShellCommand(string command) { using (var runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); using (var ps = PowerShell.Create()) { ps.Runspace = runspace; ps.AddScript(command); try { var results = ps.Invoke(); var output = GetObjectInfo(results); return output; } catch (Exception ex) { log.Error("Hata oluştu: " + ex.ToString()); return string.Empty; } } } } private static string GetObjectInfo(Collection<PSObject> psObjects) { string output = string.Empty; foreach (var psObject in psObjects) { output += $"{psObject.ToString()}{Environment.NewLine}"; } return output; }```
Added;
Microsoft.PowerShell.SDK
System.Management.Automationasked Jul 18, 2023 at 5:30
Load 6 more related questions
Show fewer related questions
How To Use HTTPS and SOCKS Proxies in PowerShell
If you need to use an HTTPS or SOCKS proxy, you must upgrade to version 7.x+ of PowerShell. Otherwise, Invoke-WebRequest will fail with:
Invoke-WebRequest : The ServicePointManager does not support proxies with the https scheme.
Or in the case of a SOCKS proxy:
Invoke-WebRequest : The ServicePointManager does not support proxies with the socks scheme.
When dealing with HTTPS or SOCKS proxies in PowerShell 7.x, the Invoke-WebRequest command structure remains the same:
Invoke-WebRequest -Proxy "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]" <Uri>What changes is that <PROTOCOL> will be https, socks4, socks4a, socks5, or socks5a, instead of http.
If you try to invoke a request with a proxy involving a protocol other than those mentioned above, you will get this error:
Invoke-WebRequest: Only the 'http', 'https', 'socks4', 'socks4a' and 'socks5' schemes are allowed for proxies.Thus, a complete example of an Invoke-WebRequest SOCKS proxy request is:
Invoke-WebRequest -Proxy "socks5://94.14.109.54:3567" "http://httpbin.org/ip"
As you can expect, the result will be:
StatusCode : 200
StatusDescription : OK
Content : {
"origin": "94.14.109.54"
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 31
Content-Type: application/json
Date: Thu, 01 Feb 2024 12:47:56 GMT...
Forms : {}
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials,
true], [Content-Length, 31]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 31Installing Invoke-WebRequest
To use Invoke-WebRequest, you need PowerShell. So, let’s learn how to install PowerShell and get access to the Invoke-WebRequest cmlet!
Windows
You can verify the current version of PowerShell installed on your Windows machine with this command:
$PSVersionTableOn PowerShell 7.x, that should print something similar to:
PSVersion 7.4.1
PSEdition Core
GitCommitId 7.4.1
OS Microsoft Windows 10.0.22631
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0macOS and Linux
Debugging Proxy Issues
Sometimes, requests through a proxy server might fail. Debugging these issues requires examining the detailed response and error messages. You can use the -Debug parameter with Invoke-WebRequest to get more information:
$proxy = "http://proxyserver:8080"
$response = Invoke-WebRequest -Uri "http://example.com" -Proxy $proxy -Debug
Write-Output $response.ContentThe debug output provides additional details about the request process, which can help identify and resolve issues.
Using the Invoke-Command
The Invoke-Command in PowerShell allows you to run a command or script on a remote computer. When you need to run multiple commands on a remote computer, then it’s better to use the New-PSSession cmdlet.
The structure of the Invoke-Command is pretty straightforward, but nevertheless, there are still quite a few options (parameters) that we can use:
| Parameter | Description |
|---|---|
| ComputerName | Computername or IP Address to run the command on. For multiple computer, separate the names with a comma , |
| Credential | Credentials to connect to remote computer |
| FilePath | Specifies the path to a local script to run on the remote computer(s) |
| AsJob | Run the remote command as background job on the local computer |
| InDisconnectedSession | Used to run the command in a disconnected session on the remote computer |
| ScriptBlock | Script or command to run |
| ArgumentList | Used to pass arguments to the cmdlet in the scriptblock |
Invoke-Command -ComputerName la-srv-dc01 {Get-ComputerInfo}
This will run the command Get-ComputerInfo on the domain controller (la-srv-dc01) and return the results to the console.
Running a Script
The example below works fine, but it’s a bit harder to read this way:
Invoke-Command -ComputerName la-srv-dc01 -ScriptBlock {Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID, MediaType, @{Name="FreeSpace (GB)"; Expression={"{0:N2}" -f ($_.FreeSpace / 1GB)}}}$script = { Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID, MediaType, @{Name="FreeSpace (GB)"; Expression={"{0:N2}" -f ($_.FreeSpace / 1GB)}}
}
Invoke-Command -ComputerName la-srv-dc01 -ScriptBlock $scriptThe third option is to store the script on your local computer and refer to the script using the -FilePath parameter:
Invoke-Command -ComputerName la-srv-dc01 -FilePath c:\test\diskInfo.ps1
Run on Multiple Computers
One of the big advantages of the Invoke-Command cmdlet in PowerShell is that you can also run it on multiple computers simultaneously. There are a couple of options to do this, we can simply specify the computer names separated by a comma:
Invoke-Command -ComputerName la-srv-dc01, la-srv-app01, la-srv-file01 -FilePath c:\test\diskInfo.ps1
Another option to write this is to use a hashtable and splatting. Splatting the parameters will make your script easier to read when you need to add a lot of properties.
$parameters = @{ ComputerName = 'la-srv-dc01', 'la-srv-app01', 'la-srv-file01', 'la-win11-lab03' ScriptBlock = { Get-ComputerInfo } }
Invoke-Command @parametersWhen you need to run a command on many computers, let’s say a hundred or more, then you want to minimize the load on your local computer. For this, we can use the InDisconnectedSession parameter.
If you run the Invoke-Command cmdlet normally, then your local computer will connect to the remote computer, start the script, wait for the results, and disconnect. The waiting parts consume the most time and resources from your local computer, especially when connecting to 100 or more computers.
With the InDisconnectedSession parameter, the cmdlet will only connect to the remote computer, start the script, and then disconnect. This reduces the whole process time significantly.
$parameters = @{ ComputerName = (Get-Content -Path C:\Test\Servers.txt) InDisconnectedSession = $true FilePath = '\\lazyadmin\scripts\InstallWinUpdates.ps1'
}
Invoke-Command @parametersUsing Credentials
You will need to have permission on the remote computer to run the PowerShell commands. When running the command on a server you probably won’t have the correct permission from your local workstation.
Invoke-Command -ComputerName la-srv-dc01 -Credential lazyadmin\administrator -Scriptblock {Get-ComputerInfo}Just like with most PowerShell cmdlets, you can also pass a credential object to the -Credential cmdlet. This method is especially handy when you want to run multiple commands or need to run different commands on different remote computers:
$cred = Get-Credential
Invoke-Command -ComputerName la-srv-dc01 -Credential $cred -Scriptblock {Get-ComputerInfo}Include Local Variables
$path = "c:\test"
Invoke-Command -ComputerName la-srv-dc01 -Scriptblock {Get-Childitem -Path $path}The example above isn’t going to work. The remote computer, in this case la-srv-dc01, doesn’t know what the variable $path is, so it won’t return any results.
$path = "c:\test"
Invoke-Command -ComputerName la-srv-dc01 -Scriptblock {Get-Chiditem -Path $Using:path}What Is PowerShell Invoke-WebRequest?
Invoke-WebRequest is a PowerShell cmdlet for sending HTTP, HTTPS, and FTP requests to web servers and web services. By default, it automatically parses the response produced by the server and returns collections of forms, links, images, or other significant HTML elements.
Usually, it is used for accessing REST APIs, downloading files from the web, or interacting with web services. This is the basic syntax of an Invoke-WebRequest request:
Invoke-WebRequest [-Uri] <Uri> [-Method <WebRequestMethod>] [-Headers <IDictionary>] [-Body <Object>]The key parameters to remember are:
- -Uri: The URI of the web resource to which the request is sent.
- -Method: The HTTP method to use for the request (e.g., GET, POST, PUT, DELETE). Invoke-WebRequest sends GET requests by default.
- -Headers: The additional HTTP headers to include in the request.
- -Body: The body of the request to send to the server.
As you can see, the only required argument is <Uri>. Thus, in short, the simplest syntax to perform a GET request to a given URI is:
Invoke-WebRequest <Uri>This cmdlet was introduced in PowerShell 3.0, in 2012.
Setting Up a Proxy with Invoke-WebRequest
When using a proxy with Invoke-WebRequest, specify the proxy server details. PowerShell makes this easy with the -Proxy and -ProxyCredential parameters.
WarningVariable
$warnings = $null
$output = Invoke-Command -ComputerName $remoteServer { Write-Warning 'Test'
} -WarningVariable $warningsWARNING: Testis emitted into the console, and $warnings is empty.
Which PowerShell Proxy Should You Use?
The type of proxy you should use depends on your needs:
Residential proxies: Offer genuine IP addresses from real devices for high anonymity.
ISP proxies: Provide static IPs from devices registered with ISPs, suitable for SEO monitoring and market research.
Mobile proxies: Provide IPs from real mobile devices for high anonymity.
Basics of Invoke-WebRequest
Before diving into the proxy configuration, let’s review the basic usage of Invoke-WebRequest. This cmdlet is straightforward for making web requests. Here’s a simple example of how to use it:
$response = Invoke-WebRequest -Uri "http://example.com"
Write-Output $response.ContentIn this example, Invoke-WebRequest sends a GET request to “http://example.com” and stores the response in the $response variable. The content of the response is then output using Write-Output.
What is PowerShell Invoke-WebRequest?
However, direct web access may be restricted in some environments, requiring a proxy server. This guide will walk you through the steps to use Invoke-WebRequest with a proxy in PowerShell.
How to Specify an HTTP Proxy in Invoke-WebRequest
Before getting started, launch the command below in PowerShell:
Invoke-WebRequest "https://httpbin.org/ip"
That should print something like:
StatusCode : 200
StatusDescription : OK
Content : {
"origin": "194.34.233.12"
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 32
Content-Type: application/json
Date: Thu, 01 Feb 2024 10:46:14 GMT...
Forms : {}
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials,
true], [Content-Length, 32]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 32Focus on the Content field. That will contain your IP.
Why? Because the /ip endpoint from the HTTPBin project returns the origin IP of the request. In other words, it returns the IP address of the machine that performed the request. In this case, that is your machine’s IP.
If you want to access only the Content field, you can do it with:
$response = Invoke-WebRequest "https://httpbin.org/ip"
$response.Content
This would print:
{
"origin": "194.34.233.12"
}If you route that request through a proxy, you should see the IP address of the proxy server and not yours. Calling that endpoint is therefore a good test to verify that the specified PowerShell Invoke-WebRequest proxy is working as expected.
There are a couple of ways to set a PowerShell proxy in Invoke-WebRequest. Find out more in the step-by-step guided sections below!
Using a Command Line Option
Invoke-WebRequest offers the -Proxy flag to specify a proxy URL for your request.
So, the syntax to use Invoke-WebRequest with a proxy server becomes:
Invoke-WebRequest -Proxy "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]" <Uri>If you now execute this PowerShell command:
Invoke-WebRequest -Proxy "http://190.6.23.219:999" "https://httpbin.org/ip"
Invoke-WebRequest -Uri "http://httpbin.org/ip" -Proxy "http://brd.superproxy.io:22225" -ProxyCredential (New-Object System.Management.Automation.PSCredential("brd-customer-CUSTOMER_ID-zone-ZONE’S_NAME", ("ZONE’S_PASSWORD" | ConvertTo-SecureString -AsPlainText -Force)))
The result should be:
StatusCode : 200
StatusDescription : OK
Content : {
"origin": "190.6.23.219"
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 31
Content-Type: application/json
Date: Thu, 01 Feb 2024 12:36:56 GMT...
Forms : {}
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials,
true], [Content-Length, 31]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 31Notice that the origin in Content matches the proxy server IP. This proves that the target server sees the request as coming from the proxy, as expected. Awesome!
Note: Do not forget that free proxies are short-lived! By the time you read this guide, it is unlikely that the above server is still alive. In case of an error, replace it with a fresh proxy.
Using Environment Variables
Since PowerShell 7.0, Invoke-WebRequest supports proxy configuration via environment variables.
- HTTP_PROXY:The URL of the proxy server to use in case of HTTP requests.
- HTTPS_PROXY: The URL of the proxy server to use in case of HTTPS requests.
On Windows, you can set the two environment variables with this PowerShell syntax:
$env:HTTP_PROXY = "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]"
$env:HTTPS_PROXY = "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]"In our example, the commands will become:
$env:HTTP_PROXY = "http://190.6.23.219:999"
$env:HTTPS_PROXY = "http://190.6.23.219:999"On macOS and Linux, you need to use the syntax below:
export HTTP_PROXY="<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]"
export HTTPS_PROXY="<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]"So, the two commands will be:
export http_proxy="http://190.6.23.219:999"
export https_proxy="http://190.6.23.219:999"From now on, every Invoke-WebRequest request will go through the specified proxies without having to add the -Proxy option. After setting the envs, launch the command below:
Invoke-WebRequest "https://httpbin.org/ip"
You will get the same result as before:
StatusCode : 200
StatusDescription : OK
Content : {
"origin": "190.6.23.219"
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 31
Content-Type: application/json
Date: Thu, 01 Feb 2024 12:36:56 GMT...
Forms : {}
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials,
true], [Content-Length, 31]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 31To turn off the Invoke-WebRequest proxies, unset the environment variables with:
$env:HTTP_PROXY = ""
$env:HTTPS_PROXY = ""
Or on macOS and Linux:
unset HTTP_PROXY
unset HTTPS_PROXYInvoke-WebRequest will go back to its standard behavior, and https://httpbin.org/ip will now expose your IP.
Tips and Tricks You Need to Know
See some useful tricks and valuable tips for dealing with a PowerShell Invoke-WebRequest proxy like a pro.
Ignore the PowerShell Proxy Configuration
Invoke-WebRequest -NoProxy <Uri>
This instructs Invoke-WebRequest to contact <Uri> without using a proxy.
To verify that this approach works, set up a proxy in the envs and run:
Invoke-WebRequest -NoProxy "https://httpbin.org/ip"The resulting origin will contain your IP, not that of the proxy server.
Avoid SSL Certificate ErrorsWhen using HTTP proxies, your requests may fail because of SSL certificate errors. To avoid that, specify the -SkipCertificateCheck option:
Invoke-WebRequest -SkipCertificateCheck -Proxy "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]" <Uri>-SkipCertificateCheck helps you avoid certificate errors by allowing insecure server connections. Keep in mind that using this parameter is not secure. Set it only when dealing with known hosts.
For example, you can contact HTTPBin through a proxy while bypassing SSL issues with:
Invoke-WebRequest -SkipCertificateCheck -Proxy "http://190.6.23.219:999" "https://httpbin.org/ip"Wrapping Up
The PowerShell Invoke-Command is a great tool to manage remote computers. It allows you to quickly execute a command without the need to open a remote desktop. Especially when you need to run the command on multiple computers at once.
Make sure that you also look at the New-PSSession cmdlet, this is really a better option when you need to execute multiple commands on a remote computer.
I hope you found this article helpful, if you have any questions, just drop a comment below.
Proxy with Credentials
If your proxy server requires authentication, you need to provide credentials. PowerShell’s Get-Credential cmdlet is handy for this purpose. Here’s how you can include proxy authentication:
$proxy = "http://proxyserver:8080"
$proxyCredentials = Get-Credential
$response = Invoke-WebRequest -Uri "http://example.com" -Proxy $proxy -ProxyCredential $proxyCredentials
Write-Output $response.ContentWhat is a Proxy Server?
A proxy server acts as an intermediary between your computer and the internet. When you send a request to access a website, the proxy server intercepts it, forwards the request on your behalf, receives the response from the website, and then sends it back to you. This can be useful for various reasons:
- Privacy: Hides your IP address from the websites you visit.
- Security: Can filter out malicious sites or content.
- Access Control: Restricts access to certain websites.
- Performance: Caches frequently accessed content to improve speed.
Redirection
$output = Invoke-Command -ComputerName $remoteServer { Write-Warning 'Test'
} 3>&1WARNING: Testis emitted into the console, and $output is empty.
Handling Proxy Bypass
In some scenarios, you might want to bypass the proxy for certain addresses or websites. This can be achieved by configuring the proxy bypass list. Here’s how to do it:
In this example, requests to “http://example.com” will bypass the proxy server, while all other requests will use the proxy.
Invoke-Command Requirments
Before you can use the invoke-command the remote computer must have:
- The Windows Remote Management service must be running
- Allow Windows Remote Management in the Windows Firewall
In the next section, I’ll walk through how to enable this for multiple computers by using group policy.
You can add these settings to an existing GPO or create a new GPO. In this example, I’ll create a new GPO.
2. Edit the GPO and navigate to Computer Configuration -> Windows Settings -> Security Settings -> System Services

3. Select the Windows Remote Management (WS-Management) and set the service startup mode to Automatic.

4. Navigate to Computer Configuration -> Windows Settings -> Security Settings -> Windows Defender Firewall with Advanced Security
5. Right-click on inbound rule and select “New Rule”

On the rule type screen select predefined and select “Windows Remote Management” then click Next.

Select the “Domain, Private” profile and uncheck the Public profile. Click Next

Select “Allow the connection” and click Finish
Tip: For security reasons, I recommend only allowing specific authorized computers to use PowerShell commands remotely. You can limit this by using the scope settings on the firewall rule. In the remote IP address section list the IP address of your computer or any other computer you want to allow.

That completes the GPO settings.
6. Run gpupdate or Reboot Computer
Next, the remote computers need their policies refreshed to pull down the new GPO. They will get refreshed every 90 minutes on their own but to force a refresh run gpupdate on the computer. This will start the Windows Remote Management service and add the firewall rule on the remote computers.

Now I’ll check the services and firewall.

The service is now running.

The Firewall rule is added.
Here are some examples of using the PowerShell invoke-command.
Example 1: Get services on a remote computer
invoke-command -ComputerName pc1 -scriptblock {Get-Service} 
Example 2: Get services on multiple computers
To run PowerShell commands on multiple remote computers just separate them by a comma. You can use hostname or IP address.
invoke-command -ComputerName pc1, srv-vm1 -scriptblock {Get-Service} 
Example 3. Run a Script on a Remote Computer
This example will run getinfo.ps1 script on remote computers pc1 and srv-vm1.
Invoke-Command -FilePath c:\scripts\getinfo.ps1 -ComputerName pc1, srv-vm1Example 4: Get Windows Version on a Remote Computer
Use the systeminfo command to get the Windows version info from remote computers.
invoke-command -ComputerName pc1 -scriptblock {systeminfo} 
Example 5: Run commands on all computers from a text file
If you have a large list of computers you can put them in a text file. For example, I have a list of computers in a file called computers.txt.
Invoke-Command -ComputerName (Get-Content c:\it\computers.txt) -scriptblock {systeminfo}Example 6: Set Credentials
If the computer is in a different security context you may need to specify credentials.
$Credential = Get-Credential
Invoke-Command -ComputerName pc1 -Credential $Credential -ScriptBlock { Get-service}Example 7: Get Event Logs from Remote Computer
In this example, I’ll get event ID 4624 from a remote computer
invoke-command -ComputerName pc1 -scriptblock {Get-WinEvent @{logname='security';ID=4624} -MaxEvents 5}
Example 8: Get the PowerShell Version
This example will get the PowerShell version on remote computers
Invoke-Command -ComputerName pc1, srv-vm1 -ScriptBlock {$PSVersionTable.PSVersion}
Example 9: Run Multiple Commands
In this example, I’m running get-process and get-service on the remote computer.
Invoke-Command -ComputerName pc1 -ScriptBlock {(get-process), (get-service)}An alternative to the invoke-command is the psexec command. The PsExec command is a lightweight utility that lets you execute processes on remote commands, it also lets you launch programs and interact with the console.
WarningAction
Invoke-Command -ComputerName $remoteServer { Write-Warning 'Test'
} -WarningAction SilentlyContinueIs there no way do proper warning-stream passthrough in invoke-command?
From Doug Maurer – redirect internally than capture
$output = Invoke-Command -ComputerName $remoteServer { Write-Warning 'Test' 3>&1
}But in order to parse the warnings back out of other return values, I’d have to do something like
$output = Invoke-Command -ComputerName $remoteServer { Write-Warning 'Test' 3>&1
} | foreach-object { if(($_ | Get-Member).TypeName -like '*.WarningRecord') { Write-Warning $_.InformationalRecord_Message } else { $_ }
}which works, I suppose, but is kind of monstrous? Do I need to make a complete wrapper for Invoke-Cmd that handles exploding back out the Warning and Verbose and Information records?
Setting Default Proxy Settings
If you frequently need to use a proxy, setting the proxy server as a default for all web requests might be convenient. This can be done by configuring the WebRequest default settings in PowerShell:
This configuration ensures that all web requests made through Invoke-WebRequest will use the specified proxy server and credentials by default.
Which PowerShell Proxy Should You Use?
The answer to this question changes based on what you want to achieve with your Invoke-WebRequest request. To find the right PowerShell proxy for your needs, take a look at the different types of proxies available:
- Datacenter proxies: They are fast and cheap, but can be easily detected and blocked by sites because of their identifiable IP ranges.
- Residential proxies: They offer rotating genuine IP addresses from real devices in specific locations. This means they can guarantee a high level of anonymity. Residential proxies are perfect for accessing sites that rely on geo-restriction blocks or to avoid anti-bot measures.
- ISP proxies: They are secure, fast, and highly reliable as they provide static IPs from devices registered with ISPs. ISP proxies are also called residential static proxies and are a perfect solution for SEO monitoring and market research.
- Mobile proxies: They provide IPs from real mobile devices for a high level of anonymity. They are useful for accessing applications, sites, or content specifically designed for mobile devices.
Prerequisites Invoke-Command
To check if a remote computer accepts Remote Management, we can use a simple PowerShell command, Test-WSMan
Test-WSMan -Computername la-srv-dc01
If you get an error that you cannot connect to the destination, then the service Windows Remote Management is not running. To enable it we can use the PowerShell cmdlet Enable-PSRemoting on the remote computer:
Enable-PSRemoting
The advantage of this command is that it not only starts the Remote Management services but also sets it to start automatically and creates the required exception rule in the firewall.
But even a better option is to create a new Group Policy Object (GPO). This way you can easily enable the Remote Management service on multiple computers or servers.
You can find the policy setting in Computer Configuration > Windows Settings > Security Settings > System Services.
Firewall rule
We can use the same GPO to create the inbound rule as well.
- Navigate to Computer Configuration > Windows Settings > Security Settings > Windows Defender Firewall with Advanced Security
- Right-click on Inbound Rules and select New Rule
- Select Predefined and choose Windows Remote Management
- Select the rule with profile Domain, Private
- Choose Allow the connection and click finish
Make sure that the new policies are updated on the server/client, by using the GPUpdate command.
Using Secure Proxies
If your proxy server uses HTTPS for secure connections, you need to specify the URL with https://:
$proxy = "https://proxyserver:8080"
$response = Invoke-WebRequest -Uri "http://example.com" -Proxy $proxy
Write-Output $response.ContentBasic Proxy Usage
$proxy = "http://proxyserver:8080"
$response = Invoke-WebRequest -Uri "http://example.com" -Proxy $proxy
Write-Output $response.ContentIn this example, the request to “http://example.com” is routed through the proxy server at http://proxyserver:8080.
Conclusion
Using Invoke-WebRequest with a proxy in PowerShell is a straightforward process that can greatly enhance your scripting capabilities, especially in environments with restricted internet access. By understanding how to configure proxy settings and handle credentials, you can ensure your web requests are routed appropriately and securely. This guide has covered the basics and some advanced scenarios to help you maximize Invoke-WebRequest with a proxy server.
Remember, the key steps involve:
- Identifying your proxy server.
- Using the -Proxy parameter for basic proxy configuration.
- Adding credentials with the -ProxyCredential parameter if needed.
- Setting default proxy settings for convenience.
- Handling advanced scenarios like proxy bypass and secure proxies.
With this knowledge, you can effectively manage web requests in PowerShell, ensuring they comply with your network’s security and access policies.
Conclusion
In this PowerShell proxy guide, you learned what Invoke-WebRequest is, how it works, and how to use it with an HTTP/HTTPS/SOCKS proxy. As it turned out, you cannot rely on proxies from free providers. Therefore, the only decision to be made is which proxy provider you should adopt. Save time and energy and go directly for the best on the market, Bright Data.
Bright Data controls the best proxy servers in the world, serving Fortune 500 companies and over 20,000 customers. Its worldwide proxy network involves:
Overall, that is one of the largest and most reliable scraping-oriented proxy networks on the market.
No credit card required

