PowerShell删除最后一个错误

时间:2014-10-13 07:43:24

标签: powershell error-handling

在我的PowerShell脚本中,我尝试进行一些错误处理。但是,我依赖于使用Try/Catch子句的高级函数。因此,偶尔函数中的代码块会失败,并在生成错误后转到Catch子句。此时变量$Error填充了一个错误。

如果我在我的脚本中查询变量$Error它告诉我有一条记录,这是正确的。但我想知道是否有可能只删除Catch子句中函数中的最后一个错误?因此,我可以保持$Error变量清除脚本错误。

问题出在Get-ADTSProfileHC之内。我尝试用$Error[0] | Remove-Item删除最后一个错误,但失败了。

功能:

Function Get-ADusersHC {

    [CmdletBinding(SupportsShouldProcess=$True)]
    Param(
         [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true,Position=0)]
         [String[]] $OU
    )

    Begin {
        Function Get-ADOUNameHC {
            $CanonicalName = $_.CanonicalName
            [System.Collections.ArrayList]$Pieces = $CanonicalName.split(“/”) 
            $Pieces.Remove($Pieces[-1])
            $OU = $Pieces -join '\'
            $OU -replace ($Pieces[0],$Pieces[0].ToUpper())
        }

        Function Get-ADManagerDisplayNameHC {
            $m = Get-ADObject -Identity $_.manager -Properties displayName,cn
            if($m.ObjectClass -eq "user") { $m.displayName } Else{ $m.cn }
        }

        Function Get-ADTSProfileHC {

            [CmdletBinding()]
            Param(
                [Parameter(Mandatory=$true,Position=0)]
                [String] $DistinguishedName,
                [parameter(Mandatory=$true,Position=1)]
                [ValidateNotNullOrEmpty()]
                [ValidateSet('UserProfile','AllowLogon','HomeDirectory','HomeDrive')]
                [String]$Property
            )

            Begin {
                $User = [ADSI]"LDAP://$DistinguishedName"
            }

            Process {
                Try {
                    Switch ($Property) {
                        'AllowLogon'    {if ($($User.psbase.InvokeGet('allowLogon')) -eq '1'){$True}else{$False}}
                        'HomeDirectory' {$User.psbase.InvokeGet('TerminalServicesHomeDirectory')}
                        'HomeDrive'     {$User.psbase.InvokeGet('TerminalServicesHomeDrive')}
                        'UserProfile'   {$User.psbase.InvokeGet('TerminalServicesProfilePath')}
                    }
                }
                Catch {
                    # When we receive an error, it means the field has never been used before and is blank
                    # this is due to an error in the AD (same problem with the Quest CmdLet), AllowLogon is 
                    # always 'TRUE' but we don't set it because we can't read it sometimes so we write 'blanks'
                    Write-Output $null
                }
            }
        }
    }

    Process {    
        Foreach ($_ in $OU) {
            Write-Verbose "Function Get-HCADusersNoManager > OU: $_"
            Write-Verbose "Function Get-HCADusersNoManager > Manager field empty"
            Get-ADUser -SearchBase $_ -Filter 'SAMAccountName -eq "shenn"' -Properties * |
            #Get-ADUser -SearchBase $_ -Filter * -Properties * |
            Foreach {
                $Properties = ([Ordered] @{
                        "Creation date" = $_.whenCreated;
                        "Display name" = $_.displayName;
                        "CN name" = $_.name;
                        "Last name" = $_.sn;
                        "First name" = $_.givenName;
                        "Logon name" = $_.sAMAccountName;
                        "Manager" = if($_.manager){Get-ADManagerDisplayNameHC};
                        "Employee ID" = $_.EmployeeID;
                        "HeidelbergcCement Billing ID" = $_.extensionAttribute8
                        "Type of account" = $_.employeeType;
                        "OU" = Get-ADOUNameHC;
                        "Notes" = $_.info -replace "`n"," ";
                        "E-mail" = $_.EmailAddress;
                        "Logon script" = $_.scriptPath;
                        "TS User Profile" = Get-ADTSProfileHC $_.DistinguishedName 'UserProfile';
                        "TS Home directory" = Get-ADTSProfileHC $_.DistinguishedName 'HomeDirectory';
                        "TS Home drive" = Get-ADTSProfileHC $_.DistinguishedName 'HomeDrive';
                        "TS Allow logon" = Get-ADTSProfileHC $_.DistinguishedName 'AllowLogon'
                        })
                $Object = New-Object -TypeName PSObject -Property $Properties
                Write-Output $Object
            }
        }
    } 
}

2 个答案:

答案 0 :(得分:3)

$error.Remove($error[0])

不要忘记先检查是否有错误。

答案 1 :(得分:0)

 $Error.Remove($error[$Error.Count-1])

如果errors变量为空,则不会出现任何异常

我希望它有所帮助