PowerShell – Return Current User from QUser

email me

Quser.exe, short for Query User, is a utility in the Windows Command Prompt that allows administrators to view information about currently logged-on users. It’s particularly useful in environments with multiple users, such as corporate networks or shared computers. I like to use it, because it just works, and is available on all the Windows computers.

 

# MrNetTek 
# eddiejackson.net 
# 7/22/2024
# free for public use 
# free to claim as your own

$ErrorActionPreference = 'silentlycontinue'

# Initialize
Import-Module -Name Microsoft.PowerShell.Management
Import-Module -Name Microsoft.PowerShell.Security
Import-Module -Name Microsoft.PowerShell.Utility
Import-Module -Name Microsoft.PowerShell.Host

$quserOutput = quser
$currentUser = $null
$localAdmins = ""
$isAdmin = $false

# Detecting username in CU or SYSTEM
$currentUser = $quserOutput | ForEach-Object {
    if ($_ -match "\s+(\S+)\s+(\S+)\s+(\d+)\s+Active\s+") {
        $matches[1]
    }
}

if ($currentUser -eq $null) {
    $currentUser = $quserOutput | ForEach-Object {
        if ($_ -match "^\s*>\s*(\S+)\s+(\S+)\s+(\d+)\s+Active\s+") {
            $matches[1]
        }    
    }
}

# Let's verify if the user is in the local administrator's group
$localAdmins = Get-LocalGroupMember -Group "Administrators" | Where-Object { $_.PrincipalSource -ne 'Local'} | Select-Object -ExpandProperty Name

$ErrorActionPreference = 'stop'
if ($localAdmins -match $currentUser) {
    $isAdmin = $true
}

# Testing - Test in both User and System
Clear-Host
"User: $currentUser"
"Elevation: $isAdmin"
"Admins: $localAdmins"

# Session Clean up 
$localAdmins = ""
$currentUser = ""
$quserOutput = ""

# I do it this way to return a success or failed back to Intune
if ($isAdmin) {throw} else {exit 0}

 

 

Notes

 

QUser