I am running as admin and I have no idea why this code is not allowing me in Impersonate a logged in user. I am trying to run this in powershell. I can not see my typo in this code.
# Specify the username of the account you want to impersonate
$usernameToImpersonate = "TestUser"
# Create a LogonUser signature
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class MyLogonUser {
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
}
"@
# Logon to the system without a password
$token = [IntPtr]::Zero
$success = [MyLogonUser]::LogonUser($usernameToImpersonate, $null, $null, 3, 0, [ref]$token)
if ($success) {
# Impersonate the user
$impersonationContext = New-Object System.Security.Principal.WindowsIdentity($token).Impersonate()
# Now you are impersonating the user
# Perform actions as the impersonated user here
Whoami
# Revert the impersonation
$impersonationContext.Undo()
# Close the token handle
[MyLogonUser]::CloseHandle($token)
} else {
Write-Host "Failed to log on to the user account."
}