pf-WinImpersionate.ps1

function New-Impersonate_Context {
    Param(
       [System.Management.Automation.PSCredential]$Credential
    )

    if (-not $ImporsonateClass) {
        $currentScript = split-path ( Get-PSCallStack )[0].ScriptName -Parent
        $ImpersonateClassPath = "$currentScript\Impersonate.cs"
        $script:ImporsonateClass = Add-Type -passthru -Path $ImpersonateClassPath 
            | Where-Object name -eq 'Impersonation'
    }

    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    if (-not $Credential) {
        Write-Host "No credentials provided existing user is '$($currentUser.Name)'"
        return $null
    }
    
    $ntCredential = $Credential.GetNetworkCredential()
    $domain = Coalesce $ntCredential.Domain $env:USERDOMAIN
    $user = $ntCredential.UserName

    if ( $currentUser.Name -eq "$domain\$user" ) {
        Write-Host "Already using user '$($currentUser.Name)'"
        # Do not impersonate if it is using already the expected user
        return
    }

    $context = New-Object $ImporsonateClass -ArgumentList $user, $domain, $ntCredential.Password
    $newUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    Write-Host "Switched from user '$($currentUser.Name)' to '$($newUser.Name)'"

    return $context
}

function Invoke-Scope_Impersonate {
    Param(
       [System.Management.Automation.PSCredential]$Credential,
       [ScriptBlock]$script
    )

    try {
        $imp = $null
        $imp = New-Impersonate_Context -Credential $Credential
        $Result = . $script
        return $Result
    }
    finally {
        Invoke-Dispose ([Ref]$imp)
        $newUser = [Security.Principal.WindowsIdentity]::GetCurrent()
        Write-Host "Switched back to '$($newUser.Name)'"
    }
}
function Invoke-Scope_Impersonate:::Example {
    if (-not $cred) { 
       $cred = Get-Credential -UserName "CORP-LCL\SP_Admin" -Message "Example"
    }

    Invoke-Scope_Impersonate -Credential $cred -script {
        $proxyRegPath = 'HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
        reg query $proxyRegPath /v MyVal 
        #ProxyEnable
        Write-Host $proxyRegPath
    }
}