The Bee
The Bee

Reputation: 15

ADSI Searcher - PowerShell get IP address after FindAll()

I am using

([adsisearcher]“objectcategory=computer”).FindAll()

and I am able to obtain a list of all connected devices to the AD. However, if I want to obtain the IP address of each device in a list fashion, how can I do that?

Please note that I do not have AD modules installed and am looking for a way to do it from the Command Prompt.

Upvotes: 1

Views: 1448

Answers (1)

Theo
Theo

Reputation: 61148

Since there is no attribute of Active Directory computer objects for IP addresses, either IPv4 or IPv6, you need to first get the list of computers and loop through that list to find the IP addresses.
Something like this (untested):

# you can add more properties if you need to
$properties = 'Name','OperatingSystem'
$searcher   = [adsisearcher]'(objectCategory=computer)'
$searcher.PropertiesToLoad.AddRange($properties)
$computers = $searcher.FindAll() 
$output = @()
foreach ($pc in $computers) {
    # get a list of IP addresses for each computer, filter on IPV4
    try {
        $name = $pc.Properties["name"]
        $ip = $null
        $ip = [System.Net.Dns]::GetHostEntry($name).AddressList | 
              Where-Object { $_.AddressFamily -eq 'InterNetwork' } | 
              Select-Object -ExpandProperty IPAddressToString
    }
    catch { 
        Write-Warning "Host '$name' could not be reached."
    }

    # create a PSObject with selected properties for each machine found
    $result = New-Object -TypeName PSObject
    foreach ($key in $properties) {
        # apparently, all property names must be lower case
        $name  = $key.ToLower()
        $value = $pc.Properties[$name]
        $result | Add-Member -MemberType NoteProperty -Name $key -Value $value
    }
    # add the 'IpV4Addresses' property
    $result | Add-Member -MemberType NoteProperty -Name 'IpV4Addresses' -Value ($ip -join ', ')

    # output the resulting object
    $output += $result
}

# display the output on screen as table
$output | Format-Table -AutoSize  
# or $output | Format-List

# or save the output to a CSV file
# $output | Export-Csv -Path 'PATH AND FILENAME FOR THE EXPORT CSV' -NoTypeInformation

If you save this to a .ps1 file, you can run it from the Command prompt like this:

powershell.exe -noexit "& 'X:\Folder\GetComputers.ps1"

Hope that helps

P.S. In your code, you have curly 'smart-quotes'. It is always a good idea to replace them with regular, straight quotes.

Upvotes: 2

Related Questions