Powershell 错误处理在调用命令块中不起作用

Powershell Error Handling not working in Invoke-command block

我想在找不到服务或机器离线时打印错误消息

$csv = Import-Csv "C:\Users\user\Desktop\computers.csv" -delimiter ","
foreach ($cs in $csv){
   
    $computers = $cs.DNSHostname
    foreach ($computer in $computers){
   Try{
        Invoke-Command -ComputerName $computer -ScriptBlock {
        $ProcessCheck = Get-Process -Name agentid-service -ErrorAction Stop
        if ($null -eq $ProcessCheck) {
            Write-output "agentid-service IS not running $env:computername"
        }
        else {
            Write-output "agentid-service IS running $env:computername"
        }
      }
    }
    catch{
        Write-Warning $Error[0]
    }
  }
}

相反,当找不到服务名称时,我收到错误消息:

Cannot find a process with the name "agentid-service". Verify the process name and call the cmdlet again.

如果无法连接到计算机,则获取:

[vm.domain.local] Connecting to remote server vm.domain.local failed with the following error message : The WinRM client cannot process the request because the server name cannot be resolved.

并且脚本继续执行(应该如此)。 我怎样才能让“Catch”块被执行?

您可以在一个 foreach 循环中执行此操作。

尝试

$computers = (Import-Csv "C:\Users\user\Desktop\computers.csv").DNSHostname
foreach ($computer in $computers) {
    if (!(Test-Connection -ComputerName $computer -Count 1 -Quiet)) {
        Write-Warning "Computer $computer cannot be reached"
        continue  # skip this one and proceed with the next computer
    }
    try{
        Invoke-Command -ComputerName $computer -ScriptBlock {
            $ProcessCheck = Get-Process -Name 'agentid-service' -ErrorAction Stop
            if (!$ProcessCheck.Responding) {
                "agentid-service is NOT not running on computer '$env:computername'"
            }
            else {
                "agentid-service is running on computer '$env:computername'"
            }
        }
    }
    catch{
        Write-Warning $_.Exception.Message
    }
}

感谢@Theo 的回答,已成功解决:

  $csv = Import-Csv "C:\Users\user\Desktop\computers.csv" -delimiter ","
foreach ($cs in $csv){
    $error.Clear()
    $computers = $cs.DNSHostname
    foreach ($computer in $computers){
    Try{
   
        Invoke-Command -ComputerName $computer -ScriptBlock {
        
           $ProcessCheck = Get-Process -Name agentid-service -ErrorAction Stop
           if ($null -ne $ProcessCheck) {
             Write-output "agentid-service IS running $env:computername"
           }
        
               
    } -ErrorAction Stop
  }
  catch{
     if ($null -eq $ProcessCheck){
           Write-warning "agentid-service IS not running $env:computername"
          }
    Write-Warning $Error[0]
  }
   }
}