I have never worked with powershell and I only need a program that is always run at the beginning of the month
What should the program do?
At the beginning of the month it should move all data except for the last month to another folder and zip it there to save storage space.
to my question i have (-31 days) but not every month has 31 days how could i solve it or does it fit like that?
I'm sorry if I explained something wrong here, please let me know.
foreach ($kunde in (Get-ChildItem "C:\Users\kaar\Desktop\Ordneralt" -Exclude *.pdf , *.jpeg, *.png, *.gif ))
{
$dirname = $kunde.name
for ($i=0; $i -lt $dirname.length; $i )
{
$dirbackup = $dirname "BP"
get-childitem -Path "C:\Users\kaar\Desktop\Ordneralt\$dirname\ARCHIV" |
where-object {$_.LastWriteTime -lt (get-date).AddDays(-31)} |
move-item -destination "C:\Users\kaar\Desktop\Ordnerneu\$dirbackup"
}
$dirdate = get-date -format 'yyyy-MM-dd'
$backupname = $dirdate "__" $dirname
Compress-Archive -Path "C:\Users\kaar\Desktop\Ordnerneu\$dirbackup" -DestinationPath "C:\Users\kaar\Desktop\Ordnerneu\$dirbackup\$backupname"
Remove-Item "C:\Users\kaar\Desktop\Ordnerneu\$dirbackup" -Recurse -Include *.pdf -force
}
i was searching for ideas but i didnt find nothing
CodePudding user response:
#code is to get the first date of every month
$firstday=get-date -Day 1
Alternative approach is to schedule your script in Task Scheduler to trigger the PowerShell script on 1st of every month at specified time. Reference link to create a new task in task scheduler
CodePudding user response:
As commented, you can get the number of days in the current month with
$today = Get-Date
$nDays = [DateTime]::DaysInMonth($today.Year, $today.Month)
# set to midnight so it is independent of the actual time the script runs
$refDate = $today.AddDays(-$nDays).Date
Then just use that in your Where-Object clause:
Where-Object {$_.LastWriteTime -lt $refDate}