Jim Lobo
Jim Lobo

Reputation: 491

How to change Nlog.config variable value using powershell script

I am trying to change variable value ="1" for name ="one" for different environment using PowerShell script for azure devops .I am not able do it for nlog.config and getting 'D:\pss\nlog.config' does not have the 'one' key inside the file node Not sure what I am doing wrong ?. Nlog.config file :

<?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 Script :

   $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.")
       } 

Any help or advice would be great . Thanks

Upvotes: 0

Views: 533

Answers (1)

iRon
iRon

Reputation: 23788

$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)   

Upvotes: 0

Related Questions