Powershell - 查找调用脚本的用户

San*_*eev 15 powershell powershell-2.0 powershell-remoting

我有一个脚本(我们称之为myPSScript.ps1),它采用两个参数并执行预定义的步骤.脚本位于Windows Server框中,人们登录并执行脚本.支持两个用户在给定时间登录.

我想找出谁调用了脚本.

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

当用户当前登录并尝试运行脚本时,此方法有效.但是如果我在计划任务中有一个批处理文件并运行相同的脚本呢?

在这种情况下,同一个命令返回一个空异常,因为没有人登录到该机器.

有没有办法找出谁/哪个进程调用了powershell脚本.我依稀记得Start-Transcript记录从哪个用户运行命令,所以这应该是可能的?

谢谢!Sanjeev

man*_*lds 27

有趣的问题.我用三种不同的方式编写了一个脚本来让用户这样:

([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
Run Code Online (Sandbox Code Playgroud)

将其保存为test.ps1并使用以下方式调用它runas:

runas /user:domain\user "powershell e:\test.ps1"
Run Code Online (Sandbox Code Playgroud)

我在输出中三次获得域\用户.用于runas区分我登录的用户(me !!)和我运行它的域\用户.因此它确实为正在运行脚本的用户提供了帮助.