簡體   English   中英

Powershell 腳本檢查文件的修改日期並發送 email 如果更改

[英]Powershell script check modified date of files & send email if changed

我需要運行一個計划任務,該任務將在每天早上 7 點觸發,並在文件夾中搜索任何具有在最后一天或 24 小時內更改的修改日期的文件。 我一直堅持到目前為止我所做的是否是進行此檢查的最佳方法,而且我不確定如何將其發送到 email 的文件中,其中包含最后更改的文件列表24小時。 我不認為 FileSystemChecker 值得花時間讓它運行,因為我讀過它可能很麻煩。 我正在嘗試做一些事情,只查找修改日期已更改的文件。 我不必查找已刪除的文件或添加的文件 email 文件夾。 如果沒有任何變化,那么我需要將 email 發送給不同的人,而不是如果有文件發生了變化。 我被困在如何做 email 部分。 我堅持的另一部分是讓它接受一個 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 = 'folskthatwanttoknowaboutmodifications@yourcompany.com'
}
else {
    $message = 'There were no files modified in the last 24 hours'
    $emailTo = 'folskthatwanttoknowifnothingismodified@yourcompany.com'
}

# output on screen
Write-Host $message

# create a hashtable with parameters for Send-MailMessage
$mailParams = @{
    From       = 'you@yourcompany.com'
    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

希望有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM