xs4eyes

Find-user

Aug 16th, 2016
1,309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     function Find-User
  2.     {
  3.         <#
  4.             .SYNOPSIS
  5.             Finds user from the username or a portion of the username.
  6.             .DESCRIPTION
  7.             Connects to the fileserver and runs Net session to collect the
  8.             user names that have open connections. Strips the IP and Username
  9.             from the string.
  10.             Uses System.net.dns to get the computer name.
  11.             .EXAMPLE
  12.             Find-User smith
  13.             If it is only a portion of a username it could find multiple results
  14.  
  15.             CSmith is logged into PC1 with IP address 192.168.20.1
  16.  
  17.             CSmith is logged into PC2 with IP address 192.168.20.2
  18.  
  19.             psmith is logged into PC3 with IP address 192.168.20.3
  20.  
  21.             ssmith is logged into PC4 with IP address 192.168.20.4
  22.  
  23.             .EXAMPLE
  24.             Find-User -username csmith
  25.  
  26.             If using the exact username it will find all connections for that one user.
  27.  
  28.             CSmith is logged into pc1 with IP address 192.168.20.1
  29.  
  30.             CSmith is logged into pc2 with IP address 192.168.20.2
  31.         #>
  32.    
  33.         [CmdletBinding()]
  34.         param
  35.         (
  36.             [Parameter(Mandatory=$true, Position=0)]
  37.             [Object]
  38.             $Username = (read-host "Please enter the Primary  user"),
  39.             $FILESERVER = "Name of Fileserver"
  40.         )
  41.         # Connect Remotely to Server, Run Session, get a list of everybody logged in there
  42.    
  43.         $S=NEW-PSSESSION –computername $FILESERVER
  44.         $Results=(INVOKE-COMMAND –Session $s –scriptblock { (NET SESSION) }) | Select-string $USERNAME
  45.         REMOVE-PSSESSION $S
  46.         # Let’s parse through the data and pull out what we need  
  47.         Foreach ( $Part in $RESULTS ) {
  48.             $ComputerIP=$Part.Line.substring(2,21).trim()
  49.             $User=$Part.Line.substring(21,44).trim()
  50.             # Use nslookup to identify the computer, grab the line with the “Name:” field in it
  51.             $Computername=([System.Net.dns]::GetHostbyAddress("$ComputerIP"))
  52.             $computername =  $ComputerName.HostName
  53.             If ($Computername -eq $NULL) { $Computername=”Unknown”}
  54.             #Else { $Computername=$Computername.substring(9).trim()}
  55.             write-host
  56.             # Show me where the silly fool is hiding
  57.             “$User is logged into $Computername with the IP address $ComputerIP”
  58.         }
  59.     }
Advertisement
Add Comment
Please, Sign In to add comment