Home > front end >  powershell Find and replace text in a config file
powershell Find and replace text in a config file

Time:09-21

I have a config file with text within which i would like to replace.

The text in the config file looks like the following

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <applicationSettings>
      <setting name="ExtendTimeMins" serializeAs="String">
        <value>5</value>
      </setting>
      <setting name="DisableHotkeySupport" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="ServerPingInterval" serializeAs="String">
        <value>00:00:10</value>
      </setting>
      <setting name="DirectorySweepRate" serializeAs="String">
        <value>00:10:00</value>
      </setting>
      <setting name="StopSignalExitDelaySecs" serializeAs="String">
        <value>0</value>
      </setting>
  </applicationSettings>
</configuration>

I want to change the False value of DisableHotkeySupport to True, but not change the StopSignalExitDelaySecs value.

Does anyone have any advice how to do this.

CodePudding user response:

Thanks for showing the entire config XML

To change the <Value>False</Value> into <Value>True</Value> for just the setting with name="DisableHotkeySupport" do not try to use text replacements, but instead:

$file = 'X:\TheConfigFile.config'  # full path to your config file goes here
# load the file in a new XmlDocument object
$xml = [System.XML.XMLDocument]::new()
$xml.Load($file)
($xml.configuration.applicationSettings.setting | Where-Object { $_.name -eq 'DisableHotkeySupport' }).Value = 'True'
# save the updated file
$xml.Save($file)

CodePudding user response:

The same answer although using a somewhat different syntax...

[xml]($config = @'
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <applicationSettings>
      <setting name="ExtendTimeMins" serializeAs="String">
        <value>5</value>
      </setting>
      <setting name="DisableHotkeySupport" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="ServerPingInterval" serializeAs="String">
        <value>00:00:10</value>
      </setting>
      <setting name="DirectorySweepRate" serializeAs="String">
        <value>00:10:00</value>
      </setting>
      <setting name="StopSignalExitDelaySecs" serializeAs="String">
        <value>0</value>
      </setting>
  </applicationSettings>
</configuration>
'@)

$setting = $config.configuration.applicationSettings.setting | 
where name -eq 'DisableHotkeySupport'

$setting.Value = 'True'

$config.Save('mydata.xml')
  • Related