Created
June 30, 2017 18:43
-
-
Save techthoughts2/8b9624b7ba87857719ba0102f9106eda to your computer and use it in GitHub Desktop.
This code block will allow you to run subsequent cmdlets as a different 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
function Get-ImpersonatetLib { | |
if ($script:ImpersonateLib) { | |
return $script:ImpersonateLib | |
} | |
$sig = @' | |
[DllImport("advapi32.dll", SetLastError = true)] | |
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); | |
[DllImport("kernel32.dll")] | |
public static extern Boolean CloseHandle(IntPtr hObject); | |
'@ | |
$script:ImpersonateLib = Add-Type -PassThru -Namespace 'Lib.Impersonation' -Name ImpersonationLib -MemberDefinition $sig | |
return $script:ImpersonateLib | |
} | |
function ImpersonateAs([PSCredential]$cred) { | |
[IntPtr]$userToken = [Security.Principal.WindowsIdentity]::GetCurrent().Token | |
$userToken | |
$ImpersonateLib = Get-ImpersonatetLib | |
$bLogin = $ImpersonateLib::LogonUser($cred.GetNetworkCredential().UserName, $cred.GetNetworkCredential().Domain, $cred.GetNetworkCredential().Password, | |
9, 0, [ref]$userToken) | |
if ($bLogin) { | |
$Identity = New-Object Security.Principal.WindowsIdentity $userToken | |
$context = $Identity.Impersonate() | |
} | |
else { | |
throw "Can't Logon as User $cred.GetNetworkCredential().UserName." | |
} | |
$context, $userToken | |
} | |
function CloseUserToken([IntPtr]$token) { | |
$ImpersonateLib = Get-ImpersonatetLib | |
$bLogin = $ImpersonateLib::CloseHandle($token) | |
if (!$bLogin) { | |
throw "Can't close token" | |
} | |
} | |
$PASSWORD = 'password' | |
$user = "domain\user" | |
$secureString = ConvertTo-SecureString -AsPlainText -Force -String $PASSWORD | |
$credential = New-Object ` | |
-TypeName System.Management.Automation.PSCredential ` | |
-ArgumentList $user, $secureString | |
($oldToken, $context, $newToken) = ImpersonateAs -cred $Credential | |
#commands from this point forward will be run as the credential you provided | |
#Get-Service <--- now runs as the context user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment