unitechie
unitechie

Reputation: 27

powershell Find and replace text in a config file

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.

Upvotes: 0

Views: 1421

Answers (2)

Dennis
Dennis

Reputation: 1782

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

Upvotes: 0

Theo
Theo

Reputation: 61068

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)

Upvotes: 3

Related Questions