【问题标题】:Powershell Try/catch - get-userPowershell Try/catch - 获取用户
【发布时间】:2017-11-23 03:36:22
【问题描述】:

我正在学习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

【问题讨论】:

  • get-user 不是本机 PowerShell 命令。这个函数的代码是什么样的?
  • Get-User 被记录为一个 Exchange cmdlet,并且只会从 Exchange 返回对象。
  • 您设置了WarningAction,但没有设置ErrorAction。运行此程序时,您的 ErrorActionPreference 可能是 Continue?

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


【解决方案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

【讨论】:

  • 谢谢@TheIncorrigible1 和Paal Braathen。但是我尝试了 -ErrorAction Stop 并没有帮助。我发现这是因为我通过 New-PSSession 使用 Remote-powershell。它在服务器上工作正常。
猜你喜欢
  • 2012-11-16
  • 2013-11-25
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
  • 1970-01-01
相关资源
最近更新 更多