我需要运行一个预定任务,在每天早上7点触发,并搜索文件夹中任何在过去一天或24小时内有修改日期的文件。 我不知道我目前所做的是否是最好的检查方式,也不知道如何通过电子邮件发送过去24小时内发生变化的文件列表。我不认为FileSystemChecker值得花这么多时间去运行它,因为我读到它可能很麻烦。 我想做的事情,只是寻找有修改日期的文件。 我不必寻找删除的文件或添加的文件电子邮件的文件夹。如果什么都没有改变,那么我需要发送电子邮件给不同的组的人,而不是我做的,如果有改变的文件。我卡在如何做电子邮件的部分。 我被卡住的另一部分是让这个接受unc路径,这样我就可以从另一台服务器上运行任务。
Get-Item C:\folder1\folder2\*.* | Foreach { $LastUpdateTime=$_.LastWriteTime $TimeNow=get-date if (($TimeNow - $LastUpdateTime).totalhours -le 24) { Write-Host "These files were modified in the last 24 hours "$_.Name } else { Write-Host "There were no files modified in the last 24 hours" } }
首先,不要试图把所有代码都塞进一行。如果你这样做,代码会变得不可读,错误很容易犯,但很难发现。
我会做的是这样的事情。
$uncPath = '\\Server1\SharedFolder\RestOfPath' # enter the UNC path here
$yesterday = (Get-Date).AddDays(-1).Date # set at midnight for yesterday
# get an array of full filenames for any file that was last updates in the last 24 hours
$files = (Get-ChildItem -Path $uncPath -Filter '*.*' -File |
Where-Object { $_.LastWriteTime -ge $yesterday }).FullName
if ($files) {
$message = 'These files were modified in the last 24 hours:{0}{1}' -f [Environment]::NewLine, ($files -join [Environment]::NewLine)
$emailTo = '[email protected]'
}
else {
$message = 'There were no files modified in the last 24 hours'
$emailTo = '[email protected]'
}
# output on screen
Write-Host $message
# create a hashtable with parameters for Send-MailMessage
$mailParams = @{
From = '[email protected]'
To = $emailTo
Subject = 'Something Wrong'
Body = $message
SmtpServer = 'smtp.yourcompany.com'
# any other parameters you might want to use
}
# send the email
Send-MailMessage @mailParams
希望能帮到你