Solved

Last Domain User Logon Powershell Script

Posted on 2012-04-04
17
1,761 Views
Last Modified: 2012-08-14
I need a powershell script that will let me put in a computer name, and tell me who the last domain user logged on to that workstation was.  I have been using the following, but it only gives me the primary owner name:

PS> Gwmi Win32_ComputerSystem -Comp "pcname"
0
Comment
Question by:fireguy1125
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 6
  • 2
  • +1
17 Comments
 
LVL 17

Expert Comment

by:Anuroopsundd
ID: 37806051
Get-WmiObject Win32_NetworkLoginProfile |
    Sort -Descending LastLogon |
    Select * -First 1 |
    ? {$_.LastLogon -match "(\d{14})"} |
        % {
            New-Object PSObject -Property @{
                Name=$_.Name ;
                LastLogon=[datetime]::ParseExact($matches[0], "yyyyMMddHHmmss", $null)
            }
        }

http://www.powershellcommunity.org/Forums/tabid/54/aft/4831/Default.aspx
0
 
LVL 1

Author Comment

by:fireguy1125
ID: 37806060
Which area do I enter the computer name in your code? And also, is there a way to copy and paste all your lines into powershell at once? Every time I do it, it just brings me to another >> line. Thanks.
0
 
LVL 17

Expert Comment

by:Anuroopsundd
ID: 37806086
$data = @()
$profiles = GWMI Win32_NetworkLoginProfile -ComputerName COMPUTER_NAME
foreach ($profile in $profiles){
$date = $profile.LastLogon
if ($date -ne $null -and $date -ne "**************.******+***") {
$row = "" | Select User,LogonTime
$year = $date.SubString(0,4)
$month = $date.SubString(4,2)
$day = $date.SubString(6,2)
$hour = $date.SubString(8,2)
$min = $date.SubString(10,2)
$sec = $date.Substring(12,2)
$row.User = $Profile.Name
$row.LogonTime = Get-Date -Date ($month + "/" + $day + "/" + $year + " " + $hour + ":" + $min + ":" + $sec)
$data += $row
}
}
$data | Sort -Descending LogonTime | select -First
0
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 
LVL 1

Author Comment

by:fireguy1125
ID: 37806127
I copied and pasted the code, and changed the COMPUTER_NAME, however when I press enter, it still brings me to another blank line >>
0
 
LVL 1

Author Comment

by:fireguy1125
ID: 37806214
Ok, I read somewhere I have to press Enter twice on the keyboard :)  However, it brings me back to the first issue, where the results it returns are only LOCAL users on that computer, I need the domain user accounts.
0
 
LVL 12

Expert Comment

by:prashanthd
ID: 37806236
You need to copy the code to a .ps1 file and execute the file..
0
 
LVL 1

Author Comment

by:fireguy1125
ID: 37806242
Can you please provide code for that, since I'm not fluent in PowerShell.   Thank you.
0
 
LVL 12

Expert Comment

by:prashanthd
ID: 37806432
copy anyone of the above code to notepad, save file as lastuser.ps1 and execute from powershell window.

http://technet.microsoft.com/en-us/library/ee176949.aspx
0
 
LVL 1

Author Comment

by:fireguy1125
ID: 37806484
Followed instructions in technet article provide, created the lastuser.ps1 file, and ran the script, however it returns error:

PS C:\> .\lastuser.ps1
Select-Object : Missing an argument for parameter 'First'. Specify a parameter of type 'System.Int32' and try again.
At C:\lastuser.ps1:18 char:51
+ $data | Sort -Descending LogonTime | select -First <<<<
    + CategoryInfo          : InvalidArgument: (:) [Select-Object], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.SelectObjectCommand
0
 
LVL 12

Expert Comment

by:prashanthd
ID: 37806615
Try the following..

$data = @()

$NetLogs = Get-WmiObject Win32_NetworkLoginProfile

foreach ($NetLog in $NetLogs) {
if ($NetLog.LastLogon -match "(\d{14})") {
$row = "" | Select Name,LogonTime
$row.Name = $NetLog.Name
$row.LogonTime=[datetime]::ParseExact($matches[0], "yyyyMMddHHmmss", $null)
$data += $row
}
}

$data

Open in new window

0
 
LVL 1

Author Comment

by:fireguy1125
ID: 37806795
Where do I enter the computer name that I want to check this against in that script? When I run that, it only shows the domain controller that I am running it on. So it works, I just need to input domain computers in it to check on those.
0
 
LVL 12

Expert Comment

by:prashanthd
ID: 37807147
Try the following..

$strcomputer="DC001"
$data = @()

$NetLogs = Get-WmiObject Win32_NetworkLoginProfile -computername $strcomputer

foreach ($NetLog in $NetLogs) {
if ($NetLog.LastLogon -match "(\d{14})") {
$row = "" | Select Name,LogonTime
$row.Name = $NetLog.Name
$row.LogonTime=[datetime]::ParseExact($matches[0], "yyyyMMddHHmmss", $null)
$data += $row
}
}

$data
        

Open in new window

0
 
LVL 12

Expert Comment

by:prashanthd
ID: 37807176
Give all the server names to query in a text file and modify the path to text file

$file=Get-Content "c:\server_list.txt"

foreach($strcomputer in $file){
$data = @()

$NetLogs = Get-WmiObject Win32_NetworkLoginProfile -computername $strcomputer

foreach ($NetLog in $NetLogs) {
if ($NetLog.LastLogon -match "(\d{14})") {
$row = "" | Select Name,LogonTime
$row.Name = $NetLog.Name
$row.LogonTime=[datetime]::ParseExact($matches[0], "yyyyMMddHHmmss", $null)
$data += $row
}
}

$data
}        

Open in new window

0
 
LVL 1

Author Comment

by:fireguy1125
ID: 37807227
So I put in all the domain controllers we have in the text file, now where do I put in the computer name?
0
 
LVL 12

Assisted Solution

by:prashanthd
prashanthd earned 250 total points
ID: 37807326
Do you need to query one workstation at a time or multiple workstations?

If multiple workstations put all the workstations to be queried in the text file.

If only one workstation modify the $strcomputer="WKS001" in the second last script
0
 
LVL 1

Author Comment

by:fireguy1125
ID: 37829979
When I put the workstation names in the server_list.txt file, it doesn't return the domain logins, but the local logins.
0
 
LVL 70

Accepted Solution

by:
Qlemo earned 250 total points
ID: 37849404
That last script works - just tested from a non-domain-member environment against a domain.
But there are several things which aren't good style. First, we should always indent. Second, it is better to stream the file contents into a pipeline instead of storing it in vars when not needed for other processing. Having to use a bunch of variables will hog the memory in many cases.
Get-Content "c:\server_list.txt" | % {
  Get-WmiObject Win32_NetworkLoginProfile -computername $_ | % {
    if ($_.LastLogon -match "(\d{14})") {
      $row = "" | Select Name,LogonTime
      $row.Name = $_.Name
      $row.LogonTime = [datetime]::ParseExact($matches[0], "yyyyMMddHHmmss", $null)
      $row
    }
  }
}        

Open in new window

BTW, I like use of the RegEx for match here, as it servers two purposes.

That you get your local accounts here is strange. Please check if
gwmi Win32_NetworkLoginProfile -computername

Open in new window

provides the correct (remote/domain) accounts.
0

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For anyone that has accidentally used newSID with Server 2008 R2 (like I did) and hasn't been able to get the server running again because you were unlucky (as I was) and had no backups - I was able to get things working by doing a Registry Hive rec…
This article provides a convenient collection of links to Microsoft provided Security Patches for operating systems that have reached their End of Life support cycle. Included operating systems covered by this article are Windows XP,  Windows Server…
This tutorial will walk an individual through the steps necessary to install and configure the Windows Server Backup Utility. Directly connect an external storage device such as a USB drive, or CD\DVD burner: If the device is a USB drive, ensure i…
This tutorial will walk an individual through setting the global and backup job media overwrite and protection periods in Backup Exec 2012. Log onto the Backup Exec Central Administration Server. Examine the services. If all or most of them are stop…

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question