ค้นหาเว็บไซต์

เครื่องมือทำความสะอาด PowerShell


อันดับแรก ฉันมีฟังก์ชันในการลบไฟล์ออกจากไดเร็กทอรีที่ถูกแก้ไขครั้งล่าสุดหลังจากวันที่กำหนด

#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

ฟังก์ชันนี้รองรับ -WhatIf ดังนั้นหากฉันเรียกใช้ Remove-Item จะแสดงเฉพาะสิ่งที่จะลบเท่านั้น ฉันใช้แฮชเทเบิลเพื่อสร้างชุดพารามิเตอร์เพื่อแยกเป็น Get-ChildItem ฉันชอบเทคนิคนี้ในการสร้างคำสั่งแบบไดนามิก ฉันใช้คำสั่งนี้ในโฟลเดอร์ชั่วคราวเพื่อลบไฟล์ที่เก่ากว่าครั้งล่าสุดที่คอมพิวเตอร์บูท สมมติฐานของฉันคือสิ่งใดก็ตามใน TEMP ที่เก่ากว่าเวลาบูตครั้งล่าสุดเป็นเกมที่ยุติธรรมสำหรับการลบ

หากคุณดูที่ฟังก์ชันนี้ คุณจะสังเกตเห็นว่ามันมีผลกับไฟล์เท่านั้น มันปล่อยให้โฟลเดอร์อยู่คนเดียว ฉันคิดว่าฉันสามารถแก้ไขมันเพื่อลบโฟลเดอร์เก่าได้เช่นกัน แต่มีโอกาสที่โฟลเดอร์นั้นอาจมีไฟล์ใหม่กว่าอยู่ที่ไหนสักแห่งในลำดับชั้นที่ไม่ควรถูกลบ ดังนั้นฉันจึงตัดสินใจมุ่งเน้นไปที่ไฟล์เก่าเท่านั้น เพื่อล้างโฟลเดอร์ ฉันใช้สิ่งนี้:

#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

คำสั่งนี้ค้นหาโฟลเดอร์ว่างหรือโฟลเดอร์ที่ไม่มีไฟล์ ฟังก์ชันรับโฟลเดอร์ระดับบนสุดทั้งหมดในเส้นทางที่ระบุ จากนั้นค้นหาแต่ละโฟลเดอร์ซ้ำสำหรับไฟล์ใดๆ หากไม่พบไฟล์ โฟลเดอร์นั้นจะถูกลบออก

เครื่องมือทั้งสองนั้นยอดเยี่ยมด้วยตัวมันเอง เพื่อนำไปใช้ ฉันจึงสร้างสคริปต์เล็กๆ ขึ้นมา

#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

ฉันคิดว่าสคริปต์นี้เป็นเซสชัน PowerShell แบบ "กระป๋อง" แทนที่จะพิมพ์คำสั่งเพื่อล้างข้อมูลบางโฟลเดอร์ ฉันก็แค่รันสคริปต์แทน ฉันแทรกคำสั่ง Write-Host บางคำสั่งเพื่อที่ฉันจะได้รู้ว่าสคริปต์กำลังทำอะไรอยู่ ฉันล้างไฟล์เก่าทั้งหมดก่อน จากนั้นจึงทำขั้นตอนที่สองเพื่อลบโฟลเดอร์ว่างๆ ฉันเชื่อว่ามันดำเนินไปโดยไม่ได้บอกว่าหากคุณต้องการใช้สิ่งเหล่านี้ คุณต้องทดสอบในสภาพแวดล้อมที่ไม่ใช่การใช้งานจริง

สนุก.

บทความที่เกี่ยวข้อง