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

相關問題