Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to read and write a value to a json file $true or $false. If the script opened the first time

PowerShell Script

$TestPath = '.\test.json'
[bool]$TP = Test-Path -Path $TestPath -PathType Leaf
IF ($TP)
{
    $Content = Get-Content '.\test.json' | ConvertFrom-Json 
    $FirstOpen = @($Data.Config.First)
    if ($FirstOpen -eq '$true')
    {
        Write-Warning "Show disclaimer !"
        $FirstOpen.$Data.Config.First = '$False'                               # error line
        $Content | ConvertTo-Json | Set-Content '.\test.json' -Encoding utf-8  # error line
    }
    ELSE
    {
        Write-Host "This file has already been opened for the first time !"
    }
}
ELSE
{
    Write-Host "The config file not exist.🛑"
    Start-Sleep -s 5
    exit
}
pause

when I want to change the true value to false the whole file gets erased.
here the json file : Test.json

{"Config": {
 "first" : "$True"

}}

thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t know if I have $Content or $FirstOpen to change $True to $False.

I try to change some value, but not working.

$FirstOpen.$Data.Config.First = '$False'                               # error line
$Content | ConvertTo-Json | Set-Content '.\test.json' -Encoding utf-8  # error line

>Solution :

Your error is because you’re referencing a variable that doesn’t exist ($Data), it should be $Content instead.

$FirstOpen = @($Data.Config.First)

If you want to make it work, your code should be:

$TestPath = '.\test.json'
if (Test-Path -Path $TestPath -PathType Leaf) {
    $Content = Get-Content '.\test.json' | ConvertFrom-Json
    if ($Content.Config.First) {
        Write-Warning 'Show disclaimer !'
        $Content.Config.First = $false # no quotes otherwise it is interpreted as string
        $Content | ConvertTo-Json | Set-Content '.\test.json' -Encoding utf-8
    }
    else {
        Write-Host 'This file has already been opened for the first time !'
    }
}
else {
    Write-Host 'The config file not exist.🛑'
    Start-Sleep -s 5
    return
}

Your Json should look like:

{
  "Config": {
    "first": true // or false, no quotes otherwise it is interpreted as string
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading