尝试/捕获,如果过滤器没有返回任何内容则捕获

时间:2016-10-12 11:02:58

标签: powershell try-catch

我想输出一条消息,如果$ADUser没有返回任何内容,但它不会以某种方式触及catch块:

$Paths = Get-childitem '\\sto-fs-02\Users\Pictures' |Select Fullname
Foreach ($Path in $paths){
$ADName = [io.path]::GetFileNameWithoutExtension($path)
$TrimmedADName = $ADName.Replace('.',' ')
Try
{

    $ADUser = Get-ADUser {name -like $TrimmedADName}
    $ADUser.name
}
catch
{
write-host "$trimmedADName can't be found, fix filename"

}

}

2 个答案:

答案 0 :(得分:3)

您不需要在此处使用try-catch块。只需检查$ADUser是否为空:

$Paths = Get-childitem '\\sto-fs-02\Users\Pictures' |Select Fullname
Foreach ($Path in $paths) {
    $ADName = [io.path]::GetFileNameWithoutExtension($path)
    $TrimmedADName = $ADName.Replace('.',' ')

    $ADUser = Get-ADUser -filter {name -like $TrimmedADName}

    if ($ADUser)
    {
        $ADUser.name
    }
    else
    {
        write-host "$trimmedADName can't be found, fix filename"
    }
}

答案 1 :(得分:0)

FWIW - 一个很好的技巧,如果你想在某些情况下使用try / catch并且不确定是否会抛出终止错误并落入catch,你可以检查变量中的值和创建自己的终止错误。所以你可以这样做:

$Paths = Get-childitem '\\sto-fs-02\Users\Pictures' |Select Fullname
Foreach ($Path in $paths) {
    $ADName = [io.path]::GetFileNameWithoutExtension($path)
    $TrimmedADName = $ADName.Replace('.',' ')
try{
    $ADUser = Get-ADUser -filter {name -like $TrimmedADName}

    if (!$ADUser) {
         throw
    }
} catch {
    write-host "$trimmedADName can't be found, fix filename"
}