PowerShell Temizleme Araçları
İlk olarak, belirli bir tarihten sonra en son değiştirilen dizindeki dosyaları silme işlevim var.
#requires -version 3.0
Function Remove-File {
<#
.SYNOPSIS
Delete files based on file age.
.DESCRIPTION
This function will go start at a specified path and delete files and folders that are older than a
specified date and time. The comparison is made to the file's last modified time. The last access time
doesn't always accurately reflect when a file was last used. Typically you will use this function to
clean out temp folders.
.PARAMETER Path
The folder path to search. The default is the temp folder.
.PARAMETER Cutoff
The date time threshold
.PARAMETER Recurse
Recursively search from the starting path.
.PARAMETER Hidden
Include hidden and system files files.
.EXAMPLE
PS C:\> Remove-File -recurse -cutoff (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime -whatif
Remove all files in the temp folder that are older than the computer's startup time.
.EXAMPLE
PS C:\> "C:\work","$env:temp","$env:windir\temp" | Remove-File -cutoff (Get-Date).AddDays(-30) -recurse -hidden
This command will search the 3 specified paths for all files that haven't been modified in 30 days and delete them.
.NOTES
NAME : Remove-File
VERSION : 3.0
LAST UPDATED: 11/11/2013
AUTHOR : Jeffery Hicks
.LINK
https://jdhitsolutions.com/blog/2013/11/powershell-clean-up-tools
.LINK
Get-ChildItem
Remove-Item
.INPUTS
String
.OUTPUTS
None
#>
[cmdletbinding(SupportsShouldProcess)]
Param(
[Parameter(Position=0)]
[ValidateScript({Test-Path $_})]
[string]$Path=$env:temp,
[Parameter(Position=1,Mandatory,
HelpMessage= "Enter a cutoff date. All files after this date will be removed.")]
[ValidateScript({$_ -lt (Get-Date)})]
[datetime]$Cutoff,
[Switch]$Recurse,
[Switch]$Hidden
)
Write-Host "Removing files in $path older than $cutoff" -foregroundcolor CYAN
#create a hashtable of parameters to splat to Get-ChildItem
$paramHash=@{
Path= $Path
ErrorAction= "Stop"
File= $True
}
#add optional parameters
if ($Recurse) {
$paramHash.Add("Recurse",$True)
}
if ($Hidden) {
$paramHash.Add("Force",$True)
}
Try {
$files = Get-ChildItem @paramhash | where {$_.lastwritetime -lt $cutoff}
}
Catch {
Write-Warning "Failed to enumerate files in $path"
Write-Warning $_.Exception.Message
#Bail out
Return
}
if ($files) {
#only remove files if anything was found
$files| Remove-Item -Force
$stats= $files | Measure-Object -Sum length
$msg="Attempted to delete {0} files for a total of {1} MB ({2} bytes)" -f $stats.count,($stats.sum/1MB -as [int]),$stats.sum
Write-Host $msg -foregroundcolor CYAN
} #if $files
else {
Write-Host "No files found to remove" -ForegroundColor Yellow
}
} #close function
İşlev -WhatIf'i destekliyor, böylece onu çalıştırırsam Remove-Item bana yalnızca neyi sileceğini gösterecek. Get-ChildItem'e gönderilecek bir dizi parametre oluşturmak için bir karma tablosu kullanıyorum. Dinamik komutlar oluşturmak için bu tekniği seviyorum. Bu komutu geçici klasörlerimde, bilgisayarın en son başlatıldığı zamandan daha eski dosyaları silmek için kullanıyorum. Benim varsayımım, TEMP'deki son önyükleme zamanından daha eski olan her şeyin silinmesinin adil olduğudur.
Bu işleve bakarsanız, yalnızca dosyaları etkilediğini fark edeceksiniz. Klasörü yalnız bırakır. Sanırım eski klasörleri de kaldırmak için onu değiştirebilirim, ancak klasörün hiyerarşide bir yerde silinmemesi gereken daha yeni bir dosyaya sahip olma ihtimali var, bu yüzden sadece eski dosyalara odaklanmaya karar verdim. Klasörleri temizlemek için şunu kullanıyorum:
#requires -version 3.0
#remove directories that have no files.
<#
****************************************************************
* DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
* THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF *
* YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
* DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. *
****************************************************************
#>
Function Remove-EmptyFolder {
[cmdletbinding(SupportsShouldProcess)]
Param(
[Parameter(Position=0,Mandatory,HelpMessage="Enter a root directory path")]
[ValidateScript({Test-Path $_})]
[string]$Path=$env:temp
)
Write-Host "Removing empty folders in $Path" -ForegroundColor Cyan
#get top level folders
$Folders = Get-ChildItem -Path $path -Directory -Force
#test each folder for any files
foreach ($folder in $folders) {
If (-NOT ($folder | dir -file -Recurse)) {
Write-Host "Removing $($folder.FullName)" -ForegroundColor Red
$folder | Remove-Item -Force -Recurse
}
} #end foreach
} #end Remove-EmptyFolder
Bu komut boş klasörleri veya daha doğrusu dosyası olmayan klasörleri arar. İşlev, belirtilen yoldaki tüm üst düzey klasörleri alır ve ardından her klasörde herhangi bir dosya için yinelemeli olarak arama yapar. Hiçbir dosya bulunamazsa klasör kaldırılır.
İki araç kendi başlarına harikadır. Bunları kullanmak için küçük bir komut dosyası oluşturdum.
#requires -version 3.0
<#
CleanTemp.ps1
****************************************************************
* DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
* THOROUGHLY IN A LAB SETTING. USE AT YOUR OWN RISK. * *
****************************************************************
#>
#dot source functions
. C:\scripts\Remove-EmptyFolder.ps1
. C:\scripts\Remove-File3.ps1
#get last boot up time.
#Get-CIMInstance will return LastBootUpTime as a datetime object. No converting required.
$bootTime = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
#delete files in temp folders older than the last bootup time
Remove-File $env:temp $boottime -recurse -hidden
Remove-File D:\Temp $boottime -recurse -hidden
Write-Host "Removing empty folders" -ForegroundColor Cyan
Remove-EmptyFolder $env:temp
Remove-EmptyFolder D:\temp
Senaryoyu "hazır" bir PowerShell oturumu olarak düşünüyorum. Birkaç klasörü temizlemek için komutları yazmak yerine sadece betiği çalıştırıyorum. Komut dosyasının ne yaptığını bilmek için bazı Write-Host komutları ekledim. Önce tüm eski dosyaları temizliyorum, ardından boş klasörleri silmek için ikinci bir geçiş yapıyorum. Bunları kullanmak istiyorsanız üretim dışı bir ortamda test etmeniz gerektiğini söylemeye gerek yok sanırım.
Eğlence.
