简体   繁体   中英

How does $env:Username work in PowerShell?

So someone told me the following in a previous question:

"$env:Username allways refers to the user that has created the powershell session, not to the currently logged on user."

But isn't the currently logged on user always the one creating the powershell session?

I guess my question is, can you describe to me a scenario or two where user X is creating a powershell session for the currently logged on user Y?

Also I guess I'm not understanding the concept of a session. If you right click a ps1 file and select run with powershell, who is creating that session? The currently logged on user, or the creator of the script?

If I have a .bat file that runs on login, and calls a ps1 file, who is the creator of that powershell session?

Any help you can provide is greatly appreciated.

It runs as the user that powershell is currently running, even if it's different than the logged in user.

PS C:\Windows\system32> $env:username
jasonw

PS C:\Windows\system32> Start-Process powershell.exe -Credential "domain\admin.jasonw" -NoNewWindow -ArgumentList "Start-Process powershell.exe -Verb runAs"
[This opens new window running PS as the user]

PS C:\Windows\system32> $env:username
admin.jasonw

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM