Powershell - 将AD中的所有计算机存储到阵列中

时间:2013-06-07 00:29:09

标签: powershell active-directory adsi

所以目前我有一些代码可以通过Powershell中的ADSI锁定到特定的OU,循环并将它们存储到Array中。反过来,我遍历这个并运行一个测试连接。我有我的理由......

无论如何,是否有可能(仅使用内置的cmdlet,即没有Quest的东西)来递归整个AD并将所有计算机对象添加到数组中?

$myArrayOfComputers = @()

$orgUnit = [ADSI]"LDAP://OU=foo,DC=foo,dc=co,dc=uk"

ForEach($child in $orgUnit.psbase.Children) {
    if ($child.ObjectCategory -like '*computer*') { $myArrayOfComputers += $child.Name }
}

ForEach($i in $myArrayOfComputers) {
    Test-Connection $i
}

2 个答案:

答案 0 :(得分:1)

在PowerShell V2.0中,您可以尝试:

Import-module ActiveDirectory
$computers = Get-ADComputer *

在PowerShell V1.0中,您可以尝试:

# dom.fr is the DNS root name of the domain
$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://dom.fr:389/dc=dom,dc=fr","administrator@dom.fr","admin")

# Look for computers
$Rech = new-object System.DirectoryServices.DirectorySearcher($dn)
$Rech.filter = "((objectClass=computer))"
$Rech.SearchScope = "subtree"
$Rech.PropertiesToLoad.Add("sAMAccountName");  
$Rech.PropertiesToLoad.Add("lastLogon");  
$Rech.PropertiesToLoad.Add("distinguishedname");

$computers = $Rech.findall()

答案 1 :(得分:1)

在V2上使用.net:

Add-Type -AssemblyName System.DirectoryServices.AccountManagement | out-null
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = new-object  'System.DirectoryServices.AccountManagement.PrincipalContext'($ct, "foo.co.uk", "OU=foo,DC=foo,dc=co,dc=uk");
$cpp = New-Object 'System.DirectoryServices.AccountManagement.Computerprincipal'($pc)
$ps = new-object  'System.DirectoryServices.AccountManagement.PrincipalSearcher'
$ps.QueryFilter = $cpp
$MyListArray = $ps.FindAll() | select -expa name