Powershell to updatea value in a .config file

Laura Griffiths 1 Reputation point
2022-02-18T15:36:50.02+00:00

I'm rubbish at powershell and need to write a script to update the following:

filename : ReadandWrite.exe.config

Section:

<appSettings>
<add key="S_H" value="qhgQHyoZmG4xLdRVgIx4b+MPBaonXWGbZKK7jJQeXk8="/>
<add key="S_U" value="SQZHftF2qaGTAPv6Jl7PXVH1rVJMPlQKR53jnQNM1j0="/>
<add key="S_P" value="/V+jVFleFBvXyLJ7U2xZ0kZR7/hTJbB2MkbF1VCRQns="/>
<add key="ScreenMaskWordVersionSwitch" value="16.0.7000.0"/>
<add key="CheckItUnderlineAdjustmentWordVersionSwitch" value="16.0.12827.0"/>
<add key ="Login" value="1"/>
<add key ="BlockLaunchOnStartup" value="0"/>
<add key ="BlockSupportExtensionInChrome" value="0"/>
<add key ="BlockAutoUpdates" value="0"/>
</appSettings>

I want to change the value for key BlockSupportExtensionInChrome from 0 to 1 with a powershell script.

Thanks

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,514 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Andreas Baumgarten 108.2K Reputation points MVP
    2022-02-18T16:34:43.907+00:00

    Hi @Laura Griffiths ,

    maybe this works for you:

    ((Get-Content -Path ".\ReadandWrite.exe.config" -Raw) -replace '"BlockSupportExtensionInChrome" value="0"', '"BlockSupportExtensionInChrome" value="1"') |  
    Set-Content -Path ".\ReadandWrite.exe.config"  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

  2. Richard Lee 1 Reputation point
    2022-02-18T16:55:38.887+00:00

    Hi @Laura Griffiths ,

    I found this solution posted in StackOverflow (https://stackoverflow.com/questions/53386446/find-the-key-and-replace-its-respective-value-in-config-xml-files-using-powershe). Credit goes to the original author.

    This is bit more lengthy. See if this works for you which I adapted to your post.

    Sample Code

    $infile = “./ReadandWrite.exe.config”
    $outfile = “./ReadandWrite.exe.config.new”

    $xmlDoc = New-Object xml
    $xmlDoc.Load($infile)

    $nodes = $xmlDoc.SelectNodes(‘//appSettings/add[@Key =“BlockSupportExtensionInChrome”]’)

    foreach($node in $nodes) {
    $node.value = $node.value.Replace(‘0’,’1’)
    }

    $xmlDoc.Save($outfile)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.