尝试捕获-如何捕获错误但继续?

问题描述

我有这个脚本,该脚本在每台计算机的foreach循环中循环,并在每台计算机的每个NIC中循环。当前,Catch块未运行。我想做的就是捕捉错误(通常是因为get-wmi无法连接到机器),做点什么(向PSCustomObject添加一些信息),然后继续下一次迭代。我该如何捕捉错误但还要继续foreach循环?

    param (
        [Alias('Hostname')]
        [string[]]$ComputerName = @('pc1','pc2'),$OldDNSIP = '7.7.7.7',$NewDNSIP = @('9.9.9.9','8.8.8.8')
    )

    $FailedArray = @()
    $DHCPArray = @()

    Foreach ($Computer in $ComputerName){
        $NICList = Get-WmiObject Win32_NetworkAdapterConfiguration -computername $Computer | where{$_.IPEnabled -eq "TRUE"}
            Foreach($NIC in $NICList){
                If($NIC.DHCPEnabled -eq $false){

                    Try{
                        $DNSIPs = $NIC.DNSServerSearchOrder
                        if($DNSIPs -contains $OldDNSIP){
                            
                            $NewDNS = $DNSIPs | foreach {$_ -replace $OldDNSIP,$NewDNSIP[0]}
                            $null = $NIC.SetDNSServerSearchOrder($NewDNS)
                        }
                        else{
                            write-host " - Old DNS server IP not found... ignoring"
                        }


                    }
                    Catch{
                        write-host " - Something went wrong... logging to a CSV for review later" -ForegroundColor Red
                        $FailedArray += [PSCustomObject]@{
                        'Computer' = $Nic.pscomputername
                        'NIC_ID' = $nic.index
                        'NIC_Descrption' = $nic.description}
                    }

                }
                ElseIf($NIC.DHCPEnabled -eq $true){
                    write-host " - DHCP is enabled. Adding this IP,Hostname,Nic Index and DHCP Server to a CSV for reviewing."
                    #add pscomputer,nic id,refernece and dhcp server to DHCPNICArray
                    $DHCPArray += [PSCustomObject]@{
                    'Computer' = $Nic.pscomputername
                    'NIC_ID' = $nic.index
                    'NIC_Descrption' = $nic.description
                    'DHCPEnabled' =$nic.dhcpenabled
                    'DHcpserver' = $nic.dhcpserver}
                }
            }
    }


$DHCPArray | export-csv c:\temp\dhcp.csv -NoTypeinformation
$FailedArray | export-csv c:\temp\Failed.csv -NoTypeinformation

解决方法

如果WMI错误是由于连接失败引起的,则将在处理任何NIC之前 发生。如果要捕获它们,然后继续使用下一台计算机,则必须将try-catch移至该循环级别。如果您还想捕获特定于nic的错误,则需要在该级别进行第二次try-catch。

另外,请考虑使用autodoc参数,或指定-ErrorAction Stop,以确保所有错误都将终止(即,直接跳转到catch块)。

这是一个例子,并附有解释说明:

$ErrorActionPreference = 'Stop'