CSV列名含空格导致PowerShell XML替换失败,如何修复?
问题:CSV列名含空格导致PowerShell属性访问失败
场景说明
需要通过CSV列表替换XML中的字符串,当前CSV内容如下:
First;Secound One; Third Name;Beschreibung Neu;Func1 Number;handout her, func2
使用的PowerShell代码中,执行字符串替换时出现异常,问题出在以下代码行:
$NEU_NW.innerxml = $NEU_NW.innerxml -replace ("$spalte" -replace "'"),($Zeile."$spalte" -replace "'")
原因是CSV第二列列名Secound One包含空格,使用$Zeile."$spalte"的点语法访问属性时出现解析问题。
完整原代码
#Splatennamen auslesen $CSVSpalten = $CSVData | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name' # xml Objekt erstellen $xml = New-Object XML # xml laden $xml.Load($OPN_in) # Abfrage des ersten 'SW.Blocks.CompileUnit' Knotens $Bsp_NW = $xml.SelectSingleNode("//SW.Blocks.CompileUnit") # abbrechen wenn kein Knoten gefunden wurde. if (!$Bsp_NW){ throw "Error, 'SW.Blocks.CompileUnit' Node not found!" exit 1 } $z=0 foreach($Zeile in $CSV_reseve) { # erstelle eine Kopie des Knotens im Speicher $NEU_NW = $Bsp_NW.Clone() #Texte Ersetzen foreach($spalte in $CSVSpalten) { #$NEU_NW.innerxml write-Host "ALt: $spalte NEU: $Zeile.$spalte " $NEU_NW.innerxml = $NEU_NW.innerxml -replace ("$spalte" -replace "'"),($Zeile."$spalte" -replace "'") #ID's verändern $z+=1 $NEU_NW.innerxml = $NEU_NW.innerxml.Replace(' ID="',' ID="'+($z*10).ToString()) #> } # id anpassen $NEU_NW.Id = (100*$z).ToString() # hänge den kopierten Knoten im selben Parent wie vom Original wieder ins XML ein $Bsp_NW.ParentNode.InsertAfter($NEU_NW,$Bsp_NW) }
解决方案
核心修正
将属性访问的点语法改为索引器语法,无论列名是否包含空格、特殊字符,索引器语法都能稳定访问对应列的值:
# 修正后的替换行 $NEU_NW.innerxml = $NEU_NW.innerxml -replace ("$spalte" -replace "'"), ($Zeile[$spalte] -replace "'")
额外优化建议
- 确保CSV导入时指定正确分隔符
导入CSV必须明确指定分隔符为;,否则列名解析会混乱:
$CSVData = Import-Csv -Path "你的CSV文件路径" -Delimiter ';'
- 清理列名的前后空格
CSV第一行第三列带有前导空格Third,可在导入时清理列名的前后空白,避免后续匹配失败:
$CSVData = Import-Csv -Path "你的CSV文件路径" -Delimiter ';' | ForEach-Object { $cleanedObj = [PSCustomObject]@{} foreach ($propName in $_.PSObject.Properties.Name) { $cleanPropName = $propName.Trim() $cleanedObj | Add-Member -MemberType NoteProperty -Name $cleanPropName -Value $_.$propName } $cleanedObj } # 重新获取清理后的列名 $CSVSpalten = $CSVData | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
内容的提问来源于stack exchange,提问作者TheRob87
相关产品推荐
相关产品推荐

