PowerShell循环逻辑错误 无法配对同名pptx/png文件发送邮件
错误原因
原脚本的嵌套循环逻辑存在两个核心问题,导致匹配结果不符合预期:
- 内层遍历png文件夹的循环中,每次迭代都会覆盖
$Screenshot变量,整个内层循环执行结束后,$Screenshot只会保留png文件夹里最后一个被遍历到的文件,也就是你遇到的永远匹配C.png的问题 - 内层循环完全没有做文件名匹配判断,没有把当前pptx的文件名和png文件名做关联,只是无意义遍历完了所有png文件。
修复后代码
不需要做双层循环,拿到pptx的无后缀文件名后,直接拼接对应同名png的路径即可,同时修复原脚本的语法问题、增加异常校验:
# 提前配置通用发件参数,根据实际情况修改 $year = Get-Date -Format "yyyy" $smtpsettings = @{ From = "发件人邮箱@example.com" To = "收件人邮箱@example.com" SmtpServer = "SMTP服务器地址" Port = 587 UseSsl = $true Credential = Get-Credential } Get-ChildItem "C:\APPS\Deployments" -Filter *.pptx | Foreach-Object { $pptFile = $_.FullName $DeploymentName = [System.IO.Path]::GetFileNameWithoutExtension($pptFile) # 直接拼接同名png的完整路径 $pngPath = Join-Path -Path "C:\APPS\Screenshots" -ChildPath "$DeploymentName.png" # 校验对应png是否存在,不存在则跳过 if (-not (Test-Path -Path $pngPath -PathType Leaf)) { Write-Warning "部署项 $DeploymentName 未找到同名截图文件 $pngPath,跳过发件" return } try { Send-MailMessage @smtpsettings ` -Attachments $pptFile, $pngPath ` -Subject "FOR REVIEW & APPROVAL: GC.019.1: Separation of environments $DeploymentName - $year" ` -Priority High ` -Body "<font face='Californian FB'> Hello ABC, <br /> <br /> This email is in regards to executing Annual control Separation of environments (Development, Acceptance and Production) for the $year for the deployment $DeploymentName<br /> <br /> Please find attached the landscape document and the screenshots as captured from the actual deployments.<br /> <br /> Evidences for review:<br /> <br /> 1. Latest landscape document<br /> <br /> 2. Screenshots from different environments as specified in the landscape document<br /> <br /> <font face='Times New Roman' color='blue'> ===================================== <br /> <br /> Thanks & Regards, <br /> Siddhartha Das<br />" ` -BodyAsHtml -Encoding utf8 -Verbose -ErrorAction Stop Write-Host "部署项 $DeploymentName 对应邮件发送成功" } catch { Write-Warning "部署项 $DeploymentName 邮件发送失败:$($_.Exception.Message)" } }
改动说明
- 移除了无意义的内层png遍历逻辑,通过文件名直接拼接目标png路径,执行效率更高,匹配逻辑完全准确
- 新增png文件存在性校验,避免因为缺失对应截图导致发件报错中断整个流程
- 修复了原脚本中HTML Body字符串未闭合的语法错误,将原utf32编码调整为兼容性更好的utf8
- 增加执行过程提示,方便快速定位发送失败的项
内容的提问来源于stack exchange,提问作者Siddhartha Das
相关产品推荐
相关产品推荐

