powershell - Powershell:每个的元组列表顺序错误?
问题描述
我正在尝试使用元组列表以特定顺序写入 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
解决方案
坚持 Tuple 主题,您只需要Sort-Object
在处理结果之前重新排序结果:
- 构建测试数据:
$unsortedList = New-Object System.Collections.ArrayList
$unsortedList.Add([Tuple]::Create(3, "noteA"))
$unsortedList.Add([Tuple]::Create(4, "noteB"))
$unsortedList.Add([Tuple]::Create(0, "noteC"))
$unsortedList.Add([Tuple]::Create(1, "noteD"))
$unsortedList.Add([Tuple]::Create(2, "noteF"))
$unsortedList.Add([Tuple]::Create(5, "note5"))
$unsortedList | format-table
#Item1 Item2 Length
#----- ----- ------
# 3 noteA 2
# 4 noteB 2
# 0 noteC 2
# 1 noteD 2
# 2 noteF 2
# 5 note5 2
- 对数据进行排序
$sortedList = $unsortedList | sort-object -Property "Item1";
$sortedList | format-table
#Item1 Item2 Length
#----- ----- ------
# 0 noteC 2
# 1 noteD 2
# 2 noteF 2
# 3 noteA 2
# 4 noteB 2
# 5 note5 2
推荐阅读
- java - Amazon s3 文件上传时公开
- android - ListView 自定义项在图形上不正确
- css - 如何更改垫选择占位符颜色?
- angular - 使用 Azure DevOps 在 Angular 7 中 JavaScript 堆内存不足
- python - 带有 Lambda 层的 Keras
- css - 在变暗函数中使用十六进制颜色作为字符串
- windows - Cmd 将一些文件复制两次到目标
- sql-server - 为什么第一次创建数据库时已经有一些用户?(SQL Server 2017,SSMS 17.9)
- javascript - 使用 Firebase 云消息发送通知
- javascript - 修复了使用“scrollOverflow:true”滚动通过 fullPage.js 部分的标题块