There are two methods I know of to obtain the currently logged in username. Both fail when I try to use them in a script that is running under a different user account.
Specifically, I have a script that is run from a Scheduled Task. The principal for the Task is a local user account that has 'run as batch job' permissions. Domain users are logged in when the script is launched by Task Scheduler.
I need the script to obtain the username of the currently logged in domain user. How can I do this when the script is running under a different (local) user account?
Method 1:
$array = @(Get-WmiObject -ComputerName . -Namespace root\cimv2 -Class Win32_ComputerSystem | foreach { $_.username }).Split('\\') $username = "$(($array[0]).ToUpper())\$(($array[1]).ToLower())" RESULT: MYDOMAIN\myuser.name
(works only when script is run by myuser.name)
Method 2:
$username = ($env:USERNAME).ToLower()
RESULT:
myuser.name
(again, works only when script is run by myuser.name)