将Format-Table移至循环外时触发空管道错误,求解决方案
解决PowerShell「An empty pipe element is not allowed」错误
你遇到的错误根源是:foreach是PowerShell语句,并非支持管道输出的命令,直接在foreach闭合大括号后接| Format-Table,会导致管道中没有有效输出内容,从而触发报错。以下是两种可行的修改方案:
方案一:收集循环结果后统一格式化
把foreach循环生成的所有PSCustomObject收集到变量中,再统一通过管道传递给Format-Table:
$CSV = Import-Csv "C:\Users\Megan\Documents\EC_Export\AllDocs.csv" # 将循环输出收集到变量 $results = foreach($LINE in $CSV) { $docPath = $LINE.filepath # 保留原编码友好的XML加载方式 $xmlFile = [xml]::new(); $xmlFile.Load((Convert-Path -LiteralPath $docPath)) $ht = [ordered] @{} $xmlFile.files.file.ChildNodes | Where-Object Name -match 'title|lcmSubject|lcmPrincipal|lcmClosingDate|lcmAclList' | ForEach-Object { $value = $_.'#text' #.Trim() -replace '\r?\n', ',' $ht[$_.Name] = $value } [PSCustomObject]$ht } # 对收集到的结果执行格式化输出 $results | Format-Table -Wrap
方案二:改用支持管道的ForEach-Object命令
把foreach语句替换为ForEach-Object命令(注意变量引用从$LINE改为$_),这样可以直接将循环输出通过管道传递给Format-Table:
$CSV = Import-Csv "C:\Users\Megan\Documents\EC_Export\AllDocs.csv" $CSV | ForEach-Object { $docPath = $_.filepath $xmlFile = [xml]::new(); $xmlFile.Load((Convert-Path -LiteralPath $docPath)) $ht = [ordered] @{} $xmlFile.files.file.ChildNodes | Where-Object Name -match 'title|lcmSubject|lcmPrincipal|lcmClosingDate|lcmAclList' | ForEach-Object { $value = $_.'#text' #.Trim() -replace '\r?\n', ',' $ht[$_.Name] = $value } [PSCustomObject]$ht } | Format-Table -Wrap
两种方案都能解决错误:方案一适合处理大量数据时灵活控制结果;方案二代码更紧凑,契合PowerShell管道式编程的习惯。
内容的提问来源于stack exchange,提问作者baconfeltoon
相关产品推荐
相关产品推荐

