来自模块的 PowerShell 错误处理

问题描述 投票:0回答:1

我在模块内的错误处理方面遇到了一个奇怪的问题。当我在 ISE 编辑器中复制高级函数并从那里运行它时,我没有看到任何报告的错误。因为这是期望的行为。但是,当我将相同的函数粘贴到模块文件 (

Toolbox.ActiveDirectory.psm1
) 中并从那里调用它时,它确实会填充变量
$Error

我真的不明白为什么它从模块内而不是脚本窗格内的函数

Get-ADTSProfileHC
报告错误。正如你所看到的,我删除了
Catch
子句中的最后一个错误(感谢 DanL 在上一个问题中的帮助)。

控制台和模块的错误处理似乎有所不同。

功能:

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
                $Error.Remove($Error[0])
            }
        }
    }
}

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
        }
    }
} 

}

错误:

Exception calling "InvokeGet" with "1" argument(s): "The directory property cannot be foun
d in the cache.
"
At C:\Program Files\WindowsPowerShell\Modules\Toolbox.ActiveDirectory\Toolbox.ActiveDirect
ory.psm1:299 char:42
+                         'UserProfile'   {$User.psbase.InvokeGet('TerminalService ...
+                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodTargetInvocation
powershell error-handling
1个回答
4
投票

感谢 Microsoft 工程师在 StackOverflow 上发布的另一篇帖子,我找到了答案。看来模块的

$Error
变量需要在
Global
范围内更改。

简而言之,我必须将

$Error.Remove($Error[0])
更改为:

$Global:Error.Remove($Global:Error[0])
$Global:Error.RemoveAt(0) # same but shorter
© www.soinside.com 2019 - 2024. All rights reserved.