-1

This is the dummy.json file

{
    "key1":"value1",
    "key2":"value2"
}

I'm reading the contents of this file to a variable and outputting them

C:> $obj = Get-Content .\dummy.json
C:> $obj
{
        "key1":"value1",
        "key2":"value2"
}
C:> Write-Host "$obj"
{       "key1":"value1",        "key2":"value2" }

I know that Get-Content doesn't preserve the line breaks and joins it by " ". Powershell keep text formatting when reading in a file

But why is there an inconsistency in the above 2 outputs ? I guess Write-Host is doing its job correctly. Or am I wrong ?

Community
  • 1
  • 1
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37

1 Answers1

3

It's not Get-Content that joins the lines (its output is an array of strings), but you putting the variable in double quotes ("$obj"). You can avoid that by joining the lines yourself:

Write-Host ($obj -join "`n")
Write-Host ($obj | Out-String)
Write-Host $($OFS="`n"; "$obj")

Another option would be to read the file directly as a single string, e.g. like this (requires PowerShell v3 or newer):

$obj = Get-Content .\dummy.json -Raw

or like this:

$obj = [IO.File]::ReadAllText('.\dummy.json')
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328