如何将 CSV 列表中的 select [n] 项分配给变量,然后删除这些项并使用 PowerShell 保存文件

How to select [n] Items from a CSV list to assign them to a variable and afterwards remove those items and save the file using PowerShell

我正在解析 CSV 文件以获取需要复制到其他位置的文件夹的名称。因为它们有数百个,所以我需要 select 前 10 个左右和 运行 复制例程,但为了避免再次复制它们,我将从列表中删除它们并保存文件。

我会 运行 在每天的计划任务中执行此操作,以避免必须等待文件夹完成复制。我在代码中使用 'Select' 和 'Skip' 选项时遇到问题(见下文),如果我删除这些行,文件夹将被复制(我正在使用空文件夹进行测试)但是如果我把它们放进去,然后当我在 PowerShell 中 运行 this 时什么也没有发生。

我查看了有关类似问题的其他问题,但没有找到任何可以回答此特定问题的内容select在 CSV 中编辑和跳过行。

$source_location = 'C:\Folders to Copy'
$folders_Needed = gci $source_location
Set-Location -Path $source_location
$Dest = 'C:\Transferred Folders'
$csv_name = 'C:\List of Folders.csv'
$csv_Import = Get-Content $csv_name


foreach($csv_n in $csv_Import | Select-Object -First 3){
    foreach ($folder_Tocopy in $folders_Needed){        
        if("$folder_Tocopy" -contains "$csv_n"){        
        Copy-Item -Path $folder_Tocopy -Destination $Dest -Recurse -Verbose        
        }
    }
    $csv_Import | Select-Object -Skip 3 | Out-File -FilePath $csv_name
}

它应该像您的示例一样与 skip/first 一起使用,但如果没有您的示例数据,我无法真正测试它。此外,在循环的每次迭代中将相同的输出写入 csv 文件似乎是错误的。我假设它不是一个 csv 文件,而实际上只是一个纯文本文件,一个文件夹列表?只是文件夹名称还是完整路径? (我假设第一个。)

无论如何,这是我建议的脚本更新(见评论):

$source_location = 'C:\Folders to Copy'
$folders_Needed = Get-ChildItem $source_location
$Dest = 'C:\Transferred Folders'
$csv_name = 'C:\List of Folders.csv'
$csv_Import = @(Get-Content $csv_name)
# optional limit
# set this to $csv_Import.Count if you want to copy all folders
$limit = 10

# loop over the csv entries
for ($i = 0; $i -lt $csv_Import.Count -and $i -lt $limit; $i++) {
    # current line in the csv file
    $csv_n = $csv_Import[$i]
    # copy the folder(s) which name matches the csv entry
    $folders_Needed | where {$_.Name -eq $csv_n} | Copy-Item -Destination $Dest -Recurse -Verbose
    # update the csv file (skip all processed entries)
    $csv_Import | Select-Object -Skip ($i + 1) | Out-File -FilePath $csv_name
}