windows - Powershell Try/catch - 获取用户

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

我正在学习优雅。我试图理解为什么这个脚本没有捕获警告。

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

最佳答案

调用函数时可以捕获两种情况:错误或警告。您可以在脚本中使用 $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

关于windows - Powershell Try/catch - 获取用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655642/

相关文章:

windows - Fortran 中的清屏

powershell - 使用PowerShell和SMO库从.BAK文件创建新数据库

java - 从 try 中获取一个变量

javascript - 如果 URL 不正确,fetch API 不会在 catch 中显示确切的错误

java - 如何将 selenium Web 驱动程序打开的浏览器窗口置于前面

php - 如果进程停止然后执行url,如何编写批处理/CMD文件以每5分钟检查一次?

c - 在 Windows 上使用 __cdecl 了解 C 函数调用序言

powershell - 按子文件夹列出文件计数

powershell - 使用 Azure Power Shell 将应用程序设置添加到现有 Azure Web 应用程序

javascript - 如何在 javascript/nodejs 中的 try...catch 期间防止双重回调?