Tuesday, June 2, 2015

#78 : Find who is logged in list of machines using Powershell

Recently, there were list of workstations assigned to our team. As there are many people working on those workstations, it was difficult to find who is logged in on which machine without asking. Finally, I ended with below script which can tell the same easily.

Below are steps for testing the script :

1. Create a directory, say WhoLoggedIn.
2. Create a file with name list.txt.
3. Use Notepad and edit list.txt and add all servers with one line for each server.
4. Create a Powershell script say WhoLoggedIn.ps1

Paste the code from below :

$THIS_SCRIPT_NAME=${myInvocation}.ScriptName
$SCRIPT_LOC=Split-Path -parent ${Script:THIS_SCRIPT_NAME}
 

$VALS=gc $SCRIPT_LOC\List.txt | where { $_ -match "^[1-9]" } | foreach { $_ + $(& query user /server:"$_")  }

$FINAL_VAL=$VALS | foreach { $_.replace("USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME  ","") } | foreach { $_.replace("  ", " ") }

echo $FINAL_VAL


Run the same and you will see results in proper format. I made a script which will log the same info into SQL Server using the same script. Choice is all yours what you do with it. My job is to give direction ...

Enjoy!

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...