1 hour ago · Tech · hide · 0 comments

The use of JSON can be powerful in your PowerShell functions and processes. JSON is naturally a machine style language that is easy to use for storing settings and other useful elements throughout a scripts steps. Recently, I have a process that relies on a JSON configuration file and while the file existed, the contents were not valid and thus silently errors. I do have plenty of error handling but not in this one area. I was only checking if the file existed, but not the contents of the file. Let’s fix that. Starting with PowerShell 5.1+ $path = '.\data.json' try { $json = Get-Content -LiteralPath $path -Raw -ErrorAction Stop if ([string]::IsNullOrWhiteSpace($json)) { throw 'The file is empty.' } $null = ConvertFrom-Json -InputObject $json -ErrorAction Stop 'Valid JSON syntax' } catch { "Invalid JSON or file read error: $($_.Exception.Message)" } When using PowerShell 5.1, I need to read the file and then try to use the ConvertFrom-Json command to test if we can read the file…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.