1. $file = "C:\Users\HHH\Desktop\ddd\Web.config"
    2. $xml = New-Object -TypeName xml
    3. $xml.Load($file)
    4. function XmlAdd
    5. {
    6. Param (
    7. $xml,
    8. $Pattern,
    9. $Content,
    10. $After = $null
    11. )
    12. $Content=$Content.Trim()
    13. $Content=[xml]$Content
    14. $pnode=Select-Xml -Xml $xml -XPath $Pattern
    15. if ($After -ne $null) {
    16. $After = [xml]$After
    17. $Location = $pnode.Node.InnerXml.IndexOf($After.OuterXml)
    18. }
    19. if ($pnode -ne $null) {
    20. if (-not ($pnode.Node.InnerXml.Contains($Content.OuterXml))) {
    21. if ($After -eq $null -or $Location -eq -1) {
    22. $pnode.Node.InnerXml+=$Content.OuterXml
    23. }else {
    24. $InsertLocation = $Location+$After.OuterXml.Length
    25. $AddString = $pnode.Node.InnerXml.Substring(0,$InsertLocation)+$Content.OuterXml+$pnode.Node.InnerXml.Substring($InsertLocation)
    26. $pnode.Node.InnerXml=$addstring
    27. }
    28. }
    29. }
    30. }
    31. $xpath = '//appSettings/add[@key="CompanyCode"]'
    32. if (Select-Xml -Xml $xml -XPath $xpath){
    33. $item = Select-Xml -Xml $xml -XPath $xpath
    34. $item.Node.Value = "test"
    35. $xml.Save($file)
    36. }
    37. else {
    38. $Content='<add key="CompanyCode" value="nnono" />'
    39. $Pattern="/configuration/appSettings"
    40. XmlAdd $xml $Pattern $Content
    41. $xml.Save($file)
    42. }
    43. # 研究xml管理整理
    44. # 函数
    45. # outerxml 获取包含此节点及其所有子节点的标记
    46. # innerxml 获取或设置仅表示此节点的子节点的标记
    47. # substring 用于提取字符串中介于两个指定下标之间的字符
    48. # contains 用于判断字符串中是否包含指定的字符或字符串
    49. # Xpath常用语法总结
    50. ## https://www.cnblogs.com/ruhai/p/10705719.html
    51. # 命令
    52. # Select-Xml
    53. # select-object
    54. # 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