Powershell, cleanup, delete old files, task scheduler« Wróć do listy pytań

example script
Wysłane przez mrmucha
Zadane przez 15/03/2021 10:11
0

1. Cleanup.ps1

$Folder = "C:\ToBackup"
$Daysback = "-7"

Add-Content C:\logs\delete_log.txt   "Cleanup started $((Get-Date).ToString())"

Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays($Daysback)} |
ForEach-Object {
   $_ | del -Force
   $_.FullName | Out-File C:\logs\delete_log.txt  -Append
}

#Delete empty folders and subfolders
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {$_.PsIsContainer -eq $True} |
? {$_.getfiles().count -eq 0} |
ForEach-Object {
    $_ | del -Force
    $_.FullName | Out-File C:\logs\delete_log.txt  -Append
}

2. Task Scheulder

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass –NoProfile –Command "& {Cleanup.ps1; exit $LastExitCode}" > C:\logs.log
Wysłane przez mrmucha
Odpowiedziane 15/03/2021 10:16