2012-04-19 54 views
2

我在PowerShell中有这样的功能。当用户传递任何参数的空字符串时,PowerShell会验证并引发异常。我如何处理这种例外情况?Powershell - 异常通过功能上的“验证”属性引发

function CheckADUser() 
{ 
    param(
      [ValidateLength(1,256)] 
      [string]$domainName, 
      [ValidateLength(1,256)] 
      [string]$username, 
      [ValidateLength(1,256)] 
      [string]$password) 
    Process{ 
    $fullyQualifiedUser = $domainName+"\"+$username 
    $domain = New-Object DirectoryServices.DirectoryEntry("", $fullyQualifiedUser, $password) 
    return $domain.name 
    } 
} 

回答

2

使用try/catch块处理异常:

try { 
    checkaduser $null $null $null 
} 
catch [System.Management.Automation.ValidationMetadataException] { 
    # exception handling code 
}