PowerShell: Find computers that a specific user is logged on with the LastLogonDate

Anxo Alonso 1 Reputation point
2023-01-20T21:32:14.29+00:00

Good afternoon,

I would need to run a script that would tell me which computers a particular user was logged into.

I found this script:

#Set variables
$progress = 0

#Get Admin Credentials
Function Get-Login {
Clear-Host
Write-Host "Please provide admin credentials (for example DOMAIN\admin.user and your password)"
$Global:Credential = Get-Credential
}
Get-Login

#Get Username to search for
Function Get-Username {
	Clear-Host
	$Global:Username = Read-Host "Enter username you want to search for"
	if ($Username -eq $null){
		Write-Host "Username cannot be blank, please re-enter username!"
		Get-Username
	}
	$UserCheck = Get-ADUser $Username
	if ($UserCheck -eq $null){
		Write-Host "Invalid username, please verify this is the logon id for the account!"
		Get-Username
	}
}
Get-Username

#Get Computername Prefix for large environments
Function Get-Prefix {
	Clear-Host
	$Global:Prefix = Read-Host "Enter a prefix of Computernames to search on (CXX*) use * as a wildcard or enter * to search on all computers"
	Clear-Host
}
Get-Prefix

#Start search
$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

#Start main foreach loop, search processes on all computers
foreach ($comp in $computers){
	$Computer = $comp.Name
	$Reply = $null
  	$Reply = test-connection $Computer -count 1 -quiet
  	if($Reply -eq 'True'){
		if($Computer -eq $env:COMPUTERNAME){
			#Get explorer.exe processes without credentials parameter if the query is executed on the localhost
			$proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
		}
		else{
			#Get explorer.exe processes with credentials for remote hosts
			$proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
		}			
			#If $proc is empty return msg else search collection of processes for username
		if([string]::IsNullOrEmpty($proc)){
			write-host "Failed to check $Computer!"
		}
		else{	
			$progress++			
			ForEach ($p in $proc) {				
				$temp = ($p.GetOwner()).User
				Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
				if ($temp -eq $Username){
				write-host "$Username is logged on $Computer"
				}
			}
		}	
	}
}
write-host "Search done!"

The problem is that I would need it to also tell me the LastLogonDate of that user on those computers found by the script.

I tried several times to add some corrections to the script but i could not achieve it.

Could you help me with this task, please?

Thank so much.

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

7 answers

Sort by: Most helpful
  1. Santhi Swaroop Naik Bukke 595 Reputation points
    2023-01-20T21:36:16.6166667+00:00
    You can use the PowerShell cmdlet Get-AdComputer to find computers that a specific user is logged on to, along with the user's last logon date. Here is an example of how you can do this:
    
    Copy code
    $username = 'Username'
    $computers = Get-ADComputer -Filter {LastLogonDate -like "*$username*"}
    foreach ($computer in $computers) {
        Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer.Name | Select-Object Name, UserName, @{Name="LastLogonDate";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}}
    }
    This script uses the Get-ADComputer cmdlet to find all computers where the LastLogonDate attribute contains the specified username. Then it uses a foreach loop to iterate through each computer and run the Get-WmiObject cmdlet to retrieve the computer's name, the username of the currently logged on user, and the last logon date, which is obtained from the LastBootUpTime property of the Win32_ComputerSystem class and converted to a datetime format using ConvertToDateTime() method.
    
    It's important to note that the above script only works if the ActiveDirectory module is installed and available in your environment and the user running the script has the permission to run the script.
    
    Also, the script uses the LastBootUpTime property instead of the LastLogonDate property, because the LastLogonDate property is not available in the WMI class Win32_ComputerSystem.
    
    Finally, it's worth mentioning that the script will only return the computers that are currently powered on and have a network connection, otherwise the script will fail to get the information of the computers.
    

  2. Santhi Swaroop Naik Bukke 595 Reputation points
    2023-01-20T21:37:01.3533333+00:00
    You can use the PowerShell cmdlet Get-AdComputer to find computers that a specific user is logged on to, along with the user's last logon date. Here is an example of how you can do this:
    
    Copy code
    $username = 'Username'
    $computers = Get-ADComputer -Filter {LastLogonDate -like "*$username*"}
    foreach ($computer in $computers) {
        Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer.Name | Select-Object Name, UserName, @{Name="LastLogonDate";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}}
    }
    This script uses the Get-ADComputer cmdlet to find all computers where the LastLogonDate attribute contains the specified username. Then it uses a foreach loop to iterate through each computer and run the Get-WmiObject cmdlet to retrieve the computer's name, the username of the currently logged on user, and the last logon date, which is obtained from the LastBootUpTime property of the Win32_ComputerSystem class and converted to a datetime format using ConvertToDateTime() method.
    
    It's important to note that the above script only works if the ActiveDirectory module is installed and available in your environment and the user running the script has the permission to run the script.
    
    Also, the script uses the LastBootUpTime property instead of the LastLogonDate property, because the LastLogonDate property is not available in the WMI class Win32_ComputerSystem.
    
    Finally, it's worth mentioning that the script will only return the computers that are currently powered on and have a network connection, otherwise the script will fail to get the information of the computers.
    
    0 comments No comments

  3. Santhi Swaroop Naik Bukke 595 Reputation points
    2023-01-20T21:40:28.86+00:00
    To check for the user's last logon date, you can use the Win32_NetworkLoginProfile WMI class and retrieve the LastLogon property which is in the format of a timestamp. Here is an example of how you can do this:
    
    Copy code
    $user = 'Username'
    $computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
    foreach ($computer in $computers) {
        $lastLogon = (gwmi -Class Win32_NetworkLoginProfile -ComputerName $computer.Name | Where-Object {$_.Name -eq $user}).LastLogon
        if($lastLogon){
            write-host "$user last logged on $computer on $(($lastLogon).ToLocalTime())"
        }
    }
    This script uses the Get-ADComputer cmdlet to find all enabled computers that match the specified prefix. Then it uses a foreach loop to iterate through each computer and run the Get-WmiObject cmdlet to retrieve the Win32_NetworkLoginProfile class, and filters it by the username you are searching for. The LastLogon property is retrieved and converted to a readable date format using the .ToLocalTime() method.
    
    It's important to note that the LastLogon property only gives you the last logon date of the user on that specific computer and it's not a global property across the domain. Also, the above script uses Win32_NetworkLoginProfile class which is only available on Windows 7 and Windows Server 2008 R2 or later.
    
    Also, you need to make sure that the necessary PowerShell modules are installed and available in your environment and the user running the script has the permission to run the script.
    

  4. Anxo Alonso 1 Reputation point
    2023-01-20T21:41:43.4033333+00:00

    @Santhi Swaroop Naik Bukke Thank so much for the info.

    In which part of the script do you add this information?

    Thank so much.


  5. Anxo Alonso 1 Reputation point
    2023-01-23T00:31:51.81+00:00

    Finally i could solve it with the "query user" line: query user $Username /server:$Computer

    I wouId like to know, to have the perfect script, if, when the "query user" command shows all information: https://ibb.co/jZ6NsF2

    I need that it shows only the LOGON TIME information.

    Is that possible?

    Thank so much.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.