$file = "C:\Users\HHH\Desktop\ddd\Web.config"$xml = New-Object -TypeName xml$xml.Load($file)function XmlAdd{Param ($xml,$Pattern,$Content,$After = $null)$Content=$Content.Trim()$Content=[xml]$Content$pnode=Select-Xml -Xml $xml -XPath $Patternif ($After -ne $null) {$After = [xml]$After$Location = $pnode.Node.InnerXml.IndexOf($After.OuterXml)}if ($pnode -ne $null) {if (-not ($pnode.Node.InnerXml.Contains($Content.OuterXml))) {if ($After -eq $null -or $Location -eq -1) {$pnode.Node.InnerXml+=$Content.OuterXml}else {$InsertLocation = $Location+$After.OuterXml.Length$AddString = $pnode.Node.InnerXml.Substring(0,$InsertLocation)+$Content.OuterXml+$pnode.Node.InnerXml.Substring($InsertLocation)$pnode.Node.InnerXml=$addstring}}}}$xpath = '//appSettings/add[@key="CompanyCode"]'if (Select-Xml -Xml $xml -XPath $xpath){$item = Select-Xml -Xml $xml -XPath $xpath$item.Node.Value = "test"$xml.Save($file)}else {$Content='<add key="CompanyCode" value="nnono" />'$Pattern="/configuration/appSettings"XmlAdd $xml $Pattern $Content$xml.Save($file)}# 研究xml管理整理# 函数# outerxml 获取包含此节点及其所有子节点的标记# innerxml 获取或设置仅表示此节点的子节点的标记# substring 用于提取字符串中介于两个指定下标之间的字符# contains 用于判断字符串中是否包含指定的字符或字符串# Xpath常用语法总结## https://www.cnblogs.com/ruhai/p/10705719.html# 命令# Select-Xml# select-object# new-object
参考:https://blog.vichamp.com/2017/06/03/Mastering-Everyday-XML-Tasks-in-PowerShell/
https://www.cnblogs.com/Ulysse/p/14939143.html#/c/subject/p/14939143.html
