Запрос списка компьютеров - вывод последнего зарегистрированного пользователя и последнего входа в систему - PullRequest
0 голосов
/ 10 октября 2019

Я создаю сценарий для извлечения всех имен компьютеров из TXT-файла, а затем запрашиваю их;

ComputerName UserName (последнего пользователя, вошедшего в систему) Дата последнего входа в систему. / Используется

Это то, что у меня есть

Clear-Host
$machines = Get-Content -Path C:\Users\khalifam\Desktop\Winver\MachineNames.txt
ForEach ($Compu in $machines) {
    Get-WmiObject –ComputerName $machines –Class Win32_ComputerSystem | Select 
    Username, PSComputerName | FT
}

1 Ответ

0 голосов
/ 10 октября 2019

Как sidenotes:

  • дефисы для имен параметров - это не дефисы, а En-Dash es, поэтому я понимаю, что этот код скопирован из Интернета где-то
  • внутри цикла вы используете неверную переменную в параметре ComputerName, которая должна быть $Compu

Сказав это, я не думаю, что вы можете получить необходимую информацию изWMI Win32_ComputerSystem class ..
Вам нужно будет проанализировать информацию из журнала событий компьютеров:

# get an array of computernames loaded from the text file
$machines = Get-Content -Path C:\Users\khalifam\Desktop\Winver\MachineNames.txt

$result = foreach ($computer in $machines) {
    # test if the compurer is on-line
    if (!(Test-Connection -ComputerName $computer -Count 1 -Quiet)) {
        Write-Warning "Computer '$computer' is off-line."
        # skip this computer and carry on with the next iteration
        continue
    }

    # search the computers eventlog and parse the username and last logon time from that
    # you can play around with other values for -MaxEvents if you feel you're missing information.
    Get-WinEvent -ComputerName $computer -FilterHashtable @{Logname='Security';ID=4672} -MaxEvents 20 | 
        Where-Object { $_.Properties[1].Value -notmatch 'SYSTEM|NETWORK SERVICE|LOCAL SERVICE' } | 
        Select-Object @{Name ='ComputerName'; Expression = {$_.MachineName}},
                      @{Name ='UserName';     Expression = {$_.Properties[1].Value}},
                      @{Name ='LastLogon';    Expression = {$_.TimeCreated}} -First 1

}

# show on screen:
$result | Format-Table -AutoSize

# save as CSV file
$result | Export-Csv -Path 'D:\LastLogonInfo.csv' -NoTypeInformation


Обновление

ЕслиЯ правильно понимаю ваш комментарий, вы хотели бы получить список всех пользователей (кроме нескольких) и получить их последний логин на компьютере из списка.

В этом случае вы можете сделатьследующее:

# get an array of computernames loaded from the text file
$machines = Get-Content -Path C:\Users\khalifam\Desktop\Winver\MachineNames.txt
$result = foreach ($computer in $machines) {
    # test if the compurer is on-line
    if (!(Test-Connection -ComputerName $computer -Count 1 -Quiet)) {
        Write-Warning "Computer '$computer' is off-line."
        # skip this computer and carry on with the next iteration
        continue
    }

    # you do not want to include these account logins
    $exclude = '\$|SYSTEM|NETWORK SERVICE|LOCAL SERVICE|KHALIFAM'
    # search the computers eventlog and parse the username and last logon time from that
    # you can play around with other values for -MaxEvents if you feel you're missing information.
    Get-WinEvent -ComputerName $computer -FilterHashtable @{Logname='Security';ID=4672} -MaxEvents 100 | 
        Where-Object { $_.Properties[1].Value -notmatch $exclude } | 
        Select-Object @{Name ='ComputerName'; Expression = {$_.MachineName}},
                      @{Name ='UserName';     Expression = {$_.Properties[1].Value}},
                      @{Name ='LastLogon';    Expression = {$_.TimeCreated}} |
        Group-Object -Property UserName | ForEach-Object {
            $_.Group | Sort-Object LastLogon -Descending | Select-Object -First 1
        }
}

# show on screen:
$result | Format-Table -AutoSize

# save as CSV file
$result | Export-Csv -Path 'D:\LastLogonInfo.csv' -NoTypeInformation
...