首页 > 解决方案 > 如何从用户列表中找到 PC

问题描述

我需要帮助。我不太确定这是否可能。

我有文件列表,samAccountName.csv需要从中获取他们的 PC 名称和 IP。

我不太确定如何构建这样的脚本。

标签: powershellactive-directorypowershell-2.0powershell-3.0

解决方案


执行此操作的一种方法是遍历环境中的所有计算机并测试每一台计算机。这当然会很

问题中没有您的 CSV 文件是什么样子的示例,但如果它看起来像这样:

    "SamAccountName","职务"
    "jdoe","testuser"
    "rboizov","系统管理员"

你可以做:

# get an aray if SamAccountNames from the Csv
$userNames = Import-Csv -Path 'PathToYOurCsvFile' | Select-Object -ExpandProperty SamAccountName

# get all computer objects from AD and loop through
# this of course can take a LONG time to finish..
$result = Get-ADComputer -Filter * | ForEach-Object {
    Write-Host "Testing computer $($_.Name)"
    if (Test-Connection -ComputerName $_.Name -Count 1 -Quiet) {
        $pc = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $_.Name
        # or use: $pc = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $_.Name

        $user = ($pc.UserName -split '\\')[-1]
        if ($userNames -contains $user) {
            [PSCustomObject]@{ 
                'SamAccountName' = $user
                'ComputerName'   = $pc.Name
                'IP'             = (Test-Connection -ComputerName $pc.Name -Count 1).IPV4Address.IPAddressToString
            }
        }
    }
    else {
        Write-Warning "Computer $($_.Name) could not be reached"
    }
}

#output in console
$result

# output to Csv
$result | Export-Csv -Path 'UsersOnComputers.csv' -NoTypeInformation

可能有一种更快的方法,但只有当您的用户的所有主目录都已重定向到中央服务器\共享时才能工作。如果您的环境是这种情况,请告诉我


实验性的

以下方法用于Win32_ServerConnection查找到用户 HomeDrive 文件夹的所有会话。

仅当您的用户的所有主目录都已重定向到中央\\server\share时,这才有效,当然,如果您的权限允许它

 # the UNC \\Server\Share name of the network share where all user homedirectories are
$usersHomePath = '\\HomesServer\HomesShare$' 

# get an aray if SamAccountNames from the Csv
$userNames = Import-Csv -Path 'PathToYOurCsvFile' | Select-Object -ExpandProperty SamAccountName

# split the UNC path to get the server name and share name separate
$svr = $usersHomePath.TrimStart("\") -split '\\'        #"# fix syntax highlighting for SO..
$server = $svr[0]
$share  = $svr[-1]

$result = Get-CimInstance -ClassName Win32_ServerConnection -ComputerName $server |  # or use: Get-WmiObject -Class Win32_ServerConnection
            Where-Object { $_.ShareName -eq $share -and $userNames -contains $_.UserName } |
            Select-Object @{Name = "SamAccountName"; Expression = { $_.UserName }}, 
                          @{Name = "ComputerName"; Expression = {(([System.Net.Dns]::GetHostEntry($_.ComputerName).HostName) -split "\.")[0]}},
                          @{Name = "IP"; Expression = { (Test-Connection -ComputerName $_.ComputerName -Count 1).IPV4Address.IPAddressToString }} |
            Sort-Object SamAccountName

#output in console
$result

# output to Csv
$result | Export-Csv -Path 'UsersOnComputers.csv' -NoTypeInformation

推荐阅读