简体   繁体   English

删除powershell脚本中的某些文件

[英]Deleting certain files in powershell script

I have a powershell script that goes through a directory and deletes files that are older than 18 months. 我有一个PowerShell脚本,它通过一个目录并删除超过18个月的文件。 Most of the files follow the following naming convention: 大多数文件遵循以下命名约定:

20140628

However, some of the files do not. 但是,有些文件没有。 I am trying to make the script ignore these files and just delete the files that follow the naming convention. 我试图让脚本忽略这些文件,只是删除遵循命名约定的文件。 For some reason, though, the script below is doing the exact opposite of that and deleting the files that do not follow the naming convention and leaving the ones that do. 但是,出于某种原因,下面的脚本与此完全相反,并删除不遵循命名约定的文件,并保留那些文件。 How would I modify the script to fit my needs? 我如何修改脚本以满足我的需求? Any help would be greatly appreciated. 任何帮助将不胜感激。

$targetdirectory = "\\DPR320-W12-1600\PRTG"
$CleanupList = Get-ChildItem $targetdirectory\test
$Threshold = (get-date).AddMonths(-18)
$culture = [Globalization.CultureInfo]::InvariantCulture

foreach ($DirName in $CleanupList)
{
try {
  [datetime]::ParseExact($DirName.BaseName, 'yyyyMMdd', $culture)
  Remove-Item $DirName.FullName -Force -Recurse
} 

catch {

  continue
}

}
$targetDirectory = "\\DPR320-W12-1600\PRTG"
$cleanupList = Get-ChildItem $(Join-Path $targetdirectory "test")
$threshold = (Get-Date).AddMonths(-18)
$culture = [Globalization.CultureInfo]::InvariantCulture

foreach ($dirName in $cleanupList) {
    try {
        $dateFromName = [datetime]::ParseExact($dirName.BaseName, "yyyyMMdd", $culture)

        if($dateFromName -le $threshold) {
            Remove-Item $dirName.FullName -Force -Recurse
        }
    } catch {
        Continue
    }
}

If parsing as a date fails, an error will be thrown and file will not be deleted. 如果解析为日期失败,则会引发错误并且不会删除文件。

I'm not even sure Continue is needed here, but you cannot remove the catch block. 我甚至不确定这里是否需要Continue ,但你不能删除catch块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM