tl;dr; why does the script below (replace.ps1) cause xml not well-formed errors in IIS but doing it manually doesn't
I'm running the script (replace.ps1) below on windows server 2016 with IIS 10 installed but it causes all powershell and gui config changes after it to error with the message "configuartion file is not well-formed xml", if i do the same change manually it doesn't error.
If i open the orginal version of applicationHost.config and compare it to the changed version in winmerge i can see the only line that has changed is the extra section tag so unless i'm missing something it seems unlikely that the file is actually not well formed.
As an aside i thought it might have been due to Out-File adding a newline at the bottom of the file so i tried adding the -NoNewline argument but then that caused it to strip out all existing newlines but still kept the newline in $newSection but after looking at the original config it looks like it ends with a newline anyway so it doesn't seem like it would matter anyway.
$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
I also thought it may have been due to using the wrong process mode/archtecture (see here for details) but i'm pretty sure i'm running the script in 64 bit powershell and if i run Start-Job { ls c:\windows\system32\inetsrv\config\ } -RunAs32 | Wait-Job | Receive-Job
i can't see any applicationHost.config file so running it in a 32 bit process would fail anyway.
The default encoding of Out-File
is the encoding of the system's current ANSI code page.
Use Out-File -Encoding ascii
to force the file to be written with ascii encoding