[玩转系统] PowerShell 清理工具
作者:精品下载站 日期:2024-12-14 07:40:33 浏览:14 分类:玩电脑
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 命令,这样我就可以知道脚本在做什么。我首先清理所有旧文件,然后进行第二次删除所有空文件夹。我相信,不言而喻,如果你想使用这些,你必须在非生产环境中进行测试。
享受。
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag