Detect When an Elevated PowerShell Script Runs Under a Different Account Than the Desktop User

Abstract: UAC may run an elevated script under a different account than the one that owns the desktop. Compare the process token against the session owner to catch the mismatch before HKCU paths and mapped drives break.

Created: 2026-11-02 by

Yes — the elevated shell keeps the session ID of the desktop it was launched from, so you can compare the account inside your process token with the account that owns that session. When the two differ, the script was elevated with someone else's credentials, and everything that follows the token — HKEY_CURRENT_USER, %USERPROFILE%, mapped drives — silently points at the wrong profile. This article shows a quick manual check, a scriptable check you can gate a script on, and an audit-log route for investigating incidents after the fact.

Why elevation can silently switch accounts

User Account Control gives every interactive administrator a split token at logon: a filtered token for everyday work, and a full token that is only attached after a UAC prompt is approved. Elevating yourself simply swaps in the other half of your own logon. But the UAC prompt also accepts a completely different set of credentials — the over-the-shoulder scenario, where a colleague or a service account approves the prompt. Windows then builds a brand-new token for that second account and runs your script with it, while the process stays inside the original desktop session.

The script still sees the same screen and session, yet its identity, its HKCU view, its profile paths, and its per-logon mapped drives all belong to whoever typed the password. That mismatch is what breaks installers that write per-user settings, scripts that touch the logged-on user's registry hive, and anything expecting the desktop user's environment.

A thirty-second manual check

Open the elevated console and run two commands:

whoami
qwinsta

whoami reports the account in your process token. qwinsta lists every session on the machine, and the USERNAME column shows who owns each one:

 SESSIONNAME       USERNAME       ID  STATE   TYPE     DEVICE
 services                          0  Disc
>console           jdoe            1  Active

If the console line (or your rdp-tcp#n line over remote desktop) shows a different name than whoami, your elevated shell is running as another account.

A scriptable check you can gate on

The manual comparison translates directly into code: ask Terminal Services which user owns the session your process lives in, then compare it with your own token. The session ID never changes across UAC elevation, so this check is stable:

Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;

public static class WtsSession
{
    [DllImport("wtsapi32.dll")]
    static extern bool WTSQuerySessionInformation(
        IntPtr hServer, int sessionId, int infoClass,
        out IntPtr pBuffer, out int bytesReturned);

    [DllImport("wtsapi32.dll")]
    static extern void WTSFreeMemory(IntPtr pMemory);

    const int WTSUserName   = 5;
    const int WTSDomainName = 7;

    public static string GetSessionUser(int sessionId)
    {
        IntPtr buf; int len;
        string domain = "", user = "";
        if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTSDomainName, out buf, out len))
        { domain = Marshal.PtrToStringAnsi(buf); WTSFreeMemory(buf); }
        if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTSUserName, out buf, out len))
        { user = Marshal.PtrToStringAnsi(buf); WTSFreeMemory(buf); }
        return domain + "\\" + user;
    }
}
'@

$me    = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$owner = [WtsSession]::GetSessionUser([Diagnostics.Process]::GetCurrent().SessionId)

if ($me -ieq $owner) {
    'Same account - safe to continue.'
} else {
    throw "Elevated as $me, but the desktop session belongs to $owner."
}

For a stricter comparison, translate the session owner's name into a SID and compare SIDs instead of strings; NTAccount/SecurityIdentifier translation handles local-versus-domain name collisions.

An alternative is to read the security descriptor of your process's window station: its DACL contains a per-user access-allowed ACE (an S-1-5-21-... SID) for the desktop owner, and elevation merely appends an Administrators group ACE. Extracting that SID and comparing it with your token SID also works, but you have to guess which ACE is the user ACE, so the WTS route above is simpler and less brittle.

Investigating after the fact with the security event log

If you need to know who elevated what — rather than gate a script — the Windows security log answers this in event ID 4624, provided success logon auditing was enabled beforehand. Every interactive logon of an administrator on a UAC-enabled system produces paired 4624 events, one with Elevated Token: Yes and one with No, tied together by the Logon ID and, on Windows 10 / Server 2016 and newer, the Linked Logon ID field. When someone approves a UAC prompt with different credentials, the log records a 4624 for that account with an elevated token, letting you correlate the elevated logon with the console session and see exactly which account was used.

Reading the security log requires administrative rights, and because auditing must be switched on before the event occurs, this is a forensics tool, not an in-script check.

Pitfalls and hardening

  • Don't trust the window station's Owner field. It always reads BUILTIN\Administrators, never the desktop user — use the DACL's per-user ACE or the WTS query instead.
  • Don't infer anything from group membership. Whether the token is an admin says nothing about which account owns the desktop; two different administrators produce the same "elevated: yes" result.
  • Compare SIDs when you can. A local and a domain account can share a name; SIDs cannot collide.
  • Fail fast. Put the comparison at the top of the script and exit with a message naming both accounts, rather than failing three steps later on a missing mapped drive.
  • Re-map drives or use UNC paths. Mapped drives are per logon session; if the elevated context needs the user's drive, map it again inside the script or address the share directly.
  • Load the right hive explicitly. If you must edit the desktop user's registry from a different elevated account, load their NTUSER.DAT under a custom key instead of relying on HKCU.

Frequently Asked Questions

Does UAC elevation change the session ID?

No. The elevated process stays in the same session as the desktop; only the security token — and therefore the account — changes. That is exactly why session-based checks like the WTS query work.

Why can't I just check %USERPROFILE% or HKEY_CURRENT_USER?

Because both follow the token, not the session. They show the elevating account's profile — the very thing that breaks. Use them to confirm symptoms, not to identify the desktop owner.

Does the WTS check work over RDP?

Yes. The query uses your own process's session ID, so it behaves identically for console and remote sessions, returning whichever user is logged on to that session.

Do I need administrator rights to run these checks?

Not for the token and session comparisons — both read information your own process already has access to. Yes for the security event log, which also requires success logon auditing to have been enabled in advance.

Why compare SIDs instead of usernames?

Account names are only unique within their domain; a local account and a domain account can share a display name. SIDs such as S-1-5-21-... are unambiguous, so SID comparison avoids false "same user" results.

Can the script continue safely when the accounts differ?

Sometimes. If the script only touches machine-wide state, the mismatch is harmless — log a warning and continue. If it touches HKCU, profile paths, or the user's mapped drives, either re-run unelevated as the desktop user or perform those steps explicitly against that user's profile.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More