【问题标题】:How can I recursively delete folder with numerical names using PowerShell如何使用 PowerShell 递归删除具有数字名称的文件夹
【发布时间】:2018-11-13 10:34:41
【问题描述】:

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

$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}

}

【问题讨论】:

  • 您使用什么 PowerShell 版本?添加到您的位置-and $_.Name -match '^\d+$'
  • PSVersion 5.1.15063.786

标签: powershell recursion directory


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我可以使用-like 标签解决这个问题。

    $locations=import-csv "C:\Temp\Scripts\AgeOffDirsGeneral.csv"
    foreach ($location in $locations)
    {
        $Source=$location.Source
        Get-ChildItem  $source  | Where-Object {  $_.psiscontainer -and $_.Name -like '*[0-9]*' } | Foreach-Object {Remove-Item  -Recurse  -Force $_.FullName}
    }
    

    【讨论】:

    • 抱歉,您的要求是to delete if folder name contains only numeric in it,您的like 传递任何包含至少一位数字的任何其他字符的名称。
    最近更新 更多