Powershell - 如果没有Excel进程,添加catch以获取

met*_*lah 3 com excel powershell

有没有办法只添加一个if/else catch

$excelId = get-process excel | %{$_.Id} | ?{$before -notcontains $_}
Run Code Online (Sandbox Code Playgroud)

如果没有excel进程在运行?例如,如果Excel正在运行,那么get-process id,如果没有,则忽略它.

Get-Process:找不到名为"excel"的进程.验证进程名称并再次调用cmdlet.在run.ps1:3 char:24 + $ before = @(get-process <<<< excel |%{$ _.Id})+ CategoryInfo:ObjectNotFound:(excel:String)[Get-Process],ProcessCommandException + FullyQualifiedErrorId:NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

我的代码的第3-5行如下:

$before = @(get-process excel | %{$_.Id} ) 
$excel=new-object -com excel.application
$excelId = get-process excel | %{$_.Id} | ?{$before -notcontains $_}
Run Code Online (Sandbox Code Playgroud)

Efr*_*isi 6

您可以使用该-ErrorAction参数,告诉PowerShell SilentlyContinue您的脚本是什么结果Get-Process; 之后,$?将根据最终出现的错误进行设置(因此也缺少您正在寻找的过程):

$excel = Get-Process excel -ErrorAction SilentlyContinue
if (-not $?) { 'Excel is not running.' }
Run Code Online (Sandbox Code Playgroud)