确保在任何给定时间只有 1 个 PowerShell 脚本实例正在运行 [英] Assure only 1 instance of PowerShell Script is Running at any given Time

查看:41
本文介绍了确保在任何给定时间只有 1 个 PowerShell 脚本实例正在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 PowerShell v1 中编写一个批处理脚本,该脚本将被安排为每分钟运行一次.不可避免地,有时工作需要超过 1 分钟才能完成,现在我们有两个脚本实例在运行,然后可能有 3 个,等等......

I am writing a batch script in PowerShell v1 that will get scheduled to run let's say once every minute. Inevitably, there will come a time when the job needs more than 1 minute to complete and now we have two instances of the script running, and then possibly 3, etc...

我想通过让脚本本身检查是否有自己的实例已经在运行来避免这种情况,如果是,则脚本退出.

I want to avoid this by having the script itself check if there is an instance of itself already running and if so, the script exits.

我在 Linux 上用其他语言完成过这个,但从未在 Windows 上用 PowerShell 完成过.

I've done this in other languages on Linux but never done this on Windows with PowerShell.

例如在 PHP 中,我可以执行以下操作:

For example in PHP I can do something like:

exec("ps auxwww|grep mybatchscript.php|grep -v grep", $output);
if($output){exit;}

PowerShell v1 中有这样的东西吗?我还没有遇到过这样的事情.

Is there anything like this in PowerShell v1? I haven't come across anything like this yet.

在这些常见模式中,哪一种对频繁运行的 PowerShell 脚本最有意义?

Out of these common patterns, which one makes the most sense with a PowerShell script running frequently?

  1. 锁定文件
  2. 操作系统任务计划程序
  3. 具有睡眠间隔的无限循环

推荐答案

如果脚本是使用 powershell.exe -File 开关启动的,您可以检测到在进程命令行属性中存在脚本名称的所有 powershell 实例:

If the script was launched using the powershell.exe -File switch, you can detect all powershell instances that have the script name present in the process commandline property:

Get-WmiObject Win32_Process -Filter "Name='powershell.exe' AND CommandLine LIKE '%script.ps1%'"

这篇关于确保在任何给定时间只有 1 个 PowerShell 脚本实例正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆