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*);
...
4
  • 2
    Instead of return @($result), use Write-Output $result -NoEnumerate. You are fighting PowerShell's want to unroll array outputs. Commented Sep 25, 2020 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 :) Commented Sep 25, 2020 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 <value> or, preferably, , <value>, using @(...) on the caller's side is the more PowerShell-idiomatic solution - see this answer. Commented Sep 25, 2020 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. Commented Sep 27, 2020 at 17:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.