Last active
February 26, 2021 08:30
-
-
Save alexmags/9acb3f041d6f0e5040207b481d63053a to your computer and use it in GitHub Desktop.
Configure Git client to use corporate proxy and authenticate as current user
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
# This takes a guess at what Git config should be for proxy. Effectivly we're doing netstat.exe | find "8080" | |
# Lookup current user via Active Directory | |
[reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement") | out-null | |
$currentUser=[System.DirectoryServices.AccountManagement.UserPrincipal]::Current | |
#region Test if behind a proxy. This also generates some traffic that we'll use to determine proxy URL | |
try { | |
Write-output "Testing internet access" | |
$status = (Invoke-WebRequest -Uri "https://www.powershellgallery.com/api/v2" -UseBasicParsing).StatusDescription | |
Write-Output "`tProxy test: $status" | |
} | |
catch { | |
# web request failed | |
$ex = $_.exception[0] | |
# $fullError = $ex | Format-List -Force | |
Write-Output "`tProxy test: $($ex.message)" | |
Write-output "Enabling proxy authentication and session options" | |
# Make PowerShell use proxy with current credentials | |
$browser = New-Object System.Net.WebClient | |
$browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials | |
# try again | |
try{ | |
$status = (Invoke-WebRequest -Uri "https://www.powershellgallery.com/api/v2" -UseBasicParsing).StatusDescription | |
Write-Output "`tProxy test: $status" | |
} | |
catch { | |
$ex = $_.exception[0] | |
$fullError = $ex | Format-List -Force | |
write-output "internet access failed $($ex.message)" | |
$fullError | |
throw $ex.InnerException | |
} | |
} | |
#endregion | |
# Have a guess at current session's autodiscovered internet proxy | |
$proxyPort='8080' | |
try{ | |
$arrayOfConnectionsToProxyPort=@(Get-NetTCPConnection | where-object {($_.RemotePort -eq $proxyPort)}) | |
$probablyProxyIP=($arrayOfConnectionsToProxyPort | Group-Object -Property RemoteAddress | sort-object -descending -property count)[0].name # most frequent | |
#Perform a DNS Reverse Lookup (IP to hostname .Net): | |
$proxyFullyQualifiedDomainName=[System.Net.Dns]::GetHostEntry($probablyProxyIP).HostName | |
& git.exe config --global http.proxy "http://$($currentUser.SamAccountName)@$($proxyFullyQualifiedDomainName):$($proxyPort)" | |
} | |
catch{ | |
Write-Output "Didn't find any connections to $proxyPort that look like proxy" | |
} | |
# open git config to review whats been configured | |
# & git.exe config --global --edit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment