简体   繁体   English

PowerShell将电子邮件发送到另一个脚本中的地址列表

[英]PowerShell send email to list of addresses within another script

I am trying to create a PowerShell script that will send an email to a list of people, but the email call is already embedded within a ping script. 我正在尝试创建一个PowerShell脚本,该脚本会将电子邮件发送给人员列表,但是该电子邮件呼叫已嵌入ping脚本中。 This is for a system that only has PowerShell v2.0. 这适用于仅具有PowerShell v2.0的系统。

Computers.txt contains a list of computers to be pinged and on failure will send an email. Computers.txt包含要ping的计算机列表,如果出现故障,将发送电子邮件。

This is my existing script I am trying to modify: 这是我要修改的现有脚本:

Get-Content -path "E:\Computers.txt" | ForEach-Object {
if (-not (Test-Connection -ComputerName $_ -Delay 2 -Quiet)) {
    Send-MailMessage -To "email address" -Subject "$_ is Unreachable" -Body "$_ is unreachable by ping. Next check is in 5 minutes" -SmtpServer "server address" -From "another email address"  
    } 
}

I know that I can use the Get-Content -path "E:\\From_Email.txt" and Get-Content -path "E:\\To_Email.txt" to call the list of email addresses, but I am not sure how to do this within the existing command. 我知道我可以使用Get-Content -path“ E:\\ From_Email.txt”和Get-Content -path“ E:\\ To_Email.txt”来调用电子邮件地址列表,但是我不确定该怎么做在现有命令中。 I have looked online, but I have not found how to nest calling additional text files within PowerShell for a script. 我在网上看过,但还没有找到如何在PowerShell中嵌套调用脚本的其他文本文件的方法。

Do I need to call these files earlier and set them equal to a variable which gets called? 我需要更早地调用这些文件并将它们设置为等于被调用的变量吗? Any help would be greatly appreciated. 任何帮助将不胜感激。 Thank you. 谢谢。

Assuming you have an email address on each line of "E:\\To_Email.txt", the code below should work 假设您在“ E:\\ To_Email.txt”的每一行上都有一个电子邮件地址,则下面的代码应该可以正常工作

$emails = (Get-Content "E:\To_Email.txt") -join ";"
Get-Content -path "E:\Computers.txt" | ForEach-Object {
if (-not (Test-Connection -ComputerName $_ -Delay 2 -Quiet)) {
  Send-MailMessage -To $emails -Subject "$_ is Unreachable" -Body "$_ is unreachable by ping. Next check is in 5 minutes" -SmtpServer "server address" -From "another email address"  
  }
}

The extra first line reads in all lines of the email list file as an array, then joins it with semi-colons, which I think is how your email addresses should be separated. 多余的第一行以数组的形式读取电子邮件列表文件的所有行,然后将其与分号连接,我认为这是应该分隔电子邮件地址的方式。 Worth checking though. 值得检查。

Example content of "E:\\To_Email.txt" “ E:\\ To_Email.txt”的示例内容

person.one@yourdomain.whatever
person.two@yourdomain.whatever
person.three@yourdomain.whatever
person.four@yourdomain.whatever

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM