I have only started working with XML files and PowerShell. I feel that while there are many ways to accomplish the same thing that I might be doing the following inefficiently.
This is all based on the following SO post which I have an answer to:
$numberOfCores = Get-WmiObject -class win32_processor numberOfCores | Select-Object -ExpandProperty numberOfCores
$path = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machineTest.config"
[xml]$machineConfig = Get-Content $path
# Remove the elements we are going to be replacing
$node = $machineConfig.SelectNodes("/configuration/system.web")
[void]($node.RemoveChild(($node.SelectSingleNode("processModel"))))
[void]($node.RemoveChild(($node.SelectSingleNode("httpHandlers"))))
# Create the element processModel and set attributes
$processModelxml = $machineConfig.CreateElement("processModel")
$processModelxml.setAttribute("maxWorkerThreads",370)
$processModelxml.setAttribute("maxWorkerThreads",370)
$processModelxml.setAttribute("maxIoThreads",370)
$processModelxml.setAttribute("minWorkerThreads",50)
$processModelxml.setAttribute("minIoThreads",50)
[void]($node.AppendChild($processModelxml))
# Create the element httpRuntime and set attributes. Adjust values based on number of cores
$httpRuntimexml = $machineConfig.CreateElement("httpRuntime")
$httpRuntimexml.setAttribute("minFreeThreads",90 * $numberOfCores)
$httpRuntimexml.setAttribute("minLocalRequestFreeThreads",80 * $numberOfCores)
[void]($node.AppendChild($httpRuntimexml))
# Build the <system.net> section
[xml]$systemnetxml = @"
<system.net>
<connectionManagement>
<add address = "*" maxconnection = "$(200 * $numberOfCores)" />
</connectionManagement>
</system.net>
"@
# Import into config
$machineConfig.configuration.AppendChild($machineConfig.ImportNode($systemnetxml."system.net",$true)) | Out-Null
# Save changes
$machineConfig.Save("c:\temp\testing.xml")
# Change back to $path to write back to original file.
If you wanted to test this you need to change $path
to that of a local machine.config in a .Net build folder. Also the last step saves the file in an alternate location for testing. Changing it to $machineConfig.Save($path)
would be a production approach.
In my defense this code was gear towards a new user so there are a few lines that are created to be more verbose on purpose. I am mostly interested in the XML focus of this code but will welcome any criticism towards the rest (in case I am being complacent.) Was designed using PowerShell v4.