在 x 天后删除文件并忽略一个子文件夹

在 x 天后删除文件并忽略一个子文件夹

虽然使用我在网上找到的另一个 powershell 脚本,但它删除的是目录而不是目录内的文件。整个想法是查看某些文件夹,同时忽略一个文件夹,并删除超过 365 天的文件,同时保留子文件夹。这是我尝试修改的脚本:

# Variables 
$dump_path = "C:\DoceServe"    # set folder path this would be changed to a network drive
$Ignore_Path = "C:\DoceServe\System" # I want to ignore the system folder on the network drive
$max_days = "-365"    # set min age of files
$curr_date = Get-Date    # get the current date
$del_date = $curr_date.AddDays($max_days)   # determine how far back we go based on current date
$includefiles = "*.txt, *.bak, *.csv, *.prn, *.PDF, *.S@#"  # determine what to include in the delete
$excludefiles = "DoceServe Info* , DoceServe Log*"   # Determine what to exclude from the delete  -Exclude $exclude

# delete the files
Get-ChildItem $dump_path -Exclude $excludefiles -Include $includedfiles  | Where-Object { $_.LastWriteTime -lt $del_date } | Remove-Item -Recurse -Force -WhatIf

任何帮助都将不胜感激,因为我刚开始使用 powershell 而且有些内容有点令人困惑。

答案1

  • $dump_path$Ignore_Path需要有尾随\*
  • $includefiles$excludefiles需要是数组。
  • -Recurse参数必须在 Get-ChildItem 上,绝对不能在 Remove-Item 上

该脚本在这里有效(具有不同的参数值)

## Q:\Test\2018\05\11\SF_911512.ps1
$dump_path =   "C:\DoceServe\*"
$Ignore_Path = "C:\DoceServe\System\*"

$max_days = -365
$del_date = (Get-Date).AddDays($max_days)

$includefiles = @("*.txt","*.bak","*.csv","*.prn","*.PDF","*.S@#")
$excludefiles = @("DoceServe Info*","DoceServe Log*")

# delete the files
Get-ChildItem $dump_path -Inc $includefiles -Excl $excludefiles -Recurse |
  Where-Object { !($_.PSIsContainer) -and
                   $_.LastWriteTime -lt $del_date -and
                   $_.Directory -notlike $Ignore_Path } |
    Remove-Item -Force -WhatIf

为了简洁起见,参数名称可以缩短,只要它们是唯一可识别的

相关内容