1

I want to remove the following files from the source, however in the source there is a sub-directory that contains files with similar names. When I run the following command it is deleting files in the sub-directory with similar file name. Is there a way to just delete the files from the source and not the sub-directory?

Example: test_1_file, test_2_file, test_3_file exists in each directory, TestFolder and TestFolder/sub

$source = testfolder 
remove-item -Path $source -filter test_*_file -recurse -force
BenH
  • 9,766
  • 1
  • 22
  • 35
Mike
  • 133
  • 2
  • 4
  • 13

2 Answers2

7

It's usually easiest to pipe the output of Get-ChildItem cmdlet into Remove-Item. You then can use the better filtering of Get-ChildItem as I think -Recurse in Remove-Item has some issues. You can even use Where-Object to further filter before passing to Remove-Item

$source = testfolder
Get-ChildItem -Path $source -Filter test_*_file -Recurse |
    Where-Object {$_.Fullname -notlike "$source\sub\*"} |
    Remove-Item -Force
BenH
  • 9,766
  • 1
  • 22
  • 35
  • Looks like this was still removing test_*_file from "$source/sub/*" – Mike Mar 27 '17 at 13:13
  • @mike Verify that you slashes are facing the correct direction. If it's Windows they should be backslashes. Because the issue will be the matching in the `Where-Object` filter. I used the `/` to match your path, but I have edited the answer since you had issues. – BenH Mar 27 '17 at 17:22
2

If the files to delete:

  • are all located directly in $source

  • and no other files / directories must be deleted:

Remove-Item -Path $source/test_*_file -Force

No need for -Recurse (as @Bill_Stewart notes).

Note: For conceptual clarity I've appended the wildcard pattern (test_*_file) directly to the $source path.
Using a wildcard expression separately with -Filter is generally faster (probably won't matter here), but it has its quirks and pitfalls.

Community
  • 1
  • 1
mklement0
  • 382,024
  • 64
  • 607
  • 775