I have a script for zipping up old files. I know using Windows Compression isn't ideal, so I will make the script run using 7-Zip later on. For now though, I just want see how I can make my current script better. By better I mean, how could I make this code cleaner or neater? How could I make the script more effective? Here is the code:
Write-Output("Beginning script....")
#File path of file to be cleaned
$File_Path = "C:\Users\Administrator\Downloads\Testing\*"
#Location of ZIP file
$Send_To = "C:\Users\Administrator\Documents\ARCHIVE2"
#Location of old files before being zipped
$Old_Files = "C:\Users\Administrator\Documents\OLD_FILES"
#Time frame for files
$Days = "-65"
$now = Get-Date
$last_Write = $now.AddDays($Days)
#Filtering files according to time parameters
$Filter = Get-ChildItem -Path $File_Path | Where-Object { $_.LastWriteTime -lt $last_Write }
#Moving old files to destination folder
if (!$Filter){
Write-Host "Variable is null"
}
else{
Move-Item $Filter -Destination $Old_Files
Write-Output("Moving files....")
}
#Compressing destination folder if there is folders in $Old_Files folder
if (!(Test-Path $Old_Files)) {
Write-Output("No old files found")
}
else{
Compress-Archive -Path $Old_Files -DestinationPath $Send_To -Update
Write-Output("Old files zipped!")
Remove-Item -Path $Old_Files -Force
}
Write-Output("Script is finished")
#Moving old files to destination folder
part.Compress-Archive
accepts pipeline input (ByPropertyName) instead of-Path
/-LiteralPath
. Use$Filter | Compress-Archive -DestinationPath $Send_To -Update -CompressionLevel Optimal
. For planned7-Zip
, use its@{listfile}
facility; create an auxiliary list file from$Filter.FullName
usingUTF8
encoding (7-Zip
's default). \$\endgroup\$