Folder cleanup with PowerShell
powershell, powershell-2.0
Solution
# 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 }
Problem
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.