【问题标题】:Powershell: Delete folder with specific file in itPowershell:删除包含特定文件的文件夹
【发布时间】:2020-04-02 10:30:50
【问题描述】:

我正在尝试在 powershell 中创建一个脚本来删除 C:\Temp 中包含 *.sr_processed 文件的所有文件夹。

我已经有了这个,但这只会删除文件而不是它所在的文件夹。

Get-ChildItem -Path C:\Temp -Include *.sr_processed -File -Recurse | foreach { $_.Delete()}

【问题讨论】:

标签: windows powershell scripting


【解决方案1】:

您告诉它删除文件。要删除文件夹,请执行以下操作:

Get-ChildItem -Path C:\Temp -Include *.sr_processed -File -Recurse | foreach { Remove-Item –path $_.Directory.Fullname}

如果您在一个文件夹中有多个.sr_processed 文件,它可能会多次尝试将其删除。通常删除您正在使用的文件夹是不好的做法。所以一个更好的主意是收集一个列表/哈希中的文件夹并在最后删除它们。

看起来像:

# declare array
$foldersToDelete = @()
# fill array with folder names
Get-ChildItem -Path C:\Temp -Include *.sr_processed -File -Recurse | foreach { $foldersToDelete += $_.Directory.Fullname}
# sort and make unique
$foldersToDelete = $foldersToDelete | Sort-Object | Get-Unique
# delete folders
$foldersToDelete | Remove-Item –path $_

这是从内存中输入的,因此您可能需要对其进行调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2020-05-03
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    相关资源
    最近更新 更多