当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 清理工具

作者:精品下载站 日期:2024-12-14 07:40:33 浏览:14 分类:玩电脑

PowerShell 清理工具


[玩转系统] 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 将仅显示它将删除的内容。我使用哈希表构建一组参数以splat 到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 命令,这样我就可以知道脚本在做什么。我首先清理所有旧文件,然后进行第二次删除所有空文件夹。我相信,不言而喻,如果你想使用这些,你必须在非生产环境中进行测试。

享受。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯