我正在尝试编写一个脚本,该脚本将递归扫描目录、带有“.Error”扩展名的本地文件,然后通过电子邮件向一群人发送文件列表。我计划通过 Control-M 运行此脚本,并让它每 20 分钟运行一次。我希望脚本记录自上次运行以来已扫描的文件,而不是将它们包含在电子邮件中。我是一个 powershell 新手,所以我不知道如何做到这一点。下面是我必须扫描文件并发送电子邮件的代码的消毒版本。我非常感谢任何人的帮助。
function sendEmail {
$SMTPServer = "relay.EXAMPLE.com"
$SMTPFrom = "[email protected] /cdn-cgi/l/email-protection"
$EmailAddress = "[email protected] /cdn-cgi/l/email-protection"
send-mailmessage -to $EmailAddress -from $SMTPFrom -Subject "Error loading XPOLL File - $file" -body "This is the body" -smtpserver $SMTPServer
}
##Search for .Error files
$array = @((Get-ChildItem -Path \\SERVER\FOLDER -Recurse -Include *.Error).Fullname)
foreach ($file in $array) {
sendEmail
}
##
尝试将任务分解为简单的步骤:
- 从文件中读取排除列表
- 发现文件
- 根据排除列表过滤文件
- 发电子邮件
- 将新的排除列表附加到文件
$exclusionFilePath = '.\path\to\exclusions\file.txt'
if(-not(Test-Path $exclusionFilePath)){
# Create the exclusion file if it doesn't already exist
New-Item $exclusionFilePath -ItemType File
}
# read list of exclusions from file
$exclusions = Get-Content -Path $exclusionFilePath
# discover files
$array = @((Get-ChildItem -Path \\SERVER\FOLDER -Recurse -Include *.Error).Fullname)
# filter current files against list of exclusions
$array = $array |Where-Object {$exclusions -notcontains $_}
foreach($file in $array){
# send emails
sendEmail
# append new file path to exclusions file
$file |Add-Content -Path $exclusionFilePath
}
额外提示:参数化你的函数
依赖调用上下文中的变量有点反模式,我强烈建议重构你的sendEmail
函数类似于:
function Send-ErrorFileEmail {
param(
[string]$File
)
$MailMessageArgs = @{
SMTPServer = "relay.EXAMPLE.com"
From = "[email protected] /cdn-cgi/l/email-protection"
To = "[email protected] /cdn-cgi/l/email-protection"
Subject = "Error loading XPOLL File - $file"
Body = "This is the body"
}
Send-MailMessage @MailMessageArgs
}
然后在脚本中使用它,例如:
Send-ErrorFileEmail -File $file
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)