Powershell - 如果一个进程没有运行,启动它 [英] Powershell - if a process is not running, start it

查看:86
本文介绍了Powershell - 如果一个进程没有运行,启动它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请菜鸟帮忙.我正在尝试编写一个脚本来检查进程是否正在运行,如果没有,则启动它.如果进程正在运行,它应该什么都不做.到目前为止,我已经提出了以下内容,但它正在启动该过程的一个新实例,无论它是否已经在运行.任何帮助表示赞赏.

Noob help please. I'm trying to write a script that will check if a process is running, and if not, start it. If the process is running, it should do nothing. I've come up with the following so far but it is starting a new instance of the process regardless of whether it was running already. Any help is appreciated.

$Prog = "C:\utilities\prog.exe"
$Running = Get-Process prog -ErrorAction SilentlyContinue
$Start = ([wmiclass]"win32_process").Create($Prog)
if($Running -eq $null)
{$Start}
else
{}

推荐答案

首先,这是您的代码中的错误.在你的代码中,进程是在你评估你的程序是否已经运行之前创建的

First of all, here's is what is wrong in your code. In your code, the process is created before you evaluate whether your program is already running

$Prog = "C:\utilities\prog.exe"
$Running = Get-Process prog -ErrorAction SilentlyContinue
$Start = ([wmiclass]"win32_process").Create($Prog) # the process is created on this line
if($Running -eq $null) # evaluating if the program is running
{$Start}

可以通过将其包装在 {}(脚本块)中来创建应在代码中进一步评估的代码块:

It is possible to create a block of code that should be evaluated further in your code by wrapping it in {} (a scriptblock):

$Prog = "C:\utilities\prog.exe"
$Running = Get-Process prog -ErrorAction SilentlyContinue
$Start = {([wmiclass]"win32_process").Create($Prog)} 
if($Running -eq $null) # evaluating if the program is running
{& $Start} # the process is created on this line

但是,如果您正在寻找一种短的单线来解决您的问题:

However, if you're looking for a short one-liner to solve your problem:

if (! (ps | ? {$_.path -eq $prog})) {& $prog}

这篇关于Powershell - 如果一个进程没有运行,启动它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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