10

I'd like to clean up some directories after my script runs by deleting certain folders and files from the current directory if they exist. Originally, I structured the script like this:

if (Test-Path Folder1) {
  Remove-Item -r Folder1
}
if (Test-Path Folder2) {
  Remove-Item -r Folder2
}
if (Test-Path File1) {
  Remove-Item File1
}

Now that I have quite a few items listed in this section, I'd like to clean up the code. How can I do so?

Side note: The items are cleaned up before the script runs, since they are left over from the previous run in case I need to examine them.

4 Answers 4

11
# if you want to avoid errors on missed paths
# (because even ignored errors are added to $Error)
# (or you want to -ErrorAction Stop if an item is not removed)
@(
    'Directory1'
    'Directory2'
    'File1'
) |
Where-Object { Test-Path $_ } |
ForEach-Object { Remove-Item $_ -Recurse -Force -ErrorAction Stop }
3
  • 1
    You can pipe straight into Remove-Item by dropping the $_. Commented Apr 24, 2010 at 15:25
  • 1
    Good point (for binding input to the -Path parameter). In fact, I usually use -LiteralPath as much as possible (less error prone), so I proposed this version still keeping -LiteralPath in mind. Commented Apr 24, 2010 at 16:30
  • Great snippet, I've been struggling with "Error: directory is not empty" for longer than I'd like to admit. Commented Apr 12, 2014 at 22:48
1
Folder1, Folder2, File1, Folder3 |
    ?{ test-path $_ } |
        %{
            if ($_.PSIsContainer) {
                rm -rec $_ #  For directories, do the delete recursively
            } else {
                rm $_ #  for files, just delete the item
            }
        }

Or, you could do two separate blocks for each type.

Folder1, Folder2, File1, Folder3 |
    ?{ test-path $_ } |
        ?{ $_.PSIsContainer } |
            rm -rec

Folder1, Folder2, File1, Folder3 |
    ?{ test-path $_ } |
        ?{ -not ($_.PSIsContainer) } |
            rm
1
  • 1
    It turns out Remove-Item -r works for both folders and files. Commented Apr 24, 2010 at 15:19
0

One possibility

function ql {$args}

ql Folder1 Folder2 Folder3 File3 |
    ForEach {
        if(Test-Path $_) {
            Remove-Item $_
        }
    }
0
# if you do not mind to have a few ignored errors
Remove-Item -Recurse -Force -ErrorAction 0 @(
    'Directory1'
    'Directory2'
    'File1'
)
2
  • I prefer to not have ignored errors since they are pretty easily avoided here. :) Commented Apr 24, 2010 at 15:26
  • Agree, it is not suitable for your scenario because you should know the issues before the script continues. Still, this version will do in some other cases, for example cleanup after the script work. Commented Apr 24, 2010 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.