Link to home
Start Free TrialLog in
Avatar of mossyback
mossybackFlag for United States of America

asked on

How do I find what computer a user is logged into in Powershell?

I have a list of user names that I need to find out what computer each is logged into.  I would like to do this in Powershell.  How do I do this?
Avatar of Tribus
Tribus
Flag of United States of America image

See if this script from Spiceworks helps you:

http://community.spiceworks.com/scripts/show/1055-find-computers-a-user-is-logged-into

And here is another article to integrate this into AD:

http://deployhappiness.com/find-out-what-computer-a-user-logged-into/
This command should remotely interrogate what you need:

"gwmi -computername computername -class win32_computersystem -property username"

(remove the quotes)

You can attach this to a scheduled task and report at logon, if you don't want to do this kind of stuff via GPO.

Info sourced from here
Avatar of mossyback

ASKER

Thanks Tribus.  Unfortunately my rights allow me to query AD but not make any changes to it.  So no snappins or group policie changes will work for me.  If I could take a list of user names and run it against an OU with thousands of computers in it to find the computer name the user is logged into that would be fine.
Avatar of becraig
Here is a rough concept:

Import-Module activedirectory
$servers = Get-ADComputer  -filter {name -like "whatever filter you are using"} | select -expand name 
Foreach ($server in $servers)
{
#you could simply use if / else logic here it is expensive but gets what you want
$logcheck =  Get-WmiObject Win32_LoggedOnUser {$_.Antecedent -like "*user*"}
if ($logcheck -ne "")
{
#you can make some action here
write-host "user is logged on to computer"
}
}

Open in new window

SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I also bumped into a function here for what you need as well:

     [Cmdletbinding()]
        param (
            [Parameter(Position=0)]
            [String[]]$Computername = $ENV:COMPUTERNAME,
                   
                    [Parameter(Position=1)]
                    [ValidateSet('0','LocalSystem','2','Interactive','3','Network','4','Batch','5',
                    'Service','6','Proxy','7','Unlock','8','NetworkCleartext','9','NewCredentials',
                    '10','RemoteInteractive','11','CachedInteractive','12','CachedRemoteInteractive',
                    '13','CachedUnlock','All')]
                    [String[]]$LogonType = @('0','2','3','4','5','6','7','8','9','10','11','12','13') # All
        )
     
        Begin{
                # define LogOnType hashtable for to convert Numbers into Text
                $HashLogonType = @{
                    '0'='LocalSystem'
                    '2'='Interactive'
                    '3'='Network'
                    '4'='Batch'
                    '5'='Service'
                    '6'='Proxy'
                    '7'='Unlock'
                    '8'='NetworkCleartext'
                    '9'='NewCredentials'
                    '10'='RemoteInteractive'
                    '11'='CachedInteractive'
                    '12'='CachedRemoteInteractive'
                    '13'='CachedUnlock'
                }
               
        } # end Begin block
     
        Process {       
            ForEach($CurComputerName in $ComputerName) {           
                $LogonSessions = Get-WmiObject Win32_LogonSession -ComputerName $CurComputerName     
                ForEach($LogonSession in $LogonSessions) {                   
                    $LoggedOnUser = Get-WmiObject -Query "Associators of {Win32_LogonSession.LogonId=$($LogonSession.LogonId)} Where AssocClass=Win32_LoggedOnUser Role=Dependent" -ComputerName $CurComputerName |
                        Select-Object Domain,Name,SID,StartTime,LogonID,LogonType,LogonTypeName,ComputerName
                   
                    $LoggedOnUser.StartTime = [Management.ManagementDateTimeConverter]::ToDateTime($LogonSession.starttime)
                    $LoggedOnUser.LogonID = $LogonSession.LogonID
                    $LoggedOnUser.LogonType = $LogonSession.logontype
                    $LoggedOnUser.LogonTypeName = $HashLogonType[[String]$LogonSession.logontype]
                    $LoggedOnUser.ComputerName = $CurComputerName
                   
                                    # Filter selected LogonTypes to report
                                    If($LogonType -contains [String]$LoggedOnUser.LogonType -or $LogonType -contains $LoggedOnUser.LogonTypeName) {
                                            # return result object
                                            $LoggedOnUser
                                    }
                } # end  ForEach $LogonSession
               
            }  # end ForEach $Computer
             
        } # end process block
        End {}
     
    }

Open in new window


reposted from:
http://poshcode.org/4304


You can modify the script above to do exactly what you are asking for (feeding in both computer name from an AD scan and users from a text file input).
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
All,

There is some good stuff here for me to try which sadly I have not had the time to do.  I hope to get back to it this weekend.  Thanks for the comments!
Did this ever work for you ?

Or did you need any additional help to identify a better solution ?
I am having a can not locate a server with AD web services available.  I may not be able to do what I want since I am not an AD administrator.
Can you try running this from a poweshell console and tell me what you get:
Import-Module activedirectory
$servers = (Get-ADComputer  -filter {name -like "*"} | select -expand name )
$servers

Open in new window


You can simply run that from a powershell window, let me know if you get an error or not.

If you get an error paste the exact output in your response
Again thanks for your patience becraig - Here's what I am getting when running the command posted by: becraigPosted on 2013-10-16 at 14:48:43ID: 39577805 .  


Import-Module activedirectory
$servers = (Get-ADComputer  -filter {name -like "*"} | select -expand name )
$servers
WARNING: Error initializing default drive: 'Unable to find a default server with Active Directory Web Services running.'.
Get-ADComputer : Unable to find a default server with Active Directory Web Services running.
At line:2 char:27
+ $servers = (Get-ADComputer <<<<   -filter {name -like "*"} | select -expand name )
    + CategoryInfo          : ResourceUnavailable: (:) [Get-ADComputer], ADServerDownException
    + FullyQualifiedErrorId : Unable to find a default server with Active Directory Web Services running.,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
When I run get-module right the above command after I get:

get-module

ModuleType Name                      ExportedCommands                                              
---------- ----                      ----------------                                                          
Manifest   activedirectory           {Set-ADOrganizationalUnit, Get-ADDomainControllerPasswordReplicationPoli...
Do you already have a list of servers you want to run this against or do you really need to query the AD for all computers ?
I could query an OU in Ad to see what computers the list of users I have are logged into.  I still can NOT get past the error "unable to find a default server with Active Directory Web services running".
Could query, or could not query?
There's only one command in my script and in becraig's that uses a MS AD cmdlet, and it's used to gather a list of computers.  That's why becraig asked if you already have a list of servers, since if you do we can skip the AD query and avoid that error.

If you have a text file with the list of servers you could just do
$servers = Get-Content serverlist.txt

Open in new window


Another way of performing the query without the MS AD cmdlets is
$servers = ([ADSISearcher]"ObjectClass=Computer").FindAll() | % {$_.Properties.name}

Open in new window

This question's been open for quite a while.  Please respond to comments promptly or close the question.  Thanks.
Somehow my script error as follow:

Get-WmiObject : Not found 
At C:\Users\administrator\AppData\Local\Temp\bdd24f5d-3f01-46e7-a963-e6226a529443.ps1:8 char:50
+                     $LoggedOnUser = Get-WmiObject <<<<  -Query "Associators of {Win32_LogonSession.LogonId=$($LogonSession.LogonId)} Where AssocClass=Win32_LoggedOnUser Role=Dependent" -ComputerName $server
 | select-Object Domain,Name,SID,StartTime,LogonID,LogonType,LogonTypeName,ComputerName
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Open in new window