0

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*);
...
Ares
  • 1,356
  • 1
  • 9
  • 22
  • 2
    Instead of `return @($result)`, use `Write-Output $result -NoEnumerate`. You are fighting PowerShell's want to unroll array outputs. – AdminOfThings Sep 25 '20 at 21:34
  • 2
    `@()`'s entire purpose is to ensure that an expression evaluates to an array, I would definitely stick with it rather than reinvent the wheel :) – Mathias R. Jessen Sep 25 '20 at 22:19
  • 1
    In short: output from functions is also subject to _enumeration_ of collections - whether or not you use `return`. While you can prevent this enumeration from within the function with `Write-Output -NoEnumerate ` or, preferably, `, `, using `@(...)` on the _caller_'s side is the more PowerShell-idiomatic solution - see [this answer](https://stackoverflow.com/a/62489498/45375). – mklement0 Sep 25 '20 at 23:16
  • My problem is that if I do ```@()``` 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. – Ares Sep 27 '20 at 17:02

0 Answers0