在PowerShell 2.0中编辑JSON数据

问题描述 投票:0回答:1

我有一个脚本应该在json首选项数据中写入,以更改不同扩展名的自动打开。

我从here得到的第一部分,但是这个脚本使用ConvertFrom-JsonConvertTo-Json,它只在Powershell> = 3.0中得到支持。

然后我找到了一个模仿这个Cmdlet here的函数。现在我的问题是它根本不工作,我不知道为什么,因为我没有任何错误或其他东西。

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

我认为接下来的两个功能是它无法正常工作的原因。

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 
}

将不胜感激任何建议或帮助。

  • 我的问题不是this post的重复,因为我使用了这篇文章的功能,但我的代码不相关
json powershell powershell-v2.0
1个回答
0
投票

PowerShell版本2不允许直接从对象列表中扩展属性,就像您一样:

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

对于PowerShell版本2,您应该使用Select-Object -ExpandProperty cmdlet /参数:

($prefs | gm | Select -ExpandProperty Name) -contains "download"
© www.soinside.com 2019 - 2024. All rights reserved.