ログ ファイルを C:\Logs に毎日書き込むサーバーがいくつかあります。毎月、30 日以上経過したファイルを特定し、それらをアーカイブし、ソース ファイルを削除するスクリプトが実行されることになっています。C:\Logs フォルダには、ログ ファイルと、ログ ファイルを含むサブ フォルダ (名前は 1234、4567、7890) が含まれています。Powershell は初めてなので、このタスクを自動化できることを期待して、以下のスクリプトをまとめました。
このスクリプトは 30 日以上経過したファイルを識別できます (テスト時にファイル名を出力してもらいました) が、アーカイブ ルーチンが開始されると、すべてが C:\Logs フォルダーに圧縮され、ファイルは保持されません。サブフォルダー構造。
スクリプトはおそらく可能な限り最善の方法で書かれていないので、スクリプトを改善して必要なことを実行させる方法について提案があれば、ぜひ聞いてください.
$Hname = hostname #Name of server
$Source = "C:\logs" #Folder where log files reside
$Archive = "C:\logs\$hname\Archive.zip" #Folder where archive file will be created
$Extension = "*.txt" #Only files with this extension will be identified and archived
$Date = Get-Date #Today's date
$Days = "30" #Number of days past today's date that will be archived
$Files = get-childitem $Source -include $Extension -recurse | Where-Object {$_.LastWriteTime -lt $Date.AddDays(-$Days)}
$FileNames = ""
foreach ($File in $Files)
{
write-host "File Name : $File " $File.LastWriteTime
$FileNames = $FileNames + " " + $File
}
write-host "Files to archive : " $FileNames
if($FileNames.Trim() -ne "")
{
[string]$Zip = "C:\apps\7-zip\7z.exe"; #path to 7Zip executable
[array]$arguments = "a", "-tzip", "-y", $Archive, $Source+$Extension;
& $Zip $arguments ;
}
foreach ($File in $Files)
{
write-host "Deleting file :"$File
#remove-item $File -exclude *.zip
}
else
{
write-host "No files to archive"
}
write-host "Archive Completed"