0

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?

Tomasz Maj
  • 1,541
  • 15
  • 15
  • 3
    `Write-Host @databaseDev` -> `Write-Host $databaseDev` :) – Mathias R. Jessen Sep 21 '22 at 12:25
  • 2
    As an aside: [`Write-Host` is typically the wrong tool to use](http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/), unless the intent is to write _to the display only_, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it _by itself_; e.g, `$value`, instead of `Write-Host $value` (or use `Write-Output $value`); see [this answer](https://stackoverflow.com/a/60534138/45375). To explicitly print only to the display _but with rich formatting_, use `Out-Host`. – mklement0 Sep 21 '22 at 14:15

1 Answers1

4

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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206