Powershell. Отчет о подключениях / отключениях пользователей с Терминального Сервера

Скрипт PS который выбирает из логов Терминальных Служб события подключения, отключения, дисконнекта пользователей для выбранного компьютера.

Поправить значение:
StartTime = (Get-Date).AddDays(-30)
если нужно

Поправить выходной файл:
$OutputFilePath = “C:\123\file.csv”
если нужно

[CmdletBinding()]
Param(
  [Parameter(Mandatory = $false,
             Position = 0,
             ValueFromPipeline = $true,
             ValueFromPipelineByPropertyName = $true,
             HelpMessage = "Computer or computers to get Remote Desktop history for.")]
  [String[]]$computers
)

Import-Module ActiveDirectory -Verbose:$false

Function getDisplayNameFromUser($userName) {
  Try {
    Return Get-ADUser $userName -ErrorAction SilentlyContinue | Select-Object -ExpandProperty name
  } Catch {
    Return [string]::Empty
  }
}

If ([string]::IsNullOrEmpty($computers)) {
  [string]$input_from_user = Read-Host "Remote Desktop history
Enter computer name (blank to quit)"
  If ($input_from_user.indexOf(",") -gt -1) {
    $computers = $input_from_user -Split ","
  } ElseIf ($input_from_user.indexOf(" ") -gt -1) {
    $computers = $input_from_user -Split " "
  } Else {
    $computers = $input_from_user
  }
}

If ([string]::IsNullOrEmpty($computers)) {
  Write-Output "No computer entered, quitting..."
  Exit
}

$filter = @{
  LogName = "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational"
  StartTime = (Get-Date).AddDays(-30)
  ID = 21, 23, 24, 25
}

$AllResults = @()

ForEach ($computer in $computers) {
  $TimerStart = Get-Date

  If (Test-Connection $computer -Count 1 -Quiet -ErrorAction SilentlyContinue) {
    Try {
      $Results = @()
      $Events = Get-WinEvent -ComputerName $computer -FilterHashtable $filter

      $eventsCount = if ($Events.Count) { $Events.Count } else { 0 }
        "Got $eventsCount events from $computer in " + [math]::Round((New-Timespan -Start $TimerStart -End $(Get-Date)).TotalSeconds, 2) + " seconds" | ForEach-Object { Write-Debug $_ }


      $progress_counter = 0
      $Events_count = $Events.Count

      ForEach ($Event in $Events) {
        $progress_counter++
        Write-Progress -Activity "Processing $($Events_count) events from $($computer)..." -Status " " -PercentComplete ($progress_counter/$Events_count * 100)

        $EventXml = [xml]$Event.ToXML()
        $source_ip = [string]::Empty
        If (Get-Member -InputObject $EventXml.Event.UserData.EventXML -Name Address -MemberType Properties) {
          $source_ip = $EventXml.Event.UserData.EventXML.Address
        }

        $Result = @{
          Computer = $computer
          Time = $Event.TimeCreated.toString("d/MMM/yyyy h:mmtt")
          "Event ID" = $Event.Id
          "Desc" = ($Event.Message -split [environment]::NewLine)[0]
          Username = [string]$EventXml.Event.UserData.EventXML.User.Replace("DOMAIN\", [string]::Empty)
          DisplayName = getDisplayNameFromUser([string]$EventXml.Event.UserData.EventXML.User.Replace("DOMAIN\", [string]::Empty))
          "Source IP" = $source_ip
        }

        $Results += (New-Object PSObject -Property $Result) |
          Select-Object Computer, Time, Username, DisplayName, "Source IP",
            @{ Name = "Event description"; Expression = {
                If ($Event.Id -eq "21") { "Logon" }
                If ($Event.Id -eq "23") { "Logoff" }
                If ($Event.Id -eq "24") { "Disconnected" }
                If ($Event.Id -eq "25") { "Reconnection" }
              }
            }
      }

      $AllResults += $Results

    } Catch {
      $msg = "Error getting events on $computer" + ": " + $error[0].ToString()
      Write-Error $msg
    }
  } Else {
    Write-Warning "The computer $computer is not contactable, skipping..."
  }
}

$OutputFilePath = "C:\123\file.csv"
$AllResults | Export-Csv -Path $OutputFilePath -NoTypeInformation -Encoding UTF8
Write-Host "Results exported to: $OutputFilePath"

Write-Debug "Done!"
Exit

Ссылки

https://gist.github.com/thomasswilliams/473f02c52e7036e84486dd8515dff7d0

Оставьте ответ

Ваш адрес email не будет опубликован.

÷ 1 = 5