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
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.