2016-04-27 129 views
0

我試圖在發現錯誤時在輸出中創建空行。這可能嗎?Powershell - 嘗試在出現錯誤時出現空行

這裏是我的代碼:

$list = ForEach ($mailbox in $mailboxes) { 
    Get-Mailbox $mailbox | select primarysmtpaddress 
    If (ErrorAction == $True) { Write-Output `n} 
} 

$mailboxes被指派給正常使用一個獲取內容的命令。所選的primarysmtpaddress也正常工作。 If語句和其中的代碼不是。

編輯:更正「N有n

+0

嘿jisaak!我在代碼之前嘗試了四個空格。你是如何得到它正確顯示的? –

+0

只是標記的代碼,並使用格式化的'{}'的editior ;-) –

+0

@ArthurMarquis標準的方法,以紀念在計算器上一個問題的回答是*接受*內其中一個答案可以點擊下面的對勾投票按鈕。沒有必要把它放在標題中。 –

回答

0

的`正確的轉義字符我會建議您使用trycatch,並寫在catch中的空行。

您同時還使用了不正確的轉義字符:http://ss64.com/ps/syntax-esc.html

ForEach ($mailbox in $mailboxes) 
{ 
    try 
    { 
     Get-Mailbox $mailbox | select primarysmtpaddress 
    } 
    catch 
    { 
     Write-Host `n 
    } 
} 
+0

我現在就試試吧! –

+0

似乎沒有工作,仍然得到像正常列表這裏是我使用的確切代碼。 '$ list = foreach($ mailboxes中的$ mailbox){try {Get-Mailbox $ mailbox | select primarySMTPaddress} catch {Write-Host'n}} 對不起,我仍然沒有得到正確的代碼格式。我會努力的。 –

0

既然你保存到你不能使用Write-Host一個變量,但你可以返回一個空字符串。 Select primarysmptpaddress返回pscustomobjectprimarysmtpaddress屬性。由於我們在出錯時返回空白字符串,因此我將使用-ExpandProperty primar...來僅獲取字符串值,因此我們在成功和失敗時都具有相同類型的對象。

$list = ForEach ($mailbox in $mailboxes) { 
    #Try/Catch to catch errors 
    try { 
     #Added -ErrorAction Stop to make sure it goes to catch on error. Might not be necessary (depends on the cmdlet). 
     #Used ExpandProperty to only get the value of primarysmptaddress as a string (since no mail = empty string in catch-block) 
     Get-Mailbox $mailbox -ErrorAction Stop | Select-Object -ExpandProperty primarysmtpaddress 
    } catch { 
     #Blank value. Can't use Write-Host/Out-Host since you're saving to a variable 
     "" 
    } 
} 
+1

Frode F.這完美地工作。我沒有嘗試沒有-ErrorAction Stop,所以我無法確定它是否有必要。非常感謝您花時間幫助PowerShell noobie!我將編輯帖子將其標記爲已回答。再次感謝! –

+1

沒問題。您不必編輯標題。您使用答案左側的複選標記標記正確的答案。這將結束這個問題。歡迎來到StackOverflow並祝你好運。 :-) –

相關問題