如何将文件添加到变量Powershell中



除了我在这里所做的:

使用Powershell循环浏览excel文件

我想发送一个只包含传输文件的邮件,我遇到了一个小问题。为此,我使用下面的脚本将文件添加到变量$FilenameFR中。

这是我尝试过的

#Look for each number in the columns selected    
for($j=1; $j -le $rowMax-1; $j++){

$Noria = $sheet.cells.Item($RowNoria+$j, $colNoria).text
$NheSN = $sheet.cells.Item($RowNheSN+$j, $colNheSN).text
$Site = $sheet.cells.Item($RowSite+$j, $colSite).text
if ($Noria -like $SBF -and $NheSN -eq $SN) {  
Write-Host ($Noria)
Write-Host ($Site)
write-Host ($NheSN)

If ($Site -eq "TMF" -or $Site -eq "TSF") {
Copy-item "P:MK_M$F" -Destination "\inshare.collab.group.safranCOMNoriaCCoCTest_MK_DFrance"
$FR = $FR + 1 #coutn how many files I transfered
$FilenameFR += $F #here for every file transfered i add it's name to this variable

但是当我在邮件中用这个脚本调用$FilenameFR

$Mail.Body = 
"Hello,
You've received $FR files, if you Could please treat the certificates received on your folder in the next few days it would be very good.
Please find the link to the folder below :
....
Thank you for your understanding and have a nice day.
PS. The files are :
"
foreach ($File in $FilenameFR) {     # Cette boucle c'est pour avoir un nom de Fichier par ligne dans le mail
$Mail.Body += "$File"
}
$Mail.Send()   
}

不是把每个文件放在a行,而是把它们一个接一个地放在另一个。

示例:File1.pdfFile2.pdfFile3.pdf…

你能帮我一下吗?

如果有什么不清楚的地方请告诉我,非常感谢你的帮助

假设变量$F具有每次迭代的文件名,并且在主循环之前将变量$FR设置为零,您不希望将具有+=的文件名添加到(直到那时)未定义的变量。
而不是capture将文件名作为字符串数组,然后在电子邮件中使用换行符将它们连接起来。

$FR          = 0  # initialize the counter to 0
$source      = 'P:MK_M'
$destination = '\inshare.collab.group.safranCOMNoriaCCoCTest_MK_DFrance'
# loop through the files
$FilenameFR = for ($i = 0; $i -lt $filename.Count; $i++) {
$F     = $filename[$i].Name
$SN    = $F.split("_")[0]
$split = $F.split("_")[1]
$SB    = -join $split[-3..-1]
$SBF   = "*_*$SB`_*"
# Look for each number in the columns selected    
for ($j = 1; $j -le $rowMax-1; $j++) {    
$Noria = $sheet.cells.Item($RowNoria + $j, $colNoria).text
$NheSN = $sheet.cells.Item($RowNheSN + $j, $colNheSN).text
$Site  = $sheet.cells.Item($RowSite  +$j, $colSite).text
if ($Noria -like $SBF -and $NheSN -eq $SN) {  
Write-Host "$Noria`r`n$Site`r`n$NheSN"
if ($Site -eq "TMF" -or $Site -eq "TSF") {
Copy-Item -Path (Join-Path -Path $source -ChildPath $F) -Destination $destination
# output the filename so it gets collected in variable $FilenameFR
$F
$FR++   # increment the file counter
}
}
}
}
你现在有了一个数组如果要在邮件正文中使用$FilenameFR变量,可以这样做:
$Mail.Body = "@
Hello,
You've received $FR files, if you Could please treat the certificates received on your folder in the next few days it would be very good.
Please find the link to the folder below :
....
Thank you for your understanding and have a nice day.
PS. The files are :
%%TRANSFERREDFILES%%
@" -replace '%%TRANSFERREDFILES%%', ($FilenameFR -join [environment]::NewLine)
$Mail.Send()   

当然,如果这封邮件要以HTML格式发送,您需要在<br />而不是[environment]::NewLine中加入文件名:

-replace '%%TRANSFERREDFILES%%', ($FilenameFR -join '<br />')

最新更新