obtener_usuarios_con_una_sesion_iniciada_en_un_grupo_de_hosts

Get Logged-On Users Script Using PowerShell

This PowerShell script retrieves the list of Active Directory computers with names starting with 'BOIAVD', checks for logged-on users on each computer, and outputs the results in the format `{host, user}`. This format is suitable for copying into Excel.

Script Details

  1. Retrieve AD Computers: The script uses `Get-ADComputer` to fetch the list of computers with names starting with 'BOIAVD'.
  2. Retrieve Logged-On Users: It queries `explorer.exe` processes on each computer and retrieves the owner (user) of each process.
  3. Output Formatting: The results are formatted as `{host, user}`, making it easy to copy into Excel.

PowerShell Script

# Import Active Directory module
Import-Module ActiveDirectory
 
# Get the list of Active Directory computers with names starting with 'BOIAVD'
$computers = Get-ADComputer -Filter 'Name -like "BOIAVD*"' -Property Name | Select-Object -ExpandProperty Name
 
# Function to get logged-on users via explorer.exe process
function Get-LoggedOnUsers {
    param (
        [string]$computerName
    )
 
    try {
        # Get explorer.exe processes
        $userInfo = Get-CimInstance win32_process -ComputerName $computerName -Filter 'Name = "explorer.exe"' -ErrorAction SilentlyContinue -ErrorVariable userInfoError
 
        if ($userInfoError) {
            return @("Unable to gather logged on user information")
        } else {
            $loggedOnUsers = $userInfo | ForEach-Object { 
                $owner = Invoke-CimMethod -InputObject $_ -MethodName GetOwner
                $owner.User
            } | Select-Object -Unique
 
            if ($loggedOnUsers -ne $null -and $loggedOnUsers.Count -gt 0) {
                return $loggedOnUsers
            } else {
                return @("(None)")
            }
        }
    }
    catch {
        return @("Failed to retrieve logged on users for $computerName. Error: $_")
    }
}
 
# Loop through each computer and get logged-on users
$results = @()
foreach ($computer in $computers) {
    $users_in_host = Get-LoggedOnUsers -computerName $computer
 
    foreach ($user in $users_in_host) {
        $results += "$computer, $user"
    }
}
 
# Output results
$results | ForEach-Object { Write-Output $_ }

How to Run the Script

  1. Open PowerShell in a Domain Controller.
  2. Copy and paste the script into the PowerShell window.
  3. Press `F5` to execute.

This will retrieve the logged-on users for each computer whose name starts with 'BOIAVD' and output the results in the format `{host, user}`.

obtener_usuarios_con_una_sesion_iniciada_en_un_grupo_de_hosts.txt · Last modified: 2024/10/17 21:42 by 127.0.0.1