【发布时间】:2021-03-20 00:38:07
【问题描述】:
我有一个将 xml 转换为 csv 的代码, 但是有些 xml 是空的, 我想要的输出是只有这些文件中的标题。 为此,我想在第一行添加我的标题。
由于 xml 的格式,我必须替换每个文件的标题
要做的事情就在这里:
$header = Get-Content -Path $OutPath'\'$content'.csv'
Try {
$header[0] = $NomColonnes
$header | Set-Content -Path $OutPath'\'$content'.csv' -Encoding:UTF8 #remplace la premiere ligne
"Operation Finished"
}
Catch{
#Remove-Item –path $OutPath'\'$content'.csv' #si vide detrui le fichier (xml vide)
"xml vide"
Add-Content -Path $OutPath'\'$content'.csv' -Value $NomColonnes"‘n" -Encoding:UTF8 #header avec un csv vide
#$NomColonnes | Out-File $OutPath'\'$content'.csv' -Encoding utf8
}
“尝试”在至少有一行时有效,如果没有,它会给我和错误, 所以catch的作用只是将缺失的头文件(本例中为$nomcolonnes)添加到一个空文件中
但是,在文件中它看起来很正常。
稍后我需要删除某些文件的标题才能合并它们 我在这里做的:
$InPath = Read-Host -Prompt 'Enter a the path to the csv'
$NomColonnes = '"Context","Proprety_Name","Design Value","Translation Value","","","",""'
Get-ChildItem $InPath -Filter '*HTML.csv' | #seulement les html
Foreach-Object {
$content = $_.FullName
#Write-Host $content
$header = Get-Content -Path $content
#Write-Host $header[0] "1st line"
#Write-Host $NomColonnes "nomcol"
if ($header[0] -eq $NomColonnes) #if first line = header then do the operation, otherwise don`t
{
get-content $content |
select -Skip 1 |
set-content "$content-temp" #recree le fichier sans la premiere ligne
move "$content-temp" $content -Force
#Write-Host $content
}else{
$header[0]
$header[1]
$header[2]
"no header to remove"
}
它选择带有 html 标记的那些来删除它们的标题 它寻找 header[0] 并且大多数都可以工作 但是当它遇到以前的空文件之一时,它就像读取列一样。
输出:
$header[0]
$header[1]
$header[2]
是:
"
C
o
更进一步会拼出“内容,...”
我不知道为什么会这样,我认为主要的罪魁祸首是当我添加该行时。 但我已经尝试了我能想到的一切。
ps:行:
#Remove-Item –path $OutPath'\'$content'.csv'
用于删除空文件的另一个版本
【问题讨论】:
-
如果你的文件只包含一行,
Get-Content会将该输出读取为单个字符串,而不是包含一个字符串的数组。您可以使用$header = @(Get-Content -Path $content)来确保始终使用数组。 -
$header = @(Get-Content -Path $content) 给了我想要的标题,但之前的空文件仍然没有
t work. move "$content-temp" $content -Force it cant find $content-temp。我认为这可能与跳过1有关,它没有地方可以跳过
标签: xml string powershell replace