我想在发现错误时在输出中创建一个空行。这可能吗?
这是我的代码:
$list = ForEach ($mailbox in $mailboxes) {
Get-Mailbox $mailbox | select primarysmtpaddress
If (ErrorAction == $True) { Write-Output `n}
}
$mailboxes
被分配给一个完美运行的get-content命令。选择primarysmtpaddress也正常工作。 If语句及其中的代码不是。
编辑:用'n
的正确转义字符修正了'n答案 0 :(得分:0)
我建议您使用try
和catch
,并在catch中写下空行。
您还使用了错误的转义字符:http://ss64.com/ps/syntax-esc.html
ForEach ($mailbox in $mailboxes)
{
try
{
Get-Mailbox $mailbox | select primarysmtpaddress
}
catch
{
Write-Host `n
}
}
答案 1 :(得分:0)
由于您要保存到变量,因此无法使用Write-Host
,但您可以返回空字符串。 Select primarysmptpaddress
会返回pscustomobject
- primarysmtpaddress
- 属性。由于我们在出错时返回一个空字符串,我会使用-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
""
}
}