识别Powershell中执行批处理文件的PID
我需要从 PowerShell (v1.0) 脚本中识别正在执行的批处理文件的 P(rocess) ID。谁能建议一种方法来做到这一点?
谢谢,魔术安迪。
I need to identify the P(rocess) ID of an executing batch file from a PowerShell (v1.0) script. Can anyone suggest a way of doing this?
Thanks, MagicAndi.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么,这是否可能取决于您执行批处理文件的方式。
一般来说,找到这个问题的唯一方法是查看用于启动批处理的命令行。如果您在 Windows 资源管理器中双击批处理文件,您将获得类似于
在 Powershell 中的命令行,然后您可以在
Win32_Process
上使用Get-WMIObject
,其中包括命令行:但是,如果您直接从命令提示符启动批处理,则您无法从外部找出批处理正在运行以及是谁启动的。
Well, whether that's possible depends on how you executed the batch file.
In general, the only way you could possibly find this out is to look at the command line used to start the batch. If you double-click a batch file in Windows Explorer you'll get a command line like
In Powershell you can then use
Get-WMIObject
onWin32_Process
which includes the command line:However, if you started the batch directly from a command prompt, then you have no way of externally finding out that a batch is running and who started it.
我找到了一种发现正在运行的批处理文件的 PID 的方法。您需要在批处理文件中设置批处理控制台窗口的标题来识别它:
在 PowerShell 脚本中,您可以检查 MainwindowTitle 属性并从与批处理窗口标题匹配的进程中检索 PID:
我已经对此进行了测试方法,并且它似乎可以通过双击批处理文件来调用它,也可以通过从命令行调用它来工作。
I have found one method of discovering the PID of a running batch file. You will need to set the title of the batch console window in the batch file to identify it:
In the PowerShell script, you can check for the MainwindowTitle property and retrieve the PID from the process that matches your batch window title:
I have tested this method, and it appears to work both where you call the batch file by double clicking it, or by calling it from the command line.
我认为这不可能以可靠的方式实现。批处理文件本身不会启动单独的进程,而是在 cmd.exe 实例中运行。该特定进程中没有导出的数据可以可靠地告诉您正在运行哪个文件。
一个例外是专门启动 cmd.exe 实例来运行批处理文件。在这种情况下,它将出现在应用程序的命令行中,并且可以在命令行中 grep 查找批处理文件。尽管从 cmd.exe 提示符中运行多个批处理文件,但这并不能解决正常情况。
I don't believe this is possible in a reliable manner. Batch files themselves do not launch a separate process but instead are run within a cmd.exe instance. There is no exported data from that particular process that will reliably tell you what file is being run.
The one exception is if a cmd.exe instance is launched specifically to run a batch file. In that case it would appear in the command line of the application and it would be possible to grep the command line for the batch file. This wouldn't solve the normal case though of multiple batch files being run from within a cmd.exe prompt.