使用 powershell 连接 txt 文件中的字符串

concatenate the string in the txt file using powershell

我有一个文件“check1.txt,内容如下

     user1
     user2
     user3

我想从文件中取出这个字符串并放入这样的变量中

   "user1@abc.com","user2@abc.com","user3@abc.com"

我使用这段代码:

  $variable1 = """" 
  $variable2 = (Get-content -path "C:\check1.txt") -join "@abc.com"","""



  $variable3 = $variable2 + "@abc.com"""
  $variable4 =  $variable1 + $variable3
     [String[]] $emailTo=$variable4
    [String[]] $emailCc="abcd6@xyz.com","abcd1@xyz.com"

 write-host $variable4 +"hi"

 write-host $emailTo +"To"
 write-host $emailCc +"Cc"

发送报告邮件

Send-MailMessage -To $emailTo -Subject $subject -Body $Body -cc  $emailCc -SmtpServer $smtpServer -From $emailFrom -Priority $priority 

但我收到如下错误:

   "user1@abc.com","user2@abc.com","user3@abc.com" +hi

   "user1@abc.com","user2@abc.com","user3@abc.com" +To

   abcd@xyz.com abcd1@xyz.com +Cc

    Send-MailMessage : The specified string is not in the form required for an e-mail address.
   At C:\Users\Administrator\Desktop\DisconnectedSession\mail.ps1:31 char:17
   + Send-MailMessage <<<<  -To $emailTo -Subject $subject -Body $Body -cc  $emailCc -SmtpServer $smtpServer -From $emailF
  rom -Priority $priority
+ CategoryInfo          : InvalidType: (:) [Send-MailMessage], FormatException
+ FullyQualifiedErrorId : FormatException,Microsoft.PowerShell.Commands.SendMailMessage

问题是虽然变量 $emailTo 和 $emailCc 的格式与我定义的相同,但对于 $emailTo ,脚本对它的解释不同,而对于 $emailCc,它的解释不同导致失败脚本。 任何人都可以建议为 $emailTo 做什么,因为 $emailCc 目前工作正常,无论分配给它什么?

我不太确定您要做什么,但我认为您的 $emailTo 变量是错误的 - 它需要是一个字符串数组。

您可以从您的文件中构建它:

$emailTo = @()
Get-content -path "C:\check1.txt" | % { $emailTo += ,"$_@abc.com" }

这将创建一个空数组,然后迭代您的用户列表,将域附加到每个用户名并将电子邮件地址添加到数组