Skip to content

Instantly share code, notes, and snippets.

@danblank000
Created August 19, 2017 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danblank000/a60f24ac919a8d782ffaa308f4689a9e to your computer and use it in GitHub Desktop.
Save danblank000/a60f24ac919a8d782ffaa308f4689a9e to your computer and use it in GitHub Desktop.
Queries share connections to see what machine a users is currently logged in to
Import-Module activedirectory
write-host "**************************************************************"
Write-Host "`nThis script will tell you what computer a user is logged in to" -ForegroundColor Yellow -BackgroundColor Black
write-host "`n**************************************************************"
$i = 0
#sets up credentials
$myusername = "**DOMAIN**\" + [Environment]::UserName
$credentials = Get-Credential -UserName $myusername -Message "Please enter your ADMIN password"
write-host "`nPlease enter a user name to query:" -ForegroundColor Yellow
$name = read-host
$username = ((get-aduser -filter * | where {$_.name -like "$name"} | select samaccountname).samaccountname).tostring()
# Gets relevant servers with shares:
write-host "`nGetting server list." -ForegroundColor Cyan
$servers = get-adcomputer -filter {(name -like "*KSLNAS01*") -or (name -like "kslpartner") -or (name -like "kslsql01*") -or (name -like "kslfs01")} | sort-object name
# Starts a job for each server
write-host ""
write-host 'Querying' $servers.count 'servers.' -ForegroundColor Yellow
$servercount = $servers.count
foreach ($server in $servers)
{
# Querying each of the servers for connections to shares
$servername = $server.name
$userSessions = Get-WmiObject Win32_ServerConnection -computername $servername -Credential $credentials
#progress bar
write-host "Querying $servername" -ForegroundColor DarkYellow
Write-Progress -activity "Servers Processed" -status "Percent Complete : " -PercentComplete (($i++ / $Servers.Length) * 100)
# Filtering out the results
foreach ($userSession in $userSessions)
{
if ($userSession.username -eq $username)
{
#convert ip to hostname
$IPAddress = $userSession.computername
$hostname = Get-WmiObject win32_computersystem -Computer $IPAddress -Credential $credentials
$found = "yes"
#select user details
$userDetails = [string]::Format("User {0} is logged on to {1}", $userSession.UserName, $hostname.name)
#print user details
Write-Host "`n$userDetails" -ForegroundColor Green
$continue = read-host "`nPress ENTER to exit"
if ($continue -Ne "C")
{
exit
}
}
else
{
#if no instances are found, continue to search next server
}
}
}
if ($found -ne "yes")
{
write-host "I can't find any PCs with $user logged in to them" -ForegroundColor Red
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment