首页 > 开发 > PowerShell > 正文

用PowerShell删除N天前或指定日期(前后)创建(或修改)的文件

2020-05-30 20:21:42
字体:
来源:转载
供稿:网友

本来想用批处理的,想想算时间太麻烦了……

立马安装PowerShell看帮助文档,里面有个例子:

以下命令查找 Program Files 文件夹中上次修改日期晚于 2005 年 10 月 1 日并且既不
小于 1 MB 也不大于 10 MB 的所有可执行文件(测试发现没法运行-_-!):

Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object `
-FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) `
-and ($_.Length -le 10m)}

改了一下成为下面的,以删除D:/test及子目录里10天前创建的文件为例,测试请谨慎!
因为内容太长显示成多行,实际上是一行。用“`”字符作为延续符(双引号内的,是重
音符不是单引号),相当于vbs的“_”,它告诉Windows PowerShell下一行是延续部分,
它在整行如果不换行就无法置于库中这种情况下有用。只允许将表达式作为管道的第一
个元素。

一行命令取得过期文件列表:
Get-ChildItem -Path D:/test -Recurse -ErrorAction:SilentlyContinue | `
Where-Object -FilterScript {(((get-date) - ($_.CreationTime)).days -gt 10 `
-and $_.PsISContainer -ne $True)} | Select-Object FullName

一行命令删除过期文件:
Get-ChildItem -Path D:/test -Recurse -ErrorAction:SilentlyContinue | `
Where-Object -FilterScript {(((get-date) - ($_.CreationTime)).days -gt 10 `
-and $_.PsISContainer -ne $True)} | Remove-Item

一行命令删除过期文件(包括删除只读、隐藏):
Get-ChildItem -Path D:/test -Force -Recurse -ErrorAction:SilentlyContinue | `
Where-Object -FilterScript {(((get-date) - ($_.CreationTime)).days -gt 10 `
-and $_.PsISContainer -ne $True)} | Remove-Item -Force
当然,可以用别名简写命令。


或者先在Types.ps1xml文件里找到System.IO.FileInfo,增加Age成员:

<Name>System.IO.FileInfo</Name>
   <Members>
       <ScriptProperty>
           <Name>Age</Name>
           <GetScriptBlock>
              ((get-date) - ($this.creationtime)).days
           </GetScriptBlock>
       </ScriptProperty>
   </Members>

添加的内容是从<ScriptProperty>到</ScriptProperty>,修改后以后不用再加。

脚本内容:

ForEach ($file in Get-ChildItem D:/test/* -Force -Recurse `-ErrorAction:SilentlyContinue)  {    if (($file).Age -ge 10 -and $file.PsISContainer -ne $True)      {$file.Delete()}  }

这里不能使用{Remove-Item -Force "$file"}

脚本扩展名是.ps1,扩展名里的是数字1。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表