Powershell: Remove a Folder from every Home Directory


image

I had to remove a folder from every home directory. So I thought this is a nice thing to do with Powershell.

So I created the Remove-Folder function to do this for me :-).

The function will go through the following steps:

The begin part will browse to all the folders within the E:\users and export the full path to a CSV file. The path will look like this: E:\users\username\test\foldername.

In the process part it will remove all the folders which are saved in the CSV file.

Warning: The folders will be removed without a warning. So be sure you want to do this!!

function Remove-Folder{
    param($path,$folder)

    Begin{
        Get-Childitem $path -Recurse `
        | Where-Object { $_.Name -eq $folder } `
        | Select FullName `
        | Export-Csv -NoTypeInformation "$env:temp\remove.csv"
    }
    
    Process{
        $import = Import-Csv "$env:temp\remove.csv"
        foreach($folder in $import){
            Remove-Item $folder.FullName -Recurse -Force
        }
    Remove-Item "$env:temp\remove.csv"
    }
}

You can use the function with the following command:

Remove-Folder E:\users foldername

Via the following one-liner, you can validate the removal job:

Get-Childitem E:\users -Recurse `
| Where-Object { $_.Name -eq "foldername" } `
| Select FullName `
| Export-Csv -NoTypeInformation "$env:temp\remove.csv" 

Open the remove.csv file to verify the changes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s