Originally published on proxymint.
PowerShell proxy setup for Invoke-WebRequest and Invoke-RestMethod: -Proxy with credentials, PowerShell 7 vs 5.1, environment variables, SOCKS5 and 407 fixes.
TL;DR
- Pass -Proxy and -ProxyCredential on the call. Invoke-WebRequest and Invoke-RestMethod both take -Proxy http://HOST:PORT plus a PSCredential, and in a script you build that credential in code, because Get-Credential just sits there waiting for a person.
- A password inside the -Proxy URL does nothing useful. You still get a 407, and the error message prints the full URL with the password in it, so it lands in your logs. Put the login in -ProxyCredential instead.
- If your proxy settings seem ignored, check which PowerShell you are in. PowerShell 7 reads HTTPS_PROXY and falls back to your user's Windows proxy; Windows PowerShell 5.1 never reads the variables, and neither of them reads netsh winhttp.
- Never start the proxy address with https://. It means TLS to the proxy itself, and with the default timeout of 0 the call can hang forever, which is a rough way to find out at 3 a.m. Use http:// or socks5://.
Key takeaways
- Set -TimeoutSec on anything unattended. Thirty seconds is plenty for most calls, and a wrong proxy address then fails with a clear HttpClient.Timeout message instead of holding the task open.
- Use a wildcard default for a whole script. $PSDefaultParameterValues['*:Proxy'] reaches Invoke-RestMethod and Install-Module too; a default keyed to Invoke-WebRequest only covers that one cmdlet, which is easy to miss.
- Reuse one -WebSession for polling loops. Since PowerShell 7.4 a session keeps its connection, so you skip a CONNECT and a 407 round trip per call, but the whole loop then reaches the site over one connection, from one address.
- Use socks5://, not socks5h://, in PowerShell 7. socks5h throws NotSupportedException, and plain socks5 already sends the hostname, so DNS resolves at the proxy anyway.
Read the full guide on proxymint, with the commands, tables and sources.
Top comments (0)