Powershell - 查找调用脚本的用户

发布于 2024-12-05 16:42:47 字数 478 浏览 0 评论 0原文

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

我想找出谁调用了该脚本。

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

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

在这种情况下,同一命令将返回空异常,因为没有人登录到计算机。

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

谢谢! 桑吉耶夫

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那请放手 2024-12-12 16:42:47

有趣的问题。我用三种不同的方式编写了一个脚本来获取用户,如下所示:

([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

将其另存为 test.ps1 并使用 runas 调用它:

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

我在输出中三次获得了域\用户。使用 runas 来区分我登录的用户(我!!)和我运行它的域\用户。所以它确实给了正在运行脚本的用户。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文