简体   繁体   中英

How can I read all Active Directory computers into an array in PowerShell?

When I do:

# Gets all domain-joined computer names and properties in one object
$strCategory = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("(objectCategory=$strCategory)")

$colProplist = "name"

foreach ($i in $colPropList) {
    $objSearcher.PropertiesToLoad.Add($i)
}

$Reader = $objSearcher.FindAll()

foreach ($Computer in $Reader) {
   Write-Host $Computer
}

$Computer comes out as System.DirectoryServices.SearchResult . How can I query Active Directory for all computers and store their string values into an array like this?

I need to keep the foreach syntax (ie foreach $Computer in $Reader ) because my code is such that $Reader can also accept a file of computers like so:

$Reader = Get-Content ((Resolve-Path $iL).Path)

In summary, I want something that works with both an input file OR by querying AD using the same looping syntax.

EDIT : My input file is a text file that separates computer names by a newline as in the following:

win7box1
win7box2
win10box3

I solved it. To get a string from System.DirectoryServices.DirectorySearcher , you could just do a loop as in my example, and do:

foreach ($Computer in $Reader) {
     $ComputerString = $Computer.Properties.Name
}
$Reader = Get-ADComputer -Filter * | Select-Object -ExpandProperty samAccountName

foreach ($Computer in $Reader) {
   #WMI processing
}

Should do the trick. No need for more.

You could use System.DirectoryServices.DirectorySearcher for performance reasons, though. Or use a real filter, not * .

I guess you took your code from here , if you have not tried anything else before, it is not the easiest choice PowerShell offers.

Edit:

You need the ActiveDirectory module loaded for Get-ADComputer to be available ( Import-Module ActiveDirectory ).

... and you need RSAT installed for the ActiveDirectory PowerShell module to be available.

Edit 2:

Well without RSAT installed, obviously, this answer becomes pointless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM