Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects with no '.Count' Property - use of @() (array subexpression operator) vs. [Array] cast

I am trying to perform some simple if statements, but all of the newer cmdlets that are based upon [Microsoft.Management.Infrastructure.CimInstance] don't seem to expose a .count method?

$Disks = Get-Disk
$Disks.Count

Doesn't return anything. I found that I can cast this as an [array], which makes it returns a .NET .count method as expected.

[Array]$Disks = Get-Disk
$Disks.Count

This works without directly casting it as an array for previous cmdlets:

(Get-Services).Count

What is the recommended way to get around this?

An example that doesn't work:

$PageDisk = Get-Disk | Where {($_.IsBoot -eq $False) -and ($_.IsSystem -eq $False)}
  If ($PageDisk.Count -lt 1) {Write-Host "No suitable drives."; Continue}
   Else If ($PageDisk.Count -gt 1) {Write-Host "Too many drives found, manually select it."}
   Else If ($PageDisk.Count -eq 1) { Do X }

Option A (Cast as Array):

[Array]$PageDisk = Get-Disk | Where {($_.IsBoot -eq $False) -and ($_.IsSystem -eq $False)}
  If ($PageDisk.Count -lt 1) {Write-Host "No suitable drives."; Continue}
   Else If ($PageDisk.Count -gt 1) {Write-Host "Too many drives found, manually select it."}
   Else If ($PageDisk.Count -eq 1) { Do X }

Option B (Use Array Indexes):

 $PageDisk = Get-Disk | Where {($_.IsBoot -eq $False) -and ($_.IsSystem -eq $False)}
  If ($PageDisk[0] -eq $Null) {Write-Host "No suitable drives."; Continue}
   Else If ($PageDisk[1] -ne $Null) {Write-Host "Too many drives found, manually select it."}
   Else If (($PageDisk[0] -ne $Null) -and (PageDisk[1] -eq $Null)) { Do X }

Option C (Array) -Thanks to @PetSerAl :

$PageDisk = @(Get-Disk | Where {($_.IsBoot -eq $False) -and ($_.IsSystem -eq $False)})
  If ($PageDisk.Count -lt 1) {Write-Host "No suitable drives."; Continue}
   Else If ($PageDisk.Count -gt 1) {Write-Host "Too many drives found, manually select it."}
   Else If ($PageDisk.Count -eq 1) { Do X }

What is the reason for CIM based cmdlets not exposing the .Count method? What is the recommended way to handle this? Option B seems convoluted to me, and hard to read. Option A works, but shouldn't powershell cast this as an array for me? Am I going about this in entirely the wrong way?

like image 885
CobyCode Avatar asked Jul 13 '17 19:07

CobyCode


People also ask

How do you store values in an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.

How do you access array elements in PowerShell?

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar. length-1.

How do I add an item to an array in PowerShell?

To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator. For example, you have an existing array as given below. To add value “Hello” to the array, we will use += sign.

What is a collection in PowerShell?

Collections (Arrays) Collections are everywhere in PowerShell; they are the most prevalent of all its data structures. Cmdlets and pipes let you pass around objects, but keep in mind that they usually pass around objects (plural), not just an object (singular).


2 Answers

In PSv3+, with its unified handling of scalars and collections, any object - even $null - should have a .Count property (and, with the exception of $null, should support indexing with [0]).

Any occurrence of an object not supporting the above should be considered a bug; for instance:

  • Using this intrinsic (engine-supplied) .Count property unexpectedly fails when Set-StrictMode-Version 2 or higher is in effect, which is a long-standing bug reported in GitHub issue #2798, still present as of PowerShell 7.2 (whereas a type-native .Count property, such as on an array, can safely be accessed).

  • ([pscustomobject] instances not playing by these rules was a known bug, fixed in 2017).

Since I don't know if said bug is related to the [Microsoft.Management.Infrastructure.CimInstance#ROOT/Microsoft/Windows/Storage/MSFT_Disk] instances that Get-Disk outputs, and since Get-Disk - at least currently - is only available in Windows PowerShell, I encourage you to file a separate bug on uservoice.com.

Use of array-subexpression operator @(...) is only necessary:

  • as a workaround for the bug at hand / the Set-StrictMode -Version 2 bug.

  • in case a scalar object happens to have its own .Count property.


Generally,

  • If you do need to ensure that output from a command is captured as an array, @(...) is the PowerShell-idiomatic, more concise, and syntactically easier form compared to [Array] ... / [object[]] ...

  • By contrast, capturing output from an expression may call for [Array] ... / [object[]] ..., to avoid the potential inefficiency of enumerating expression output that already is an array and collecting it in a new array - see below for details.

  • With either type of output, as in your question, you may use [Array] as a type constraint on a variable (placed to the left of it), so as to ensure that later assignments too are treated as arrays; a contrived example: [Array] $a = 1 stores 1 wrapped in a (single-element) [object[]] array, and a later $a = 2 assignment implicitly does that for 2.

Additionally, @(...) and [Array] ... are typically, but not always equivalent, as PetSerAl's helpful examples in a comment on the question demonstrate; to adapt one of his examples:

@($null) returns a single-item array whose one and only element is $null, whereas [Array] $null has no effect (stays $null).

This behavior of @() is consistent with its purpose (see below): since $null is not an array, @() wraps it in one (resulting in a [System.Object[]] instance with $null as the only element).

In PetSerAl's other examples, @()'s behavior with New-Object-created arrays and collections - may be surprising - see below.


The purpose of @(...) and how it works:

The purpose of @(), the array-subexpression operator, is, loosely speaking, to ensure that the result of an expression/command is treated as an array, even if it happens to be a scalar (single object).:

  • @(...) collects an enclosed command's output as-is / an enclosed expression's enumerated output in an - always new - [object[]] array, even if there's only a single output object.

    • As such, @() is merely a slight modification - for the single-object output case - of PowerShell's default behavior with respect to collecting command and expression output from its success output stream - see this answer for more information. In short, single-object output is by default collected as-is, whereas @() wraps it in an array (by contrast, multiple output objects always get collected in an array, in both cases, of necessity).Tip of the hat to Slawomir Brzezinski for helping to clarify.
  • @(...) is never needed for array literals (in v5.1+ it is optimized away) - use of ,, the array constructor operator by itself is generally sufficient, e.g., 'foo', 'bar' instead of @('foo', 'bar') - but you may prefer it for visual clarity; it is also useful in the following cases:

    • to create an empty array: @())

    • to create a single-element array - e.g. @('foo') - which is easier to read than the unary form of , that would otherwise be required - e.g. , 'foo'

    • for syntactic convenience: to spread what is conceptually an array literal across multiple lines without having to use , to separate the elements and without having to enclose commands in (...); e.g.:

      @(
        'one'
        Write-Output two
      )
      
  • Pitfalls:

    • @() is not an array constructor, but a "guarantor": therefore, @(@(1,2)) does not create a nested array:

      • @(@(1, 2)) is effectively the same as @(1, 2) (and just 1, 2). In fact, each additional @() is an expensive no-op, because it simply creates a copy of the array output by the previous one.
      • Use the unary form of , the array constructor operator, to construct nested arrays:
        , (1, 2)
    • $null is considered a single object by @(), and therefore results in a single-element array with element $null:

      • @($null).Count is 1
    • Command calls that output a single array as a whole result in a nested array:

      • @(Write-Output -NoEnumerate 1, 2).Count is 1
    • In an expression, wrapping a collection of any type in @() enumerates it and invariably collects the elements in a (new) [object[]] array:

      • @([System.Collections.ArrayList] (1, 2)).GetType().Name returns 'Object[]'

Read on for more detailed information, if needed.


Details:

@() behaves as follows: Tip of the hat to PetSerAl for his extensive help.

  • In PSv5.1+ (Windows PowerShell 5.1 and PowerShell [Core] 6+), using an expression that directly constructs an array using ,, the array constructor operator, optimizes @() away:

    • E.g., @(1, 2) is the same as just 1, 2, and @(, 1) is the same as just , 1.

    • In the case of an array constructed with just , - which yields a System.Object[] array - this optimization is helpful, because it saves the unnecessary step of first unrolling that array and then repackaging it (see below).
      Presumably, this optimization was prompted by the widespread and previously inefficient practice of using @( ..., ..., ...) to construct arrays, stemming from the mistaken belief that @() is needed to construct an array.

    • However, in Windows PowerShell v5.1 only, the optimization is unexpectedly also applied when constructing an array with a specific type using a cast, such as [int[]] (the behavior has been corrected in PowerShell [Core] 6+ and older Windows PowerShell versions are not affected); e.g.,
      @([int[]] (1, 2)).GetType().Name yields Int32[]. This is the only situation in which @() returns something other than System.Object[], and assuming that it always does can lead to unexpected errors and side effects; e.g.:
      @([int[]] (1, 2))[-1] = 'foo' breaks.
      $a = [int[]] (1, 2); $b = @([int[]] $a) unexpectedly doesn't create a new array - see GitHub issue #4280.

  • Otherwise: If the (first) statement inside @(...) is an expression that happens to be an enumerable,[1] it is enumerated, i.e. its elements are sent one by one to the success output stream; a command's (typically one-by-one streaming) output is collected as-is; in either case the resulting count of objects determines the behavior:

    • If the result is a single item / contains no items, the result is wrapped in a single-element / empty array of type [System.Object[]].

      • E.g., @('foo').GetType().Name yields Object[] and @('foo').Count yields 1 (though, as stated, in PSv3+, you can use 'foo'.Count directly).
        @( & { } ).Count yields 0 (executing an empty script block outputs a "null collection" ([System.Management.Automation.Internal.AutomationNull]::Value)

      • Caveat: @() around a New-Object call that creates an array / collection outputs that array/collection wrapped in a single-element outer array.

        • @(New-Object System.Collections.ArrayList).Count yields 1 - the empty array list is wrapped in a single-element System.Object[] instance.

        • The reason is that New-Object outputs the list as a single object (that just so happens to be an enumerable itself), array/collection), causing @() to wrap it in a single-item array.

        • What may be confusing is that this does not happen when you use an expression to construct an array / a collection, because the expression's output is enumerated (an operation sometimes also called unwrapping or unrolling):

          • @([system.collections.arraylist]::new()).Count yields 0; the expression outputs an empty collection that is enumerated, and since there's noting to enumerate, @() creates an empty System.Object[] array.
            Note that, in PSv3+, simply using an extra set of parentheses ((...)) with New-Object - which converts the New-Object command to an expression - would yield the same result:
            @((New-Object System.Collections.ArrayList)).Count yields 0 too.
    • If the result comprises multiple items, these items are returned as a regular PowerShell array ([System.Object[]]); e.g.:

      • With a command:

        • $arr = @(Get-ChildItem *.txt) collects the one-by-one streaming output from Get-ChildItem in a System.Object[] array
      • With an expression:

        • $arr = [int[]] (1, 2); @($arr) enumerates [int[]] array $arr and then repackages the elements as a System.Object[] array.

        • Note the inefficiency and potential loss of type fidelity of this process: the original array is enumerated and collected in a new array that is always of type System.Object[]; the efficient alternative is to cast to [array] (which also works with commands): [array] $result = ...


[1] For a summary of which types PowerShell considers enumerable - which both excludes select types that do implement IEnumerable and includes one that doesn't - see the bottom section of this answer.

like image 116
mklement0 Avatar answered Sep 29 '22 10:09

mklement0


@mklement0 has a great answer, but one thing to add: if your script (or the script calling yours) has Set-StrictMode, the automatic .Count and .Length properties stop working:

$ Set-StrictMode -off
$ (42).Length
1
$ Set-StrictMode -Version Latest
$ (42).Length
ParentContainsErrorRecordException: The property 'Length' cannot be found on this object. Verify that the property exists.

To be safe, you can wrap any unknown variable in an array @(...) before checking the length:

$ $result = Get-Something
$ @($result).Length
1
like image 33
Carl Walsh Avatar answered Sep 29 '22 08:09

Carl Walsh