我有以下脚本,它可以正常工作,如果我的文件存在2天,我希望它能够向我发送电子邮件。我不确定如何使电子邮件部分正常工作。 谢谢
$fullPath = "\\test\avvscan.dat"
$numdays = 2
$numhours = 1
$nummins = 1
function ShowOldFiles($path, $days, $hours, $mins)
{
$files = @(get-childitem $path -include *.* -recurse | where
{($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and
($_.psIsContainer -eq $false)})
if ($files -ne $NULL)
{
for ($idx = 0; $idx -lt $files.Length; $idx++)
{
$file = $files[$idx]
write-host ("Old: " + $file.Name) -Fore Red
}
}
}
ShowOldFiles $fullPath $numdays $numhours $nummins
答案 0 :(得分:1)
可能是这样的:
$fullPath = "\\test\avvscan.dat"
$numdays = 2
$numhours = 1
$nummins = 1
function Get-OldFiles($path, $days, $hours, $mins) {
$refDate = (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)
Get-ChildItem $path -Recurse -File |
Where-Object {($_.LastWriteTime -lt $refDate)} |
ForEach-Object {
Write-Host ("Old: " + $_.FullName) -ForegroundColor Red
# emit an object containing the interesting parts for your email
[PSCustomObject]@{
'File' = $_.FullName
'LastWriteTime' = $_.LastWriteTime
}
}
}
$oldFiles = @(Get-OldFiles $fullPath $numdays $numhours $nummins)
if ($oldFiles.Count) {
# send an email if there are old files found
$body = $oldFiles | Format-Table -AutoSize | Out-String
# look for more options here: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-3.0
Send-MailMessage -From "someone@yourdomain.com" -To "you@yourdomain.com" -SmtpServer "your.smtp.server" -Subject "Old files in $fullPath" -Body $body
}