简体   繁体   中英

Edit JSON data in PowerShell 2.0

I got a script which should write inside the json preferences data to change the auto opening from different extensions.

The first part I got from here but this script uses ConvertFrom-Json and ConvertTo-Json which is only supported in Powershell >= 3.0.

Then I found a function that imitates this Cmdlet here . Now my problem is that it is not working at all and I don't know why, because I don't get any Errors or something.

$neededFileExt = "2er"
$path = $env:LOCALAPPDATA + "\Google\Chrome\User Data\Default\Preferences"
$prefContent = Get-Content $path -Encoding utf8

I think the next two functions are the reason why it doesn't work properly.

function ConvertTo-Json([object] $prefcontent) {
    add-type -assembly system.web.extensions
    $prefs = new-object system.web.script.serialization.javascriptSerializer
    return $prefs.Serialize($prefcontent)
}

function ConvertFrom-Json([object] $prefcontent) { 
    add-type -assembly system.web.extensions
    $prefs = new-object system.web.script.serialization.javascriptSerializer
    return , $prefs.DeserializeObject($prefcontent)
}

$prefs = ConvertFrom-Json $prefContent
if (($prefs | gm).name -contains "download") {
    if (($prefs.download | gm).name -contains "extensions_to_open") {
        if ($prefs.download.extensions_to_open) { #if it has value, grab the contents
            [string[]]$existingFileExt = 
            $prefs.download.extensions_to_open.tostring().split(":")
        }
        else {
            [string[]]$existingFileExt = $null
        }
    }
    else {
        #if extensions_to_open doesn't exist, create it
        $prefs.download | Add-Member -MemberType NoteProperty -Name extensions_to_open -Value ""
        [string[]]$existingFileExt = $null
    }
    foreach ($ext in $neededFileExt) {
        if ($existingFileExt -notcontains $ext) { #only add the necessary extension if it isn't already there
            [string[]]$existingFileExt += $ext
        }
    }
    $prefs.download.extensions_to_open = $existingFileExt -join ":" 
    ConvertTo-Json $prefs -Compress -depth 100 | Out-File $path -Encoding utf8 
}

Would appreciate any suggestions or help.

  • my question is not a duplicate of this post because i used the function from this post but my code is not relatable

PowerShell version 2 doesn't allow to expand properties directly from an object list like you do:

($prefs | gm).name -contains "download"

For PowerShell version 2 you should use the Select-Object -ExpandProperty cmdlet/parameter:

($prefs | gm | Select -ExpandProperty Name) -contains "download"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM