捕获 powershell 中的 if 语句错误

捕获 powershell 中的 if 语句错误

我试图捕捉设置默认值的错误。我不知道该怎么做。如果 smtp 不正确,我想在 smtp 中继中设置默认值。抱歉,我对 powershell 和脚本真的是新手。

    if ($To -eq "")
    {
    write-host "use the default value [email protected]"
    $To = "[email protected]"
    }
    if ($From -eq "")
    {
    write-host "use the default value MailboxReport"
    $From = "[email protected]"
    }
    if ($Subject -eq "")
    {
    write-host "use the default value MailboxReport"
    $Subject = "MailboxReport"
    }
    if ($body -eq "")
    {
    write-host "use the default value mail"
    $body = "mail" 
    }
    if ($SmtpServer -eq "") 
    {
       write-host "use the default value XX.XXX.XXX.XX"
       $SmtpServer = "XX.XXX.XXX.XX"
    }

Send-MailMessage -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport
write-host "******************MailSent******************"

错误

Send-MailMessage:无法解析远程名称:“1235656+”在 C:\Scripts\Exchange\Mailbox.ps1:309 char:21 + Send-MailMessage <<<< -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport + CategoryInfo:InvalidOperation:(System.Net.Mail.SmtpClient:SmtpClient)[Send-MailMessage],SmtpException + FullyQualifiedErrorId:SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

答案1

你的意思是这样的:

try{
    Send-MailMessage -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport -ErrorAction Stop
}
catch{
    $SmtpServer = "XX.XXX.XXX.XX" #default server
    Send-MailMessage -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport
}

相关内容