Reputation: 13
Trying with Windows PowerShell to delete all directories that contain a XML-file with a specific content. Getting as far as listing all the files containing the correct pattern with
ls -r -Filter *.xml | ?{ $_ | Select-String -Pattern "ACC_cont"}
but can´t get the paths from the output and delete the directory and all it´s content. There might be more than one direcotry with a XML-file with the right pattern, and I like to delete them all.
Upvotes: 1
Views: 1250
Reputation: 439842
Try the following:
Get-ChildItem -Recurse -Filter *.xml |
Select-String -List -Pattern "ACC_cont" |
Remove-Item -Recurse -LiteralPath { Split-Path -Parent $_.Path } -WhatIf
-WhatIf
previews the operation; remove it to perform actual deletion.
Select-String
directly accepts file-info objects output by Get-ChildItem
from the pipeline.
-List
makes Select-String
stop after the 1st match in a file, which improves efficiency.The match-info objects output by Select-String
have a .Path
property that contains the input file path, so Split-Path -Parent $_.Path
gets a matching file's director path.
Passing Split-Path -Parent $_.Path
inside a script block ({ ... }
) to Remove-Item
's -LiteralPath
parameter is instance of a delay-bind script block that provides parameter values derived dynamically from each input object, so that Remove-Item -Recurse
removes every directory in which a matching XML file was found.
Upvotes: 2