Список пользователей Powershell и их хосты - PullRequest
0 голосов
/ 15 мая 2018

Есть ли у кого-нибудь предложения? Мне нужно создать список пользователей и компьютеров, на которых они входят, из Active Directory. Я надеюсь получить что-то вроде этого:

Имя пользователя Имя хоста

user.lastname ComputerA1

Пока я получил:

Enter-PSSession Импорт-Модуль ActiveDirectory Get-ADComputer -Filter * -Properties Name Get-ADuser -filter * -Properties * | export-csv '\\\ AD_UserLists.csv'

Это работает, вроде. Я могу создать список компьютеров из AD, и я могу создать список ADUsers (хотя со всей информацией о пользователях). К сожалению, я не могу сгенерировать данные в один CSV.

Предложения / Совет ????

Thanx, David

Ответы [ 3 ]

0 голосов
/ 15 мая 2018

Вы можете использовать функцию wmi

Get-WmiObject -Class Win32_ComputerSystem -ComputerName "computersname" | Select-Object Name,Username
0 голосов
/ 16 мая 2018

Вот способ получить то, что вы хотите.Вам нужно будет выполнить это для объектов AD-Computer, когда машины подключены к сети, и перехватить имена компьютеров, к которым вы не можете подключиться.Как то так ...

    #grab the DN of the OU where your computer objects are located...
    $OU = ("OU=Computers,DC=domain,DC=com")

    #put your filtered results in $computers (I filtered for Enabled objects)...
    $computers = @()

    ForEach ($O in $OU) {

        $computers += Get-ADComputer -SearchBase $O -filter 'Enabled -eq "True"' -Properties CN,distinguishedname,lastLogonTimeStamp | Select-Object CN,distinguishedname,lastLogonTimeStamp

    }

    #instantiate some arrays to catch your results
    #collected user info
    $userInfo = @()
    #computers you cannot ping
    $offline = @()
    #computers you can ping but cannot establish WinRM connection
    $winRmIssue = @()

    #iterate over $computers list to get user info on each...
    ForEach ($computer in $computers) {

    #filter out System account SIDs
    $WQLFilter = "NOT SID = 'S-1-5-18' AND NOT SID = 'S-1-5-19' AND NOT SID = 'S-1-5-20'" 

    $WQLFilter = $WQLFilter + " AND NOT SID = `'$FilterSID`'"

    #set number of login events to grab
    $newest = 20     

        #attempt to ping computer once by name. return 'true' is success...
        if (Test-Connection -ComputerName $computer.CN -Count 1 -ErrorAction Stop -Quiet) {

        #if ping is true, try to get some info...
            Try {

        #currently logged in user...
                $user = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer.CN | select -ExpandProperty username

        #the most commonly logged in user, based on the past 20 log-ins...
                $UserProperty = @{n="User";e={((New-Object System.Security.Principal.SecurityIdentifier $_.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])).ToString()}}
                $logs = Get-EventLog System -Source Microsoft-Windows-Winlogon -ComputerName $computer.CN -newest $newest | select $UserProperty
                $freqent = $logs | Group User | Sort-Object Count | Select -First 1 | Select-Object -ExpandProperty Name

                }

        #catch any connection issues...
            Catch {

                $cantInvoke = [pscustomobject][ordered]@{

                'Computer' = $computer.CN
                'Message' = "Could not Invoke-Command. Probably a WinRM issue."            

                }

                $winRMIssue += $cantInvoke

                }

        #custom psobject of gathered user info...
            $userInfoObj = New-Object psobject -Property ([ordered]@{

                'Computer' = $computer.CN
                'LoggedInUser' = $user
                'mostCommonUser' = $frequent            

                })

                    $userInfo += $userInfoObj

                }

        #if you could not ping the computer, gather that info here in a custom object...               
        else {

             $noPing = [pscustomobject][ordered]@{

             'Computer' = $computer.CN
             'DN' = $computer.distinguishedname
             'lastLogonDate' = [datetime]::FromFileTime($computer.lastLogonTimeStamp).toShortDateString()

             }

             $offline += $noPing

             }

 #then kick out the results to csv
$userInfo | Sort-Object Computer | export-csv -Path c:\path\file.csv -NoTypeInformation

$offline | Sort-Object lastLogonDate | export-csv -Path c:\path.file2csv -NoTypeInformation

$winRmIssue | Sort-Object Computer | export-csv -Path c:\path\file3.csv -NoTypeInformation
0 голосов
/ 15 мая 2018

Мне нужно создать список пользователей и компьютеров, в которые они входят, из Active Directory.

Эта информация не хранится в Active Directory.Вы можете быть в состоянии получить эту информацию с помощью аудита Active Directory.В противном случае вам нужно будет опросить каждую отдельную рабочую станцию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...