Powershell -如果文件夹名称存在于文本文件中,则删除该文件夹

gxwragnw  于 2022-12-04  发布在  Shell
关注(0)|答案(2)|浏览(161)

我有一个包含文件夹名称列表文本文件。
我要从目录中删除名称出现在文本文件中的文件夹
这是我的尝试

#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千
这会给我文本文件和目录中的文件夹名称列表。现在我想删除列表中的文件夹
希望有人能帮忙
谢谢你

yeotifhr

yeotifhr1#

一个较短的方法是这样的:

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

请注意,您必须位于包含要删除的文件夹的文件夹中。

swvgeqrz

swvgeqrz2#

你可以用

#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  
    
}

相关问题