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
To get current username in PowerShell, use whoami, GetCurrent() method of WindowsIdentity . Net class or Get-WMIObject cmdlet in PowerShell. In PowerShell, there are different ways to get current user name.
Use Get-LocalUser PowerShell cmdlet to List All User Accounts. The Get-LocalUser PowerShell cmdlet lists all the local users on a device. Remember that Active Directory domain controllers don't have local user accounts.
iex is an alias for Invoke-Expression . Here the two backticks don't make any difference, but just obfuscates the command a little. iex executes a string as an expression, even from pipe. Here Start-Process is a cmdlet that starts processes.
-ArgumentList. Specifies parameters or parameter values to use when this cmdlet starts the process. Arguments can be accepted as a single string with the arguments separated by spaces, or as an array of strings separated by commas.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With