如何使用 *.exe 的 return 值用 PowerShell 替换不完全 XML 的文件内部的 XML?

How to replace XML inside of a file that is not entirely XML with PowerShell using return value of *.exe?

我有一个特殊格式的配置文本文件,其中有 1 行以 wcfconfig,Text,<?xml version... 开头,我正在尝试使用 PowerShell 将整个 XML 块替换为从可执行。文本文件(例如:C:\Temp\MyText.txt)如下所示:

Special Export File
Format: 1
Configuration: MyConfig
    startupcmd,Text,
    extracmdline,Text,
    wsdlport,Text,9500
    useserverprinters,Int,1
    aosencryption,Text,1
    dbserver,Text,Dev-SERVER
    wcfconfig,Text,<?xml version="1.0" encoding="utf-8"?><configuration>...
    hint,Text,

当使用 server/port 和 returns 一个 XML 字符串调用时,我有一个可执行文件。

C:\MyFile.exe Dev-SERVER 9500

其中 Dev-Server 来自文本文件中的 dbserver9500 来自文本文件中的 wsdlport

它 returns 一个 XML 字符串,其格式与上面的 wcfconfig 完全相同,我只想完全替换第 1 行:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    </configSections>
    <client>
    </client>
</configuration>

因为我没有你的环境,所以我不得不伪造一些东西。 C:\MyFile.exe Dev-SERVER 9500 的输出由此处的字符串 $return

表示
$return = @"
<?xml version="1.1" encoding="utf-8"?>
<configuration>
    <configSections>
    </configSections>
    <client>
    </client>
</configuration>
"@

(Get-Content "C:\Temp\MyText.txt") -replace '^(\s*?wcfconfig,Text,).*',"`$($replace -replace "`r`n")"

获取文件 "C:\Temp\MyText.txt" 的内容并使用 -replace 找到您要更新的行。用 <?xml 之前的所有文本替换它,然后附加文件数据并删除新行。

一些元素> <之间会有白色space。如果这是一个问题,另一个 -replace 应该可以解决这个问题。 -replace "\>\s+?\<","><"