Hi
I’m new to powershell, and I have gather a PS script to help me on a personal project where I need to zip, move logfiles monthly. However I need to find a way to dinamically timestamp the resulting zipped folder monthly.
#create a temporary folder using today’s date
$tempFolderRoot = “C:\Temp_”
$date = Get-Date
$date = $date.ToString(“yyMM01-30”)
$tempFinalFolder = “$tempFolderRoot$date”
New-Item -ItemType directory -Path $tempFinalFolder -Force
On this line $date = $date.ToString(“yyMM01-30”) this is the timestamp the zipped folder will have but I wonder if anyone can help me on how to make it work so if a month has 31 days or 30 days the timestamp will automatically name it according to that
Below is the full script:
#get the list of files in the original folder
$rootFolder = “C:\Windows\System32\LogFiles\W3SVC1\Test Logs”
$archivefolder = “E:\Logs\Intranet\Archive Logs\2018”
$tempVariable = $rootFolder
$files = Get-ChildItem -Path $rootFolder
#create a temporary folder using today’s date
$tempFolderRoot = “C:\Temp_”
$date = Get-Date
$date = $date.ToString(“yyMM01-30”)
$tempFinalFolder = “$tempFolderRoot$date”
New-Item -ItemType directory -Path $tempFinalFolder -Force
#decide how long back to go
$timespan = new-timespan -days 0
#move the files to a temporary location
foreach($file in $files)
{
$fileLastModifieddate = $file.LastWriteTime
if(((Get-Date) - $fileLastModifiedDate) -gt $timespan)
{
Move-Item “$rootFolder$file” -destination $tempFinalFolder
}
}
$CompressionToUse = [System.IO.Compression.CompressionLevel]::Optimal
$IncludeBaseFolder = $false
$zipTo = “{0}\ex{1}.zip” -f $archivefolder,$date
#add the files in the temporary location to a zip folder
Add-Type -AssemblyName “System.IO.Compression.FileSystem”
[System.IO.Compression.ZipFile]::CreateFromDirectory($tempFinalFolder, $ZipTo, $CompressionToUse, $IncludeBaseFolder)
So in theory the resulting naming of each zipped file should be ex180601-30, ex180501-31 and so on.
Any help would be much appreciated.