Powershell ConvertTo-Json adding many spaces between characters

370 Views Asked by At

I've got issue on following script. I am using latest PowerShell 7

Code:

$databasesArray = @('Zero','One','Two','Three')

$databasesDev = $databasesArray | ConvertTo-Json -Compress 
Write-Host @databasesDev

Result:

[ " Z e r o " , " O n e " , " T w o " , " T h r e e " ]

Expected:

["Zero", "One", "Two", "Three"]

How to fix it? What's wrong with the code?

1

There are 1 best solutions below

0
Mathias R. Jessen On

ConvertTo-Json isn't adding any space.

The splat operator @ will take any dictionary or array and "explode" the contained values against the target command.

In this case, the array being splatted simply happens to be a string, meaning you're effectively feeding Write-Host each character in the string as a separate positional argument.

You can observe the same behavior with any string:

$Text = "Hello Tomasz!"
Write-Host @Text

Which will print out:

H e l l o   T o m a s z !

So to fix your issue, simple stop using @:

# this will give print the result you want
Write-Host $databaseDev