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
Solved

Last Domain User Logon Powershell Script

Posted on 2012-04-04
17
1,735 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
  • 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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
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 69

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

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

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

Last week, our Skyport webinar on “How to secure your Active Directory” (https://www.experts-exchange.com/videos/5810/Webinar-Is-Your-Active-Directory-as-Secure-as-You-Think.html?cid=Gene_Skyport) provided 218 attendees with a step-by-step guide for…
This article describes my battle tested process for setting up delegation. I use this process anywhere that I need to setup delegation. In the article I will show how it applies to Active Directory
This tutorial will walk an individual through the steps necessary to enable the VMware\Hyper-V licensed feature of Backup Exec 2012. In addition, how to add a VMware server and configure a backup job. The first step is to acquire the necessary licen…
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…

840 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