In PS 5.1 I wrote this little func to ensure that the result of Processor will always be an array but for some strange reason it does not work. Do you know why?
function ConvertTo-Array($result) {
[bool]$isArray = ($result.getType() | Select-Object basetype).toString() -eq "System.Array"
if ($isArray -eq $false) {
return @($result)
}
return $result
}
$table = @{
"Processor" = ConvertTo-Array(Get-wmiobject Win32_Processor | Select-Object -Property Name, Number*);
}
$machinedata = @{
"Machine Info" = $table;
}
write-output (ConvertTo-Json $machinedata -Depth 3)
If I do this instead it works
...
"Processor" = @(Get-wmiobject Win32_Processor | Select-Object -Property Name, Number*);
...
return @($result), useWrite-Output $result -NoEnumerate. You are fighting PowerShell's want to unroll array outputs.@()'s entire purpose is to ensure that an expression evaluates to an array, I would definitely stick with it rather than reinvent the wheel :)return. While you can prevent this enumeration from within the function withWrite-Output -NoEnumerate <value>or, preferably,, <value>, using@(...)on the caller's side is the more PowerShell-idiomatic solution - see this answer.@()without the method then I may end up with a ([[]]) nested array which I don't want either. I'll probably have to solve this at the other side with a custom deserializer.