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.
Open PowerShell by pressing the Start button and typing PowerShell. Press Enter. Type Remove-Item –path c:\testfolder –recurse and hit Enter. Please replace c:\testfolder with the full path to the folder you wish to delete.
The Remove-Item cmdlet deletes one or more items. Because it is supported by many providers, it can delete many different types of items, including files, folders, registry keys, variables, aliases, and functions.
Commands such MKDIR or MD don't actually exist in PowerShell: Instead, they're aliases to their PowerShell brethren that do the same thing. In PowerShell, MD is an alias to MKDIR. Also, MKDIR is an alias to the New-Item cmdlet.
# 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 }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With