Powershell 替换 applicationHost.config 导致格式不正确的 xml 错误

Powershell replace on applicationHost.config causing not well-formed xml errors

tl;博士;为什么下面的脚本(replace.ps1)会导致 xml IIS 中格式不正确的错误,但手动执行却不会

我运行在安装了 IIS 10 的 windows 服务器 2016 上 运行 下面的脚本(替换。ps1),但它会导致所有 powershell 和 gui 配置更改为消息 "configuartion file is not well-formed xml" 出错,如果我手动进行相同的更改,则不会出错。

如果我打开 applicationHost.config 的原始版本并将其与 winmerge 中的更改版本进行比较,我可以看到唯一更改的行是额外的部分标记,所以除非我遗漏了某些内容,否则这似乎不太可能该文件实际上格式不正确。

顺便说一句,我认为这可能是由于 Out-File 在文件底部添加了一个换行符,所以我尝试添加 -NoNewline 参数,但这导致它删除了所有现有的换行符但仍然保留$newSection 中的换行符,但在查看原始配置后,它看起来无论如何都以换行符结尾,所以它似乎并不重要。

替换。ps1

$newSection=@('<sectionGroup name="system.webServer">
            <section name="heliconZoo" overrideModeDefault="Allow" allowDefinition="Everywhere" />');
$schemaDir="$env:windir\system32\inetsrv\config\schema\";
$appHostFile="$env:windir\system32\inetsrv\config\applicationHost.config";
Copy-Item "./assets/heliconZoo_schema.xml" "$($schemaDir)";
Copy-Item "$appHostFile" "$appHostFile.bak";
(Get-Content $appHostFile ).Replace('<sectionGroup name="system.webServer">',$newSection) | Out-File $appHostFile # -NoNewline

我还认为这可能是由于使用了错误的过程 mode/archtecture(有关详细信息,请参阅 here)但我很确定我正在 运行 编写脚本在 64 位 powershell 中,如果我 运行 Start-Job { ls c:\windows\system32\inetsrv\config\ } -RunAs32 | Wait-Job | Receive-Job 我看不到任何 applicationHost.config 文件,所以 运行 在 32 位进程中使用它无论如何都会失败。

Out-File 的默认编码是 encoding of the system's current ANSI code page

使用Out-File -Encoding ascii强制文件以ascii编码写入

或者,转换为 [System.Xml.XmlDocument](或 [xml]),作为 XML 处理并使用 XML writer 写出,其主要特征是匹配实际使用的编码的编码声明。

请参阅 Iain Brighton 的这部 tutorial 短片。

剧情简介:

$fileName = "employees.xml";
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName);

$newXmlEmployee = $xmlDoc.employees.AppendChild($xmlDoc.CreateElement("employee"));
# …

$xmlDoc.Save($fileName);