首页 > 解决方案 > 如何使用 PowerShell 递归删除具有数字名称的文件夹

问题描述

我有根据修改日期删除文件夹的脚本。如果文件夹名称中仅包含数字,有人可以帮我删除吗?

$locations=import-csv "C:\Temp\Scripts\AgeOffDirsGeneral.csv"

foreach ($location in $locations)
{

    $Source=$location.Source

    Get-ChildItem  $source  |Where-Object  {$_.psiscontainer}  | Foreach-Object {Remove-Item  -Recurse  -Force $_.FullName}

}

标签: powershellrecursiondirectory

解决方案


Remove-Item 接受管道输入,因此不需要 ForEach。
如果输出看起来正常,请删除-WhatIf

locations=import-csv "C:\Temp\Scripts\AgeOffDirsGeneral.csv"

foreach ($location in $locations){

    $Source=$location.Source

    Get-ChildItem  $source -Dir -Recurse|
      Where-Object  { $_.Name -match '^\d+$'}  | 
        Remove-Item -Force -WhatIf
}

顺便说一句,中间变量 $source 可以避免直接插入 $location.Source


推荐阅读