Last active
February 18, 2019 06:33
-
-
Save PlagueHO/6fdbd56618b7d7ca88ad11248dc0951a to your computer and use it in GitHub Desktop.
Function to allow PowerShell Code to traverse a Proxy that requires Authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Use-Proxy { | |
param ( | |
[Parameter(Mandatory)] | |
[ScriptBlock] $ScriptBlock, | |
[String] $ProxyAddress = 'http://myproxy.contoso.com', | |
[PSCredential] $ProxyCredentials | |
) | |
# If proxy creendials weren't passed in then see if global proxy creds | |
# are set. Global Proxy credentials can save some typing by setting | |
# them in the PS session. | |
if (-not ($PSBoundParameters.ContainsKey('ProxyCredentials'))) | |
{ | |
if ($Global:ProxyCredentials) | |
{ | |
$ProxyCredentials = $Global:ProxyCredentials | |
} | |
else | |
{ | |
$ProxyCredentials = Get-Credential -Message "Enter proxy credentials" | |
} # if | |
} # if | |
# Configure the proxy | |
$null = & netsh @('winhttp','set','proxy',$ProxyAddress) | |
try | |
{ | |
$webclient=New-Object System.Net.WebClient | |
$webclient.Proxy.Credentials = $ProxyCredentials | |
# Call the actual code | |
Invoke-Command -ScriptBlock $ScriptBlock | |
} | |
catch | |
{ | |
Throw $_ | |
} | |
finally | |
{ | |
# Reset the proxy | |
$null = & netsh @('winhttp','import','proxy','source=ie') | |
} # try | |
} # Function Use-Proxy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment