Antoine Delplanque
Antoine Delplanque

Reputation: 81

Powershell - delete folder if name exists in text file

I have a text file with a list of folder name.

I want to delete the folders from my directory for which the name appears in the text file

Here is my try

#I get the contents of the text file

$textfile = Get-Content "C:\Users\s611284\Desktop\Dossiers.txt"

#I get the name of the folders from the directory

$Foldersname = Get-ChildItem -Path $Directory | ForEach-Object { 
        $_.BaseName 
      } 

#I get the names present in the text file and in the folders of the directory

Compare-Object -IncludeEqual $textfile $Foldersname | Where-Object SideIndicator -eq '==' 

93 / 5 000

This gives me the list of folder names present in the text file and in the directory. Now I would like to delete folders present in this list

Hope someone can help

Thank you

Upvotes: 1

Views: 793

Answers (2)

Said Torres
Said Torres

Reputation: 653

A shorter way is this:

$filenames = Get-Content -Path ".\deleteFolders.txt"
foreach ($file in $filenames) {
    Remove-Item -Force -Path "./$file"
}

Note that you have to be inside the folder that contains the folders that you want to delete.

Upvotes: 1

dollo
dollo

Reputation: 36

You could use

#I get the contents of the text file

$textfile = Get-Content "C:\Users\s611284\Desktop\Dossiers.txt"

#I get the name of the folders from the directory

$Foldersname = Get-ChildItem -Path $Directory | ForEach-Object { 
        $_.BaseName 
      } 

#I get the names present in the text file and in the folders of the directory

Compare-Object -IncludeEqual $textfile $Foldersname | Where-Object SideIndicator -eq '=='|ForEach-Object {

    $item=$_.inputobject
    remove-item $Directory\$item -Recurse  
    
}

Upvotes: 2

Related Questions