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