如何在PowerShell Core脚本中使用.NET Core IWebProxy的GetProxy()方法?
IWebProxy.GetProxy() in PowerShell Core for Cross-Platform Proxy Retrieval Absolutely! You can absolutely leverage the IWebProxy.GetProxy() method in PowerShell Core to fetch the appropriate proxy server for a target URI—perfect for pairing with Invoke-WebRequest. This approach works seamlessly across Windows, macOS, and Linux, since it relies on .NET Core's built-in proxy handling logic. Here's a step-by-step breakdown:
Step 1: Get the system's default proxy configuration
First, retrieve the system-wide proxy settings (this automatically picks up configs from Windows' IE settings, macOS network preferences, or Linux proxy environment variables):
$systemProxy = [System.Net.WebRequest]::GetSystemWebProxy()
Step 2: Retrieve the proxy URI for your target endpoint
Specify the URI you want to access, then call GetProxy() to get the proxy that applies to that specific address. This method will even account for proxy exclusion lists (if your target URI is in the "bypass proxy" list, it returns the target URI itself instead of a proxy):
# Define your target URI $targetUri = [System.Uri]::new("https://example.com") # Get the applicable proxy URI $proxyUri = $systemProxy.GetProxy($targetUri)
Step 3: Use the proxy with Invoke-WebRequest
Add a quick check to handle cases where no proxy is needed, then make your request:
if ($proxyUri -ne $targetUri) { # Proxy is required for this URI Invoke-WebRequest -Uri $targetUri -Proxy $proxyUri } else { # No proxy needed—direct request Invoke-WebRequest -Uri $targetUri }
Bonus: Custom Proxy & Authentication
If you need to use a custom proxy instead of the system default, you can instantiate a WebProxy directly:
$customProxy = [System.Net.WebProxy]::new("http://your-proxy-server:8080") $proxyUri = $customProxy.GetProxy($targetUri)
For proxies that require authentication, set the Credentials property before calling GetProxy():
$credentials = [System.Net.NetworkCredential]::new("your-username", "your-password") $systemProxy.Credentials = $credentials # Or for a custom proxy: $customProxy.Credentials = $credentials
This method is reliable across all PowerShell Core-supported platforms, ensuring you don't have to write platform-specific logic to handle proxies.
内容的提问来源于stack exchange,提问作者user2421046

