添加到$Error变量时隐藏Powershell错误

ax6ht2ek  于 2023-01-13  发布在  Shell
关注(0)|答案(3)|浏览(149)

我有一个代码块正在执行,它已经设置了一个简单的If/Else块来捕捉错误。我通常会使用Try/Catch,但我工作的Exchange 2010 PS环境不允许我使用大多数Try/Catch功能(而且我无法以任何方式更新或更改它,因为这是客户的系统,他们不愿意)。
问题在于,当使用-ErrorAction“Stop”设置Add-DistributionGroupMember cmdlet时,代码将按预期运行,但每次都会将错误输出到主机,这会惹恼客户(和我),因为所有可能的错误都是通过详细的输出文件处理的,所以它实际上只是红色噪声。
如果我将cmdlet设置为-ErrorAction“SilentlyContinue”,则会隐藏错误文本,但不会按预期将错误添加到$Error[0]位置。-ErrorAction“Ignore”也是如此。代码要求每次出现错误时都将错误添加到$Error变量。
下面是代码:

$ListMembershipsIn | % {

        $Alias = $_.Alias
        $Member = $_.Member

        Add-DistributionGroupMember -Identity $Alias -Member $Member -Confirm:$false -ErrorAction Stop

        if($Error[0] -match "The recipient"){
            Write-Host -ForegroundColor Yellow "Already a member"
            Add-Content -Path $OutputPath -Value "$($Alias),$($Member),Group already contains Member"
        }
        elseif($Error[0] -match "couldn't be found"){
            Write-Host -ForegroundColor Yellow "not found"
            Add-Content -Path $OutputPath -Value "Group does not exist or cannot be found,$($Alias),N/A"
        }
        elseif($Error[0] -match "couldn't find"){
            Write-Host -ForegroundColor Yellow "not found"
            Add-Content -Path $OutputPath -Value "Member does not exist or cannot be found,$($Alias),$($Member)"
        }
        elseif($Error[0] -match "There are Multiple"){
            Add-Content -Path $OuputPath -Value "Member name matches too many recipient - Add Member Manually,$($Alias),$($Member)"
        }
        else{
            Add-Content -Path $OutputPath -Value "Member Successfully Added to Group,$($Alias),$($Member)"
            Write-Host -ForegroundColor Green "Throw Flag here"
        }
    }
xdyibdwo

xdyibdwo1#

您有两个追索选项,可以利用-ErrorVariable公共参数或Try/Catch块来与特定错误交互。

错误变量

当与ErrorVariable交互时,您可以在名称前面添加一个+,以向其附加其他错误,就像$Error自动变量一样,例如:-ErrorVariable '+MyError'

$ListMembershipsIn | ForEach-Object {
    $Alias = $_.Alias
    $Member = $_.Member
    Add-DistributionGroupMember -Identity $Alias -Member $Member -ErrorVariable 'MyError'

    ## No error = good, continue the next iteration of the loop
    If (-not $MyError)
    {
        Add-Content -Path $OutputPath -Value "Member Successfully Added to Group,$Alias,$Member"
        Write-Host -ForegroundColor Green "Throw Flag here"
        Continue
    }

    Switch -Regex ($MyError.Exception.Message)
    {
        'The recipient'
        {
            Write-Host -ForegroundColor Yellow "Already a member"
            Add-Content -Path $OutputPath -Value "$Alias,$Member,Group already contains Member"
        }
        "couldn't be found"
        {
            Write-Host -ForegroundColor Yellow "not found"
            Add-Content -Path $OutputPath -Value "Group does not exist or cannot be found,$Alias,N/A"
        }
        "couldn't find"
        {
            Write-Host -ForegroundColor Yellow "not found"
            Add-Content -Path $OutputPath -Value "Member does not exist or cannot be found,$Alias,$Member"
        }
        'There are Multiple'
        {
            Add-Content -Path $OuputPath -Value "Member name matches too many recipient - Add Member Manually,$Alias,$Member"
        }
    }
}

尝试/接住

$ListMembershipsIn | ForEach-Object {
    $Alias = $_.Alias
    $Member = $_.Member

    Try
    {
        Add-DistributionGroupMember -Identity $Alias -Member $Member -ErrorAction 'Stop'

        ## No error thrown = successful processing
        Add-Content -Path $OutputPath -Value "Member Successfully Added to Group,$Alias,$Member"
        Write-Host -ForegroundColor Green "Throw Flag here"
    }
    Catch
    {
        Switch -Regex ($_.Exception.Message)
        {
            'The recipient'
            {
                Write-Host -ForegroundColor Yellow "Already a member"
                Add-Content -Path $OutputPath -Value "$Alias,$Member,Group already contains Member"
            }
            "couldn't be found"
            {
                Write-Host -ForegroundColor Yellow "not found"
                Add-Content -Path $OutputPath -Value "Group does not exist or cannot be found,$Alias,N/A"
            }
            "couldn't find"
            {
                Write-Host -ForegroundColor Yellow "not found"
                Add-Content -Path $OutputPath -Value "Member does not exist or cannot be found,$Alias,$Member"
            }
            'There are Multiple'
            {
                Add-Content -Path $OuputPath -Value "Member name matches too many recipient - Add Member Manually,$Alias,$Member"
            }
        }
    }
}
kcwpcxri

kcwpcxri2#

看起来Add-DistributionGroupMember命令在指定时没有填充ErrorVariable。我发现没有办法避免不需要的输出,所以我用Tristan的技巧而不是异常处理来处理这个错误(这绝对是好的,但不适合我自己的开发):

$Error.clear()
Add-DistributionGroupMember -Identity $mySite.MailingList -Member $emailAddress
if ($Error.count -eq 0) {
    $script:logger["ldissue"] += "<li>Liste de diffusion $($mySite.MailingList) : La ressource <b>$($ADRecord.Name)</b> ($($ADRecord.SamAccountName) - $($BoondRecord.flags)) a été ajoutée à la liste</li>"
} else {
    $script:logger["ldissue"] += "<li>Liste de diffusion $($mySite.MailingList) : La ressource <b>$($ADRecord.Name)</b> ($($ADRecord.SamAccountName) - $($BoondRecord.flags)) n'a pas pu être ajoutée à la liste (<i>$($Error[0])</i>)</li>"
}
pieyvz9o

pieyvz9o3#

使用“-ErrorAction Continue”,这不会抑制错误,但会确保脚本继续运行,并将错误放置在$Error变量中。
您还可以使用$Error.clear()命令删除会话中存储的任何错误。

相关问题