使用Power Shell 1.0

时间:2017-03-09 16:16:07

标签: powershell

我试图使用OG Powershell 1.0向多个收件人发送电子邮件。但是我失败了。我想我误解了foreach循环,但我不确定。有人可以帮我吗?

[string[]]$receipients = "my@mail.com", "mysecond@mail.com"

foreach ($person in $receipients){
    $mail = @{
        SmtpServer = 'mycoolserver.com'
        Port = 33
        From = "me"
        To = "$person"
        Subject = "mycoolsubject"
        Body = "Hey guys!"
    }
    Send-MailMessage @mail 
    Write-Host "$person received"
}

它也只记录收到的my@mail.com mysecond@mail.com。 (这就是我认为循环定义错误的原因。)

2 个答案:

答案 0 :(得分:0)

您正在使用参数Splatting这是PowerShell v2的新功能,它不适用于PS v1。

您需要直接分配参数,如下所示:

[string[]]$recipients = "my@mail.com", "mysecond@mail.com"

foreach ($person in $recipients)
{
    Send-MailMessage `
        -SmtpServer 'mycoolserver.com' `
        -Port 33 `
        -From "me" `
        -To "$person" `
        -Subject "mycoolsubject" `
        -Body "Hey guys!" `
    Write-Host "$person received" `
}

答案 1 :(得分:0)

在使用PS v1时,不能使用-Port参数。 如果您乐意使用默认端口25,那么以下代码应该对您有用(包括James C的建议):

[string[]]$recipients = "my@mail.com", "mysecond@mail.com"
foreach ($person in $recipients)
{
    Send-MailMessage `
        -SmtpServer "mycoolserver.com" `
        -From "me@domain.com" `
        -To "$person" `
        -Subject "mycoolsubject" `
        -Body "Hey guys!"
    Write-Host "$person received"
}

如果您必须使用其他端口,例如问题中的端口33,请尝试以下版本:

[string[]]$recipients = "my@mail.com", "mysecond@mail.com"
foreach ($person in $recipients)
{
    $mailfrom = "me@domain.com"
    $mailto = $person
    $mail = New-Object System.Net.Mail.MailMessage($mailfrom, $mailto)
    $mail.Subject = "mycoolsubject"
    $mail.Body = "Hey guys!"
    $mailserver = "mycoolserver.com"
    $mailclient = New-Object System.Net.Mail.SmtpClient
    $mailclient.Host = $mailserver
    $mailclient.Port = 33
    $mailclient.send($mail)
    Write-Host "$person received"
}