如何使用 powershell 脚本更改 Nlog.config 变量值

How to change Nlog.config variable value using powershell script

我正在尝试使用 PowerShell 为不同的环境更改名称 ="one" 的变量值 ="1" 天蓝色的脚本 devops 。我无法为 nlog.config 做到这一点并且得到 'D:\pss\nlog.config' 在文件节点 中没有 'one' 键不知道我是什么做错了吗? Nlog.config 文件:

<?xml version="1.0" encoding="utf-8"?>
<nlog
xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
autoReload="true" 
throwExceptions="false" 
internalLogLevel="Trace"
internalLogFile="d:\log.txt">
<variable name="one" value="1" />
<variable name="two" value="2" />

<targets async="true">
  <target name="default"
  xsi:type="File"
  fileName="${Directory}\NLog_${date:format=yyyyMMddHH}.log"
  layout="${longdate}|${uppercase:${level}}|${message}}|${exception:format=ToString,StackTrace}" keepFileOpen="false" />
</targets>
<rules>
  <logger name="*" writeTo="default" minlevel="Debug" />
  <logger name="*" writeTo="eventlog" minlevel="Error" />
</rules>
</nlog>

Powershell 脚本:

   $configPath = 'D:\pss\nlog.config'
   $key = "one"
   $value = "11"
       $XPath = "nlog/variable[@name='$key']"
       $Attribute = "value"
       $xml = [xml](Get-Content -Path $configPath)
       $xmlNode = $xml.SelectSingleNode($XPath)
       if ($xmlNode) 
       {
           $xmlNode.SetAttribute($Attribute, $value)
           $xml.Save($configPath)   
          Write-Host ("Config customHeaders has been Update "+$configPath+" on key: "+$key+" with the value " + $value)
       }
       else
       {
          Write-Host ("Config '"+$configPath+"' does not have the '"+ $key + "' key inside the file node.")
       } 

任何帮助或建议都将非常有用。谢谢

$configPath = 'D:\pss\nlog.config'
$key = "one"
$value = "11"
$xml = [xml](Get-Content -Path $configPath)

$xml.nlog.variable.Where{ $_.Name -eq $key }.Foreach{ $_.value = $value }

$xml.Save($configPath)