如何使用PowerShell删除XML的一部分?

时间:2016-10-11 21:09:47

标签: xml powershell

以下脚本正在执行的操作是捕获计算机上的CPU核心数。如果脚本之前已经运行过,它会删除可能因失败尝试而遗留的部分脚本,然后将其写回。

它写入了httpruntime,Processmodel以及maxworker线程,maxworkerthreads,maxiothreads,minworkerthreads,miniotheads,然后是minfreethreads,minlocalrequestfreethreeads,然后它将minfreetheads和本地requestfreethreads中的90和80乘以CPU核心数。

然后我希望它删除如果存在的恍惚然后它写入结构,添加连接管理,并添加地址以及maxconnection字符串,添加数字200,然后乘以CPU核心数量的200倍。

以下是代码

$numberOfCores = Get-WmiObject -class win32_processor | Measure-Object numberOfCores -Sum | Select-Object -ExpandProperty sum
$path = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config"
[xml]$machineConfig = Get-Content $path
$node = $machineConfig.SelectNodes("/configuration/system.web") 
$node.RemoveChild(($node.SelectSingleNode("httpRuntime"))) | Out-Null
$node.RemoveChild(($node.SelectSingleNode("processModel"))) | Out-Null
$processModelxml = $machineConfig.CreateElement("processModel")
$processModelxml.setAttribute("maxWorkerThreads",370)
$processModelxml.setAttribute("maxWorkerThreads",370)
$processModelxml.setAttribute("maxIoThreads",370)
$processModelxml.setAttribute("minWorkerThreads",50)
$processModelxml.setAttribute("minIoThreads",50)
$node.AppendChild($processModelxml) | Out-Null
$httpRuntimexml = $machineConfig.CreateElement("httpRuntime")
$httpRuntimexml.setAttribute("minFreeThreads",90 * $numberOfCores)
$httpRuntimexml.setAttribute("minLocalRequestFreeThreads",80 * $numberOfCores)
$node.AppendChild($httpRuntimexml) | Out-Null
$node = $systemnetxml.SelectSingleNode('//system.net')
$node.ParentNode.RemoveChild($node)
[xml]$systemnetxml = @"
  <system.net>
    <connectionManagement>
      <add address = "*" maxconnection = "$(200 * $numberOfCores)" />
    </connectionManagement>
  </system.net>
"@
$machineConfig.configuration.AppendChild($machineConfig.ImportNode($systemnetxml."system.net",$true)) | Out-Null
$machineConfig.Save("C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config")

这是涉及的machine.config的更新部分,并注意额外的system.nets

machine.config中

    <configuration>
      <system.web>
    <processModel maxWorkerThreads="370" maxIoThreads="370" minWorkerThreads="50" minIoThreads="50" />
    <httpRuntime minFreeThreads="180" minLocalRequestFreeThreads="160" />
  </system.web>
  <system.net>
    <connectionManagement>
      <add address="*" maxconnection="400" />
    </connectionManagement>
  </system.net>
  <system.net>
    <connectionManagement>
      <add address="*" maxconnection="400" />
    </connectionManagement>
  </system.net>
</configuration>

更改回只有你的代码,仍然会重现相同的部分,但不会出现放置&#34; connectionManagement:connectionManagement&#34;正如我之前提到的那样

1 个答案:

答案 0 :(得分:2)

规范方法是从父节点中删除节点:

[xml]$machineConfig = Get-Content $path
...
$node = $machineConfig.SelectSingleNode('//system.net')
$node.ParentNode.RemoveChild($node)