Powershell 将AD计算机名称存储在数组中

Powershell 将AD计算机名称存储在数组中,powershell,Powershell,一个相当基本的脚本-在AD中搜索Ou并导出计算机-我想将每台计算机存储到一个数组中,以便稍后循环并对计算机运行一些命令。虽然阵列本身运气不太好,但我是否完全偏离了轨道 $computers = @() $i = 0 $ou = [ADSI]"LDAP://OU=Domain Controllers,DC=test,DC=local" foreach ($child in $ou.psbase.Children) { if ($child.ObjectCategory -like '*co

一个相当基本的脚本-在AD中搜索Ou并导出计算机-我想将每台计算机存储到一个数组中,以便稍后循环并对计算机运行一些命令。虽然阵列本身运气不太好,但我是否完全偏离了轨道

$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
}

您正在使用
$computer[$i]
索引到一个空数组中。如果您不知道阵列应该有多大,但知道它不会很大,请更改为:

$computers += $child.Name
如果知道大小,则按如下方式分配大小的数组:

$computers = new-object string[] $arraySize
然后您可以索引到最大为
size-1
的数组中

如果您不知道尺寸,并且认为尺寸会很大,请使用列表代替,例如:

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

使用管道,使用
Where Object
(别名
)过滤对象,并在每个对象的
循环中输出名称(别名
%
)。结果是一个名称数组或
$null
(当LDAP查询未返回任何计算机对象时)

如果希望在找不到计算机对象时结果为空数组,请将命令管道包装到
@()

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