读取Word文档时,ForEach-Object中操作ArrayList无输出问题排查
问题原因与解决方案
你的脚本里ArrayList其实已经正确添加了元素,看不到输出是因为Word段落的文本默认带有末尾的段落标记(\r回车符),这些不可见字符会导致排序后的输出显示异常,甚至看起来像是没有内容。另外还有一个小问题:你没有关闭Word的COM进程,会导致后台残留Word.exe。
修复后的脚本
Set-StrictMode -Version Latest Clear-Host # set input file $filename = 'C:\Users\drschank\Desktop\Acoustic Solo Set - Copy.docx' # create word object $word = New-Object -ComObject Word.Application # load word object as read-only $doc = $word.Documents.Open($filename, $false, $true) # create array to hold songs $songArrayList = New-Object System.Collections.ArrayList; # loop through word paragraphs $doc.Paragraphs | ForEach-Object { # 先移除段落末尾的回车符(Word段落文本默认带的标记) $paraText = $_.Range.Text.TrimEnd("`r") # 遇到分隔线时退出循环 if($paraText -like "---*") { break } # 跳过目录行和空段落,拆分歌手与歌曲名 if($paraText -notlike "Table of Contents*" -and $paraText -ne '') { $fullsong = $paraText -split "`t" $songsplit = $fullsong[0] -split " – " # 确保拆分出有效内容再添加,符合严格模式要求 if($songsplit.Count -eq 2) { [void]$songArrayList.Add($songsplit[1].ToString() + "`t" + $songsplit[0].ToString()) } # $songsplit[1] # $songsplit[0] } } $doc.Close($false) # 退出Word进程,避免后台残留 $word.Quit() # 释放COM对象 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null $songArrayList | Sort-Object
关键修复点
- 清理段落标记:用
TrimEnd("r")`去除Word段落文本末尾的回车符,避免不可见字符干扰输出和排序。 - 过滤无效段落:添加
-and $paraText -ne ''跳过空段落,避免无效拆分操作。 - 拆分有效性校验:增加
if($songsplit.Count -eq 2)确保拆分出歌手和歌曲名后再添加元素,符合严格模式的要求。 - 释放Word资源:添加
$word.Quit()和COM对象释放代码,避免后台残留Word进程。
内容的提问来源于stack exchange,提问作者drschank
相关产品推荐
相关产品推荐

