Powershell - Find the user who invoked the script

33,933

Interesting question. I wrote a script with three different ways to get the user like so:

([Environment]::UserDomainName + "\" + [Environment]::UserName) | out-file test.txt
"$env:userdomain\$env:username" | out-file -append test.txt
[Security.Principal.WindowsIdentity]::GetCurrent().Name | out-file -append test.txt
notepad test.txt

Saved it as test.ps1 and called it using runas as:

runas /user:domain\user "powershell e:\test.ps1"

And I got the domain\user all three times in the output. Used runas to just distinguish between the user I am logged in as (me!!) and the domain\user with which I was running it as. So it does give the user that is running the script.

Share:
33,933
Sanjeev
Author by

Sanjeev

Updated on September 22, 2020

Comments

  • Sanjeev
    Sanjeev over 3 years

    I have a script(Let's call it myPSScript.ps1) which takes two parameters and performs predefined steps. Script is located in a Windows Server box which people login and execute the script. Supports two users to be logged in at the given time.

    I want to find out who invoked the script.

    (Get-WmiObject -Class Win32_Process | Where-Object {$_.ProcessName -eq 'explorer.exe'}).GetOwner() | Format-Table Domain, User 
    

    This works when the user is logged in currently and trying to run the script. But what if I have a batch file in scheduled tasks and run the same script?

    In that case the same command returns a null exception, as there is no one logged into the machine.

    Is there a way to find out who/which process invoked the powershell script. I vaguely remember Start-Transcript records which user the command is run from etc, so this should be possible?

    Thanks! Sanjeev

  • Sanjeev
    Sanjeev over 12 years
    Perfect. This also works when the script is triggered using Invoke-Command from a different machine and different users - which is exactly I was looking for. Now I can audit who does what and when :)
  • Sanjeev
    Sanjeev over 12 years
    One more problem. Let's say a person is logged into a windows server using a domain user. In that case the script gives us the domain user, but that is not helpful when it's used by more than one person. Terminal Service Manager shows the Client Name, which is the name of the client from which the person has connected from. Is there a way to get that info?
  • Sanjeev
    Sanjeev over 12 years
    Using PSTerminalServices module is one of the option to get that info.