【问题标题】:Powershell foreach move to next if error如果错误,Powershell foreach 移动到下一个
【发布时间】:2012-03-23 17:57:48
【问题描述】:

我有一个 csv 文件中的计算机列表,这些计算机每周日上午 9 点进行系统映像备份。

hostname    macaddr            comments
TOTO-01     842B2BB728C1       Server Room
KOKO-14     842B2BB7420F       Server Room
FOFO-25     001AA0485902       Server Room

我正在尝试创建一个 powershell 脚本来打开列表中的所有计算机并进行一些检查以查看备份是否成功。

我遇到的问题是,如果脚本未通过任何一项检查,我希望脚本移动到列表中的下一台计算机。

我的代码如下:

param 
(
    [Io.FileInfo]$csvFile = 'C:\Scripts\VipBackUp.csv',
    [Io.FileInfo]$WolCmdExe = 'C:\mgmt\tools\WolCmd.exe'
)

######Get the current date - 20 hours.
$GetCurrentDate = (get-date) - (new-timespan -days 6)
$GetCurrentDate

#####Turn on PC
function TurnOnPc
{
    $TurnOn = invoke-expression "$WolCmdExe $macaddr 192.168.1.0 255.255.255.255"
    write-host ""
    write-host "Turning on $hostname.."
    if($TurnOn)
    {
        write-host "$comp has been turned on"
        write-host ""
    }
    else
    {
        $global:PCTurnOnError = "Yes"
    }
}

#####Test PC connectivity
function PingPC
{
    Start-Sleep  3
    $ping = test-connection -Computername $hostname -count 5 -quiet
    write-host "Checking connection for $hostname"
    if($ping)
    {
        write-host "Connection Found for $hostname"
        write-host ""
    }
    else                          
    {
        $global:PCPingError = "Yes"
        Write-Host "$hostname unreachable"
        write-host ""
    }   
}

#####Check backup files to see if they have been written to.
function CheckWritePC
{
    $global:OriginalWrite = Get-ChildItem "C:\Powershell Testing\$hostname.txt"
    $global:OriginaSize = (Get-ChildItem "C:\Powershell Testing\$hostname.txt").length
    write-host ""
    write-host "Checking the following PC if it has been writen to: $hostname"
    start-sleep 15
    $global:NewWrite = Get-ChildItem "C:\Powershell Testing\$hostname.txt"
    $global:Newsize = (Get-ChildItem "C:\Powershell Testing\$hostname.txt").length
    $compareWrite = compare-object $OriginalWrite $NewWrite -property Name, lastwritetime | where-object {$_.SideIndicator -eq "=>"}
    if($compareWrite)
    {
        write-host "$hostname has been modified"
        $global:HasBeenModified = "Yes"
        write-host ""
    }
    else
    {
        write-host "$hostname has not been modified"
        $global:HasBeenModified = "No"
        write-host ""
    }
}

#####Check to see if an error log has been recorded.
function CheckEventLog
{
    write-host "Checking the following PC for error logs: $hostname"
    $hostname | out-null; get-winevent -providername 'Microsoft-Windows-Backup' -computername $hostname | where {$_.id -eq "8" -and $_.timecreated -ge $GetCurrentDate}
    $hostname | out-null; if(get-winevent -providername 'Microsoft-Windows-Backup' -computername $hostname | where {$_.id -eq "8" -and $_.timecreated -ge $GetCurrentDate})
    { 
        write-host "$comp received the following eventlog ID: 8"
        $global:EventError = "Yes"
        write-host ""
    }
}

#####Check to see that the size has increased or decreased more than 5%.
function CalculatePercentageDifference
{
    $range = 5..-5
    write-host "Checking the size difference for $hostname."
    $b = $global:Newsize - $global:OriginaSize
    $c = $b/$global:OriginaSize * 100
    $RoundedNumber = [system.Math]::Round($c, 0)
    #write-host $RoundedNumber "%"
    if($range -contains $RoundedNumber)
    {
        write-host "$RoundedNumber%: There has not been a big enough change in the file size"
        $global:SizeIsTooSmall = "Yes"
        write-host ""
    }
    else
    {
        write-host "$RoundedNumber% falls within normal parameters."
        write-host ""
    }
}

#####################END FUNCTIONS###################################################

Import-Csv $csvFile.FullName | %  {
    $hostname = $_.hostname
    $macaddr = $_.macaddr

    Foreach ($_.hostname in $file) {
        if ($ErrorMessage){
            $foreach.moveNext()

            TurnOnPC
            if($global:PCTurnOnError -eq 'Yes')
            {
                #write-host "$hostname did not turn on"
                $ErrorMessage = "$hostname Did not turn on"
                write-host ""
                #email
                continue
            }

            PingPC
            if($global:PCPingError -eq 'Yes')
            {
                $ErrorMessage =  "$hostname is unreachable"
                write-host ""
                #email
                continue
            }

            CheckWritePC
            if($HasBeenModified -eq 'No')
            {
                #Write-host "No write"
                $ErrorMessage = "  Backup file has not been written to" 
                #email
                continue
            }

            CheckEventLog
            if($EventError -eq 'Yes')
            {
                $ErrorMessage = "  Received an '8' winlog message"
                #email
                continue
            }
            else
            {
                write-host "No event errors recorded"
                write-host ""
            }

            CalculatePercentageDifference
            if($SizeIsTooSmall -eq 'Yes')
            {
                $ErrorMessage = "  The file size has not changed enough"
                #email
                continue
            }
        }
    }
}

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    您没有进行任何错误处理。如果您在 PowerShell 中遇到终止错误,您需要使用 trap 或使用 try/catch 来捕获它。使用 cmdlet 时也可以使用-ErrorAction SilentlyContinue 参数。

    终止错误将停止所有执行。因此,您需要确定发生终止错误的位置并添加错误处理代码。

    例如:

    try {
        1/$null
    } catch {
        Write-Host ("The error was: " + $_)
    }
    Write-Host "Continuing..."
    

    此 try/catch 构造将向您显示错误消息,但允许继续执行。

    另一个例子:

    trap {
        Write-Host ("The error was: " + $_)
    }
    1/$null
    Write-Host "Continuing..."
    

    【讨论】:

      【解决方案2】:

      这是 continue 语句的演示:

      foreach ($i in 1..5) { 
        if ($i -eq 3) { # "error"
          continue 
        } 
      
        $i 
      }
      
      # output
      1
      2
      4
      5
      

      【讨论】:

        猜你喜欢
        • 2015-01-04
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        • 2013-05-19
        • 1970-01-01
        • 1970-01-01
        • 2014-10-26
        • 2010-10-30
        相关资源
        最近更新 更多