Search code examples
windowspowershellfile-get-contents

Replacing a string in file containing special characters


I am completely new to PowerShell, so please bear with me. I am having issues trying to replace some a string inside the Preference file, but the file contains a bunch of special characters. How would I be able to replace this ' [{"id":"*" ' with this ' [{"id":"Save as PDF" '. Also, the * in the first argument is regex.

Here is the code:

$filepath='C:\Users\%USERNAME%\AppData\Local\Google\Chrome\User Data\Profile 8\'

cd $filepath

(Get-Content Preferences) -replace '[{\"id\":\"*"', '[{\"id\":\"Save as PDF\"' | Out-File -encoding ASCII Preferences

Solution

  • Simple example using convertfrom-json:

    cat file.json
    {
        "id":  "Save as PDF"
    }
    
    $a = get-content file.json | convertfrom-json
    
    $a
    
    id
    --
    Save as JPG
    
    
    $a.id = 'Save as PDF'
    $a | convertto-json
    {
        "id":  "Save as PDF"
    }
    
    $a | convertto-json | set-content file.json
    cat file.json
    {
        "id":  "Save as PDF"
    }