try-catch绕过一步

时间:2016-06-16 08:27:47

标签: function powershell try-catch

我有一个测试与服务器列表的连接的脚本,如果可以联系,则获取服务的状态,并将结果放入三个变量$Computer$Ping(True / False )和$Service(正在运行或已停止)。

输出位于哈希表中,但我只能显示可联系的服务器,而不能显示无法联系的服务器。

我在try块以及catch中放置了$Ping / -ErrorAction Stop,因此它不会尝试运行$Service 1}}脚本,而是转到数组中的下一个$Computer。我想我试图同时做两件相互冲突的事情:

  1. 将变量添加到@Splat
  2. 不要再进行任何处理。
  3. 我的脚本中实际上有更多远程注册表查询,如果$Computer无法联系,则无关紧要,但我已将此文章缩短了。

    Function Get-Ping {
        $Servers = (gc "c:\temp\test.txt")
        foreach ($Computer in $Servers) {
            Write-Host
            Write-Host "---------------------------------" 
            Write-Host "QUERYING $Computer"
            Write-Host
            Write-Host "Performing ping test..."
            try {
                $Ping = Test-Connection $Computer -Count 1 -ErrorAction Stop
            } catch {
                Write-Warning "Cannot Ping $Computer"
                Write-Host "Trying next computer..."
                Write-Host
                continue
            }
            if ($Ping) {$Ping="$True"}
            Write-Host $Computer "can be pinged"
    
            $svcRRStopped = $false
            if ($Computer -ne $env:COMPUTERNAME) {
                Write-Host "Check RemoteRegistry status..."
            }
            $svcRR = Get-Service -ComputerName $Computer -Include RemoteRegistry
    
            $SelectSplat = @{
                Property = (
                    'Computer',
                    'Ping',
                    'Service'
            )}
    
            New-Object -TypeName PSObject -Property @{
                  Computer=$Computer 
                  Ping=$Ping
                  Service=$svcRR.status
            } | Select-Object @SelectSplat
        }
    }
    
    $results = Get-Ping
    $tableFragment = $results | Select 'Computer','Ping','Service' 
    $tableFragment
    

2 个答案:

答案 0 :(得分:0)

不要让事情变得比他们需要的更复杂。

function Get-Ping {
  Get-Content 'C:\temp\test.txt' | ForEach-Object {
    $isAvailable = [bool](Test-Connection $_ -Count 1 -EA SilentlyContinue)
    if ($isAvailable) {
      $rreg = Get-Service -Computer $_ -Name RemoteRegistry |
              Select-Object -Expand Status
    } else {
      $rreg = 'n/a'
    }
    New-Object -Type PSObject -Property @{
      Computer = $_ 
      Ping     = $isAvailable
      Service  = $rreg
    }
  }
}

Get-Ping

答案 1 :(得分:0)

您只需使用-Quiet参数:

Test-Connection $_ -Count 1 -Quiet