You are currently converting to JSON inside of the function, which is propably intended as debug output only. Due to PowerShell's implicit output behaviour, both of these statement actually add to the output of the function:
$data | ConvertTo-Json # implict output
return $data # like $data; return
After calling the function Get-Data
, the variable $test
will be an array:
$test[ 0 ]
= $data
converted to JSON string
$test[ 1 ]
= the unconverted $data
(hashtable)
After converting $test
to JSON, you can see that array, indicated by the JSON beginning with [
.
What you actually want is to prevent the JSON from inside the function to "leak" into the success stream of the function. E. g.:
Function Get-Data()
{
$data = @{}
$data.Add("Critical",1)
$data.Add("Warning",2)
$data.Add("Information",3)
$data.Add("Summary","test")
Write-Host "function"
$data | ConvertTo-Json | Out-Host # Output to host instead of implict success stream
$data # Implicit output, no "return" statement needed
}
Now we are outputting the JSON to the host stream, which will just be printed to the console, but will be separate from the actual function output.
While the host stream is OK for prototyping or code that will be logged in any case, a better choice might be the verbose stream, which will not be written to by default:
Function Get-Data()
{
[Cmdletbinding()]
Param()
$data = @{}
$data.Add("Critical",1)
$data.Add("Warning",2)
$data.Add("Information",3)
$data.Add("Summary","test")
Write-Verbose "function"
$data | ConvertTo-Json | Write-Verbose # Write to verbose stream
$data # Implicit output, no "return" statement needed
}
Now users of your function would have to explicitly switch on verbose logging to actually see the JSON output of the function:
Get-Data -Verbose
To enable this common parameter, I had to convert the function into an advanced function by inserting [Cmdletbinding()]
and Param()
at the top.
Further information about PowerShell's implict output behaviour. It is aimed at a different question, but much of it is relevant to the current question as well.