?
Solved

Last Domain User Logon Powershell Script

Posted on 2012-04-04
17
Medium Priority
?
1,789 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
Office 365 Training for IT Pros

Learn how to provision tenants, synchronize on-premise Active Directory, implement Single Sign-On, customize Office deployment, and protect your organization with eDiscovery and DLP policies.  Only from Platform Scholar.

 
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 1000 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 1000 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

Need protection from advanced malware attacks?

Look no further than WatchGuard's Total Security Suite, providing defense in depth against today's most headlining attacks like Petya 2.0 and WannaCry. Keep your organization out of the news with protection from known and unknown threats.

Question has a verified solution.

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

There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
Compliance and data security require steps be taken to prevent unauthorized users from copying data.  Here's one method to prevent data theft via USB drives (and writable optical media).
This tutorial will walk an individual through configuring a drive on a Windows Server 2008 to perform shadow copies in order to quickly recover deleted files and folders. Click on Start and then select Computer to view the available drives on the se…
This tutorial will show how to configure a single USB drive with a separate folder for each day of the week. This will allow each of the backups to be kept separate preventing the previous day’s backup from being overwritten. The USB drive must be s…
Suggested Courses

765 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