【发布时间】:2021-10-18 18:36:51
【问题描述】:
我正在尝试使用元组列表以特定顺序写入 txt 文件。该列表按 item1(数字)排序,并有一个关联的字符串作为 item2。
我尝试使用 for each 循环运行列表并将关联的字符串插入到 txt 文件中。我希望 for each 循环使用 item1 遍历列表,但是 for each 循环使用 item2 进行迭代并按字母顺序插入。
我如何确保它以正确的顺序插入笔记?
$sortedList 包含:
Item1 Item2 Length
----- ----- ------
0 noteC 2
1 noteD 2
2 noteF 2
3 noteA 2
4 noteB 2
5 note5 2
D:\ 驱动器包含:
noteA.pdf
noteB.pdf
noteC.pdf
noteD.pdf
noteF.pdf
note5.pdf
我正在做的简化版:
$notePath = "D:\"
$list = Get-ChildItem -Path $notePath -Recurse | `
Where-Object { $_.PSIsContainer -eq $false -and $_.Extension -ne '.srt' }
$sortedList = New-Object System.Collections.ArrayList
ForEach($n in $list){
if($n.name.Contains('C')) {
$sortedList.Add([Tuple]::Create(0,$n.Name))
} elseif($n.name.Contains('D')) {
$sortedList.Add([Tuple]::Create(1,$n.Name))
} elseif($n.name.Contains('F')) {
$sortedList.Add([Tuple]::Create(2,$n.Name))
} elseif($n.name.Contains('A')) {
$sortedList.Add([Tuple]::Create(3,$n.Name))
} elseif($n.name.Contains('B')) {
$sortedList.Add([Tuple]::Create(4,$n.Name))
} elseif($n.name.Contains('5')) {
$sortedList.Add([Tuple]::Create(5,$n.Name))
}
}
New-Item $notePath’\noteList.txt'
ForEach($n in $sortedList){
$var = "Note:"+ $n.Item2 | Out-File -Append $notePath’\noteList.txt'
}
txt 文件中的结果:
Note: noteA
Note: noteB
Note: noteC
Note: noteD
Note: noteF
Note: note5
我想要的结果在 txt 中:
Note: noteC
Note: noteD
Note: noteF
Note: noteA
Note: noteB
Note: note5
【问题讨论】:
-
运行代码时出现 2 个错误:
Missing expression after ','.用于[Tuple]::Create( ... ))行,Missing 'in' after variable in foreach loop.用于ForEach($n.Item1 in $sortedList){ ... }。您能否确认您的代码发布的确实在您的机器上运行? -
您是否有必须使用元组的特定要求?也许尝试使用哈希表
@{0 = 'noteC' }或字典[System.Collections.Generic.Dictionary[[int],[string]]]::new()代替? -
ForEach($n.Item1 in $sortedList)... 这在语法上是无效的 Powershell 代码。
标签: powershell foreach tuples