Skip to content

Instantly share code, notes, and snippets.

@PlagueHO
Last active February 18, 2019 06:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PlagueHO/6fdbd56618b7d7ca88ad11248dc0951a to your computer and use it in GitHub Desktop.
Save PlagueHO/6fdbd56618b7d7ca88ad11248dc0951a to your computer and use it in GitHub Desktop.
Function to allow PowerShell Code to traverse a Proxy that requires Authentication
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