ADSI Searcher-PowerShell在FindAll()之后获取IP地址

时间:2019-05-03 09:39:40

标签: powershell active-directory

我正在使用

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

,我可以获得与AD连接的所有设备的列表。但是,如果我想以列表方式获取每个设备的IP地址,该怎么办?

请注意,我没有安装AD模块,正在寻找一种方法来从命令提示符处进行操作。

1 个答案:

答案 0 :(得分:0)

由于没有Active Directory计算机对象的IP地址(IPv4或IPv6)属性,因此您需要首先获取计算机列表并循环浏览该列表以找到IP地址。
像这样(未经测试):

# 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

如果将其保存到.ps1文件,则可以从命令提示符运行它,如下所示:

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

希望有帮助

P.S。在代码中,您有卷曲的“智能引号”。用常规的直引号代替它们总是一个好主意。