1

A fairly basic script - searches Ou in AD and exports computers - I want to store each computer into an array so I can loop through later and run some commands against the computers. Although not having much luck with the array itself - am I completely off the track here?

$computers = @()
$i = 0
$ou = [ADSI]"LDAP://OU=Domain Controllers,DC=test,DC=local"
foreach ($child in $ou.psbase.Children) {
    if ($child.ObjectCategory -like '*computer*') { 
        Write-Host $child.Name 
        $computers[$i] = $child.name
        }
    $i += 1
}

2 Answers 2

3

You're indexing into an empty array with $computer[$i]. If you don't know how big the array should be but you know it won't be huge, change to this:

$computers += $child.Name

If you know the size then allocate the array that size like so:

$computers = new-object string[] $arraySize

Then you can index into the array up to size - 1.

If you don't know the size and think it will be large, use a list instead e.g.:

$computers = new-object system.collections.arraylist
[void]$computers.Add($child.Name)
0

Use a pipeline, filter the objects with Where-Object (alias ?), and output the names in a ForEach-Object loop (alias %). The result is either an array of names or $null (when the LDAP query did not return any computer objects).

$ou = [ADSI]"LDAP://OU=Domain Controllers,DC=test,DC=local"
$computers = $ou.PSBase.Children |
             Where-Object { $_.ObjectCategory -like '*computer*' } |
             ForEach-Object { $_.Name }

If you want the result to be an empty array when no computer objects are found, wrap the command pipeline in @():

$computers = @($ou.PSBase.Children | ...)

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.