Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Folder cleanup with PowerShell

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.

like image 201
Sam Harwell Avatar asked Apr 24 '10 14:04

Sam Harwell


People also ask

How do I force delete a folder in PowerShell?

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.

Does Remove-item Remove folders?

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.

Does mkdir work in PowerShell?

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.


2 Answers

# 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 }
like image 126
Roman Kuzmin Avatar answered Sep 20 '22 05:09

Roman Kuzmin


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
like image 21
Damian Powell Avatar answered Sep 23 '22 05:09

Damian Powell