Powershell脚本,用于将属性从文件的中间移动到末尾



我有一个配置文件,如下所示:

<Configuration>
<Property> 1 />
<Property> 2 />
<ConfigurationRef 1 />
<Property 3 />
</Configuration>

我需要的是始终在文件末尾但在</Configuration>结束之前有<ConfigurationRef 1 />。我现在实现的是将<ConfigurationRef 1 /></Configuration>移动到txt,然后附加到文件:

Get-Content C:file.xconf | Select-String -Pattern '<ConfigurationRef 1 />' | Out-File "C:outfile.txt"
Get-Content C:file.xconf | Select-String -Pattern '</Configuration>' | Out-File "C:outfile.txt" -Append

然后:

Get-Content C:outfile.txt | Out-file C:file.xconf -Append

有没有一种方法可以做到这一点,而不导出到新的txt文件?因为导入后,它在文件中看起来不太好

我建议走另一条路,通过遍历原始文件中的所有行来简单地构建一个新的字符串数组:

$NewContent = [System.Collections.Generic.List[string]]::new()
foreach ($Line in $Content) {
switch ($Line) {
"<ConfigurationRef 1 />" {}
"</Configuration>" {
# Reached end of Configuration block, adding hardcoded
# values
$NewContent.Add("<ConfigurationRef 1 />")
$NewContent.Add("</Configuration>")
}
default { $NewContent.Add($Line) }
}
}

在这种情况下,您将把所有行添加到新的[string[]]数组中,但有两个例外:

  • <ConfigurationRef 1 />将被忽略
  • </Configuration>将按正确顺序添加两行