Advertisement
Guest User

Untitled

a guest
Jun 30th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. function Get-ImpersonatetLib {
  2. if ($script:ImpersonateLib) {
  3. return $script:ImpersonateLib
  4. }
  5.  
  6. $sig = @'
  7. [DllImport("advapi32.dll", SetLastError = true)]
  8. public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
  9.  
  10. [DllImport("kernel32.dll")]
  11. public static extern Boolean CloseHandle(IntPtr hObject);
  12. '@
  13. $script:ImpersonateLib = Add-Type -PassThru -Namespace 'Lib.Impersonation' -Name ImpersonationLib -MemberDefinition $sig
  14.  
  15. return $script:ImpersonateLib
  16.  
  17. }
  18.  
  19. function ImpersonateAs([PSCredential]$cred) {
  20. [IntPtr]$userToken = [Security.Principal.WindowsIdentity]::GetCurrent().Token
  21. $userToken
  22. $ImpersonateLib = Get-ImpersonatetLib
  23.  
  24. $bLogin = $ImpersonateLib::LogonUser($cred.GetNetworkCredential().UserName, $cred.GetNetworkCredential().Domain, $cred.GetNetworkCredential().Password,
  25. 9, 0, [ref]$userToken)
  26.  
  27. if ($bLogin) {
  28. $Identity = New-Object Security.Principal.WindowsIdentity $userToken
  29. $context = $Identity.Impersonate()
  30. }
  31. else {
  32. throw "Can't Logon as User $cred.GetNetworkCredential().UserName."
  33. }
  34. $context, $userToken
  35. }
  36.  
  37. function CloseUserToken([IntPtr]$token) {
  38. $ImpersonateLib = Get-ImpersonatetLib
  39.  
  40. $bLogin = $ImpersonateLib::CloseHandle($token)
  41. if (!$bLogin) {
  42. throw "Can't close token"
  43. }
  44. }
  45.  
  46. $PASSWORD = 'password'
  47. $user = "domain\user"
  48. $secureString = ConvertTo-SecureString -AsPlainText -Force -String $PASSWORD
  49. $credential = New-Object `
  50. -TypeName System.Management.Automation.PSCredential `
  51. -ArgumentList $user, $secureString
  52.  
  53. ($oldToken, $context, $newToken) = ImpersonateAs -cred $Credential
  54.  
  55. #commands from this point forward will be run as the credential you provided
  56. #Get-Service <--- now runs as the context user
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement