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
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
}
}