0

'scuse my ignorance... I use @($var).Count so I can get a count even if $var contains 1 "item". When my search returns nothing why does my array contain one item? i.e.

  PS C:\Windows\system32> $Groups = $null

    Import-Module -Name "activedirectory"

    $search = "aaaarggg"

    $searchPat = `"*"` + $search + `"*"`

    $Groups = Get-ADGroup -Filter {(name -like $searchPat)}

    if ($Groups -eq $null) {
        "No matches"
        @($Groups).Count
    }
    else {
        "Matches"
        @($Groups).Count
    }



 No matches

    1
1
  • 2
    Because you are creating an array with a single element - null. Commented Dec 5, 2013 at 9:08

2 Answers 2

2

As Lee said you create array which contains one item and the item is null. It may seem illogical, but it is done this way to give you consistent results when decrementing or incrementing the amount of items in the array. Look at the example below. If the @($null).count returned 0 you would jump from 2 to 0.

@($null,$null,$null).Count #output 3
@($null,$null).Count #output 2
@($null).Count #output 1
@().Count #output 0

Ingoring $null values inside the @() operator would also render such situations impossible to handle:

$("a",$null,"c").count #output 3
$("a","b","c").count #output 3
Sign up to request clarification or add additional context in comments.

Comments

0

From the Powershell doc You create an empty array as $a = @()

To count the elements you can simply do $a.Count

$x = @()
$x.Count
0

As for processing the results of Get-ADGroup, that depends on what it returns. I think you'll find that simply doing if ($Groups.Count -eq 0 ) { # process } will work for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.