Powershell尝试/捕获 - 获取用户

时间:2017-06-20 14:19:33

标签: windows powershell try-catch exchange-server powershell-ise

我正在学习posh。我试图理解为什么这个脚本没有收到警告。

try{
    get-user aaaa -WarningAction Stop
}
catch
{
    Write-Host "hi"
}

这是错误:

get-user : The operation couldn't be performed because object 'aaaa' couldn't be found on
'iDC01.contoso.com'. At C:\Users\Gra***\Desktop\test.ps1:2 char:5
+     get-user aaaa -WarningAction Stop
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-User], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=ME1,RequestId=ebcde0d2-9222-443b-b25a-ef7279fd168e,
      TimeStamp=20.06.2017 13:51:35] [FailureCategory=Cmdlet-ManagementObjectNotFoundException]
      FE0D594D,Microsoft.Exchange.Management.RecipientTasks.GetUser

我试过-WarningActions Stop-ErrorAction Stop,但没有结果。

一般情况下,我已了解try/catch的基础知识,以下脚本可以正常使用。

try{
Get-Process -name xyz -ErrorAction Stop
}
catch{
Write-Host "oops"
}

我正在使用powershell_ise 5.1。你知道get-user有什么问题吗? 另外,我无法使用Get-ADuser

1 个答案:

答案 0 :(得分:1)

调用函数时可以捕获两件事,错误或警告。您可以在脚本中全局设置$WarningPreference$ErrorActionPreference,也可以使用-ea或-wa参数单独设置。在您的示例中,我将使用以下内容确保:

Try {
    Get-User aaaa -wa Stop -ea Stop
} Catch {
    Write-Output "hi"
    Write "[$($_.Exception.GetType().FullName)] - $($_.Exception.Message)"
}

about_Preference_Variables