为什么下面的脚本(replace.ps1)不会在IIS中导致格式良好的错误,而手动操作却不会
我在安装了IIS10的windows server 2016上运行下面的脚本(replace.ps1),但它会导致所有powershell和gui配置更改后出现错误,并显示消息“配置文件不是格式良好的xml",如果我手动执行相同的更改,则不会出错。
如果我打开applicationHost.config的原始版本,并将其与winmerge中更改的版本进行比较,我可以看到唯一更改的行是额外的部分标记,所以除非我遗漏了一些东西,否则文件实际上不太可能是格式不正确的。
顺便说一句,我认为这可能是因为Out-File在文件的底部添加了一个换行符,所以我尝试添加了-NoNewline参数,但这导致它去掉了所有现有的换行符,但仍然保留了$newSection中的换行符,但在查看了原始配置后,它看起来像是以换行符结尾,所以看起来也没什么关系。
replace.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我还认为这可能是由于使用了错误的进程模式/体系结构(有关详细信息,请参阅here ),但我非常确定我是在64位powershell中运行脚本,如果我运行Start-Job { ls c:\windows\system32\inetsrv\config\ } -RunAs32 | Wait-Job | Receive-Job,我看不到任何applicationHost.config文件,因此在32位进程中运行它无论如何都会失败。
发布于 2018-07-23 23:53:07
Out-File的默认编码是encoding of the system's current ANSI code page。
使用Out-File -Encoding ascii强制使用ascii编码写入文件
发布于 2018-07-24 17:27:02
或者,转换为[System.Xml.XmlDocument] (或[xml]),作为XML处理并使用XML编写器写出,它的主要功能是将编码声明与实际使用的编码进行匹配。
请看Iain Brighton的这篇简短的tutorial。
简介:
$fileName = "employees.xml";
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName);
$newXmlEmployee = $xmlDoc.employees.AppendChild($xmlDoc.CreateElement("employee"));
# …
$xmlDoc.Save($fileName);https://stackoverflow.com/questions/51476658
复制相似问题