首页 > 解决方案 > 在 AD 的 OU 中搜索登录到多台计算机的用户的最快方法

问题描述

我正在尝试创建一个 powershell 脚本,您可以在其中输入用户名,它将解析特定 ou 中的所有机器,并查看它们是否已登录到多台机器。

我不太确定 WMI、CIM 或查询是否会为我提供最快的查询,以查看用户是否会登录到可能防止 AD 中帐户锁定的其他计算机。

输入用户名的最佳方法是什么,然后让它扫描特定的 OU 并将结果输出到 .csv 文件?

谢谢

标签: powershellactive-directory

解决方案


如果在您的 AD 环境中,您在存储所有用户主目录的服务器上有一个共享,这可能是一个解决方案。

它连接到服务器并获取与该主目录共享的用户连接列表。
使用该列表,它会查找给定用户建立的连接,并测试建立连接的计算机是否在给定的 OU 中。

$ouDN          = 'THE DISTINGHUISHED NAME OF THE OU'
$homeDirServer = 'THE NAME OF THE SERVER WHERE THE USER HOME DIRECTORIES ARE KEPT'
$homeDirShare  = 'THE NAME OF THE SHARED ROOT FOLDER OF THE USERS HOME DIRECTORIES'
$userName      = 'SAMACCOUNTNAME OF THE USER TO SEARCH FOR'
$outputFile    = 'THE PATH AND FILENAME OF THE EXPORTED CSV FILE'

# first get a list of computernames in the given OU
$computers = Get-ADComputer -Filter * -SearchBase $ouDN | Select-Object -ExpandProperty SamAccountName

# next, get user connections on the homedir share and loop through them
Get-CimInstance -Class Win32_ServerConnection -ComputerName $homeDirServer |
# or use WMI:
# Get-WmiObject -Class Win32_ServerConnection -ComputerName $homeDirServer | 

    Where-Object { $_.ShareName -eq $homeDirShare -and $_.UserName -eq $userName } | 
    # if you want a list of all user connections, use this instead:
    # Where-Object { $_.ShareName -eq $homeDirShare -and (!$($_.UserName).EndsWith("$")) } | 

    ForEach-Object {
        # get the computername from the IP Address you usually get in '$_.ComputerName'
        $computerName = (([System.Net.Dns]::GetHostEntry($_.ComputerName).HostName) -split "\.", 2)[0]
        # is this a computer in the given OU?
        if ($computers -contains $computerName) {
            # emit an object
            [PSCustomObject]@{
                'DisplayName'  = Get-ADUser -Identity $_.UserName -Properties DisplayName | Select-Object -ExpandProperty DisplayName
                'AccountName'  = $_.UserName
                'ComputerName' = $computerName
       }
    }
} | Export-Csv -Path $outputFile -NoTypeInformation

推荐阅读