gpt4 book ai didi

powershell - 如何判断特定 ProcessName 是否正在运行而不崩溃

转载 作者:行者123 更新时间:2023-12-02 23:12:43 26 4
gpt4 key购买 nike

假设有一个名为 exampleService 的应用程序应在 Server1 上运行。如果该代码正在运行,则它会起作用。然而,当它不运行时,它就会崩溃。

$application = Get-Process -ComputerName Server1 -Name "exampleService"

如果应用程序未运行,我会遇到此崩溃。有没有更优雅的方法来确定它是否没有运行(不会崩溃)

Get-Process : Cannot find a process with the name "exampleService". Verify the process name and call the cmdlet again.
At line:1 char:16
+ $application = Get-Process -ComputerName Server1 -Name "exampleService"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Sampler:String) [Get-Process], ProcessCommandException
+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

如果应用程序未运行,是否可以在服务器上启动该应用程序?

服务器正在运行 Windows Server 2012。PowerShell 命令正在从 Windows 7 64 位 PC 运行。

最佳答案

考虑使用-ErrorAction SilentlyContinue来防止显示该错误。如果应用程序未运行,您可以在 If 语句中使用它来启动应用程序。

--更新为包括启动远程进程

If (-NOT (Get-Process -Computername Server1 -name "cmd" -ErrorAction SilentlyContinue)) { 
Write-Host "Launch application"
$application = "c:\windows\system32\cmd.exe"
$start = ([wmiclass]"\\Server1\Root\CIMV2:win32_process").Create($application)
}

关于powershell - 如何判断特定 ProcessName 是否正在运行而不崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32397743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com