views:

89

answers:

4

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.

A: 

One possibility

function ql {$args}

ql Folder1 Folder2 Folder3 File3 |
    ForEach {
        if(Test-Path $_) {
            Remove-Item $_
        }
    }
Doug Finke
A: 
# if you do not mind to have a few ignored errors
Remove-Item -Recurse -Force -ErrorAction 0 @(
    'Directory1'
    'Directory2'
    'File1'
)
Roman Kuzmin
I prefer to not have ignored errors since they are pretty easily avoided here. :)
280Z28
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.
Roman Kuzmin
+1  A: 
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
Damian Powell
It turns out `Remove-Item -r` works for both folders and files.
280Z28
@280Z28 Cool! I didn't know that.
Damian Powell
+1  A: 
# 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 }
Roman Kuzmin
You can pipe straight into `Remove-Item` by dropping the `$_`.
280Z28
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.
Roman Kuzmin