首页 > 解决方案 > 通过包含在具有 foreach 循环和 Powershell 中的 Remove-Item 的数组中的名称删除文件

问题描述

使用 Powershell,我正在尝试删除目录中的一些文件。我有一个数组,其中包含我要保留的文件的名称(它们在 $NameOfFilesToKeep 数组中)。所有其他文件都必须删除。这是我正在使用的代码:

####### YOU HAVE TO MODIFY THIS SETTINGS #######


$GenericIDandNameOfProject = "[19123]PARIS EST"  #If the name of your files is something like this [19123]PARIS EST_XXX.XML , it should be equal to "[19123]PARIS EST"

$Entries = "10
8
9
16"   #Be careful, this " should be on the same line as the last number!


####### END OF THE SETTINGS YOU HAVE TO MODIFY #######



$IDofInterestingElements = $Entries.split("`n")


for ($i=0; $i -lt $IDofInterestingElements.Length-1; $i++) {
    $IDofInterestingElements[$i] = $IDofInterestingElements[$i].Substring(0,$IDofInterestingElements[$i].Length-1)
}

Write-Output ("Soooo, you want " + $IDofInterestingElements.Length + " files at the end")

$NameOfFilesToKeep = @()

foreach ($ID in $IDofInterestingElements) {
    $NameOfFilesToKeep += $GenericIDandNameOfProject + "_" + $ID + ".XML"
}


$CurrentDirectory = (Get-Location).path

foreach ($file in dir $CurrentDirectory) {
    if ($NameOfFilesToKeep.Contains($file.name)) {
        Write-Output (${file})
    }
    else {
        Remove-Item "${CurrentDirectory}\${file}"
    }
}

Start-Sleep 100

文件的名称是“[19123]PARIS EST_XXX.XML”,其中 XXX 是一个数字,例如 [19123]PARIS EST_10.XML

它根本行不通。我想我错过了 Remove-Item 部分的重要内容。我的代码可能有什么问题?

编辑

我添加了完整的代码以便更好地理解。

标签: powershell

解决方案


我想你想删除 $file.name。否则 $file 将字符串化到整个路径(这因 powershell 版本而异)。 请注意,IList.Contains()(带数组)区分大小写 https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.system-collections-ilist-contains?视图=网络框架-4.8

$nameoffilestokeep = echo file1.txt file2.txt

$CurrentDirectory = (Get-Location).path

foreach ($file in dir $CurrentDirectory) {
    if ($NameOfFilesToKeep.Contains($file.name)) {
        Write-Output (${file})
    }
    else {
        Remove-Item "${CurrentDirectory}/$($file.name)" -whatif
    }
}

实际上,您的版本在 ps5 for windows 中适用于我。但我们不知道 $nameoffilestokeep 长什么样。它应该是一个字符串数组。

编辑:新代码应该大部分都可以工作,除了 .substring() 你要从每个字符串的末尾切掉 1 个字符。文件名中的方括号会给你带来麻烦,因为它们是 powershell 中通配符的一部分。


推荐阅读