get user token of user running explorer.exe

83 views Asked by At

I am getting an error when trying to get the user's token that is running explorer.exe. I am not sure what my is causing the error.

New-Object : Exception calling ".ctor" with "1" argument(s): "Invalid token for impersonation - it cannot be duplicated." At line:13 char:26

  • ... essToken = (New-Object System.Security.Principal.WindowsIdentity -Arg ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
    • FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
# Specify the username of the target user
$targetUsername = "$env:username"

# Get the processes running under the target user
$processes = Get-WmiObject -Class Win32_Process -Filter "Name = 'explorer.exe'" | Where-Object { $_.GetOwner().User -eq $targetUsername }

if ($processes.Count -eq 0) {
    Write-Host "No processes found for the user: $targetUsername"
} else {
    foreach ($process in $processes) {
        # Get the security token of the process
        $processHandle = [System.Diagnostics.Process]::GetProcessById($process.ProcessId).Handle
        $processToken = (New-Object System.Security.Principal.WindowsIdentity -ArgumentList $processHandle).Token

        Write-Host "Token for $targetUsername : $processToken"
    }
}
1

There are 1 answers

0
Martin Iszac On

See: https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-duplicatetokenex?redirectedfrom=MSDN

And: How to get Windows SYSTEM user token

You are trying to use a handle that can not be used as a token for impersonation. The handle must have the TOKEN_DUPLICATE access right which explorer.exe does not. Try using DuplicateTokenEx which will allow you to specify the access rights you want for the new token. See the links above for further guidance.

Please try and let me know if this helps.