2017-06-20 107 views
2

我在学习posh。我试图理解为什么这个脚本没有收到警告。Powershell Try/catch - 获取用户

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 

我tryied -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

+0

'得到-user'是不是原生PowerShell命令。这个函数的代码是什么样的? – gms0ulman

+0

'Get-User'被记录为Exchange cmdlet,并且只会从Exchange返回对象。 –

+0

您设置了WarningAction,但不是ErrorAction。当你运行这个时,你的ErrorActionPreference可能是Continue的? –

回答

1

当调用函数Error或Warning时,有两件事可以被捕获。您可以在脚本中全局设置$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

+0

谢谢@ TheIncorrigible1和Paal Braathen。但我试过了--ErrorAction Stop,它没有帮助。我发现这是因为我通过New-PSSession使用Remote-powershell。它在服务器上正常工作。 – apatic