locked
Script to pull out last logon date RRS feed

  • Question

  • Hello,

    I have a list of user that I would like to pull out last logon date from AD.

    This is the script I am using at the moment but it produces blanks and I don't know what the blanks mean.

    Import-Module ActiveDirectory
    #This script requires PowerShell AD Module
    #
    Import-csv "c:\scripts\samaccountname.csv" |
    foreach-object {get-aduser $_.samaccountname -Properties lastlogondate} |
    select name,Lastlogondate |
    Export-csv c:\scripts\LastLogon.csv -NoTypeInformation

    Please can you help?


    Kind Regards, PenDraKon

    • Moved by Bill_Stewart Tuesday, July 15, 2014 8:58 PM This is not "train me in all details" forum
    Thursday, May 22, 2014 9:50 AM

All replies

  • Script looks alright, can you try getting the output for a single user first and then try using .csv file

    Prajwal Desai, http://prajwaldesai.com

    Thursday, May 22, 2014 9:59 AM
  • Hi Prajwal,

    It does produce an output but some users have a blank login time where as others have a login time.

    What do I need to do to correct this please?


    Kind Regards, PenDraKon

    Thursday, May 22, 2014 10:01 AM
  • Hi Prajwal,

    It does produce an output but some users have a blank login time where as others have a login time.

    What do I need to do to correct this please?


    Kind Regards, PenDraKon


    That is the way it works.  That value is not set on all DCs. Look in repository for scripts which do this correctly There are dozens.

    ¯\_(ツ)_/¯

    Thursday, May 22, 2014 10:16 AM
  • Hello,

    How do I take this script:

    $searcher = New-Object DirectoryServices.DirectorySearcher([adsi]"")
    $searcher.filter = "(objectclass=user)"
    $users = $searcher.findall()
     
    Foreach($user in $users)
    {
     if($user.properties.item("lastLogon") -ne 0)
      {
       $a = [datetime]::FromFileTime([int64]::Parse($user.properties.item("lastLogon")))
       "$($user.properties.item(`"name`")) $a"
      }
    }

    and customize it so it works with a list of specific users that I have please?


    Kind Regards, PenDraKon

    Thursday, May 22, 2014 10:29 AM
  • There's a lot of potential routes you can follow up on. One thing that would make life a lot easier is to use the code tool, which formats things nicely.

    $searcher = New-Object DirectoryServices.DirectorySearcher([adsi]"") 
    $searcher.filter = "(objectclass=user)" 
    $users = $searcher.findall() 
     
     Foreach($user in $users) 
    { 
     if($user.properties.item("lastLogon") -ne 0) 
      { 
       $a = [datetime]::FromFileTime([int64]::Parse($user.properties.item("lastLogon")))
        "$($user.properties.item(`"name`")) $a" 
      } 
    }

    The easiest two options include;

    specifying a username in the filter command and putting that in a loop that operates on your list of users.

    Taking the entire result set you have at the moment and then checking each of them in the foreach loop to see if they match one of the names in your list of users.

    As jrv says there's probably a lot of scripts around that already do that if you search.


    Thursday, May 22, 2014 10:57 AM
  • If you want an accurate lastLogon date, you have to check across domain controllers.

    Here's an advanced function I created a while ago for this.

    Function Get-LastLogon {
        <#
        .SYNOPSIS
        Returns LastLogon information
        .DESCRIPTION
        Queries the LastLogin information for a user across domain controllers and returns the highest (latest) value
        .EXAMPLE
        Get-LastLogon User
        .EXAMPLE
        Get-LastLogon -Identity User
        .EXAMPLE
        Get-ADUser User | Get-LastLogon
        .EXAMPLE
        Get-LastLogon User1, User2
        .PARAMETER users
        List of users - pipeline can be used
        #>
        
        [CmdletBinding()]
        param
        (
        [Parameter(Position= 0,
                    Mandatory=$True,
                        ValueFromPipeline=$True,
                            HelpMessage='What user would you like to find the last logon for?')]
        $identity
    	)
        
        Begin {}
        
        Process {
        
            Foreach ($account in $identity) {
        
                $dateStamp = $null
                $domainController =$null
    
                Get-ADDomainController -Filter * | Foreach {
    
                    $dc = $_.HostName
                    
                    $lastLogon = (Get-ADUser $account -Properties LastLogon -server $dc | Select-Object Name,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}).Lastlogon
                    
                    If ($dateStamp -le $lastlogon)
                        {
                        $dateStamp = $lastlogon
                        $domainController = $dc
                        }
                    
                } # End of ForEach
            
                $properties = @{
                Name=$account;
                LastLogon=$dateStamp;
                DomainController=$domainController}
            
                New-Object -TypeName PSObject -Prop $properties
            
            } # End of ForEach
    
        } # End of Process
            
        End {}          
                
    } # End of Function

    You can then run...

    Import-CSV ".\samaccountname.csv" | % {Get-LastLogon $_.samaccountname}

    or...

    Import-CSV ".\samaccountname.csv" | % {Get-LastLogon $_.samaccountname} | Export-CSV ".\report.csv" -noType

    Thursday, May 22, 2014 11:23 AM
  • The solution will not help as the lastlogin is per-DC and many users will not have logged in on the DC being queried.

    Here is how we do that in PowerShell. No need for all of the long setup.  PowerShell and dotnet are defaulted to this.  The filter also needs to be different.

    $searcher=[adsisearcher]'(&(objectclass=user)(objectcategory=person))'
    $searcher.findall() |
         ForEach-Object{
              Try{
                   $ll=[datetime]::FromFileTime([int64]::Parse($_.properties['lastLogon']))
              }
              Catch{}
              New-Object PsObject -Property @{Name=$_.Properties['name'][0];LastLogon=$ll}
        } 
    

    Using try/catch avoids certain other issues.

    Use the scripts in the repository as  they scan all DCs for latest logon.


    ¯\_(ツ)_/¯


    • Edited by jrv Thursday, May 22, 2014 11:26 AM
    Thursday, May 22, 2014 11:25 AM
  • Hello,

    I have searched around for 2 days and found nothing. Where do you surgest searching.


    Kind Regards, PenDraKon

    Thursday, May 22, 2014 11:46 AM
  • Hello,

    I am not used to functions. How do I use it to get the results I need please?


    Kind Regards, PenDraKon

    Thursday, May 22, 2014 11:57 AM
  • Hello,

    I am not used to functions. How do I use it to get the results I need please?


    Kind Regards, PenDraKon

    You should try searching for answers before asking.  It will save you a lot of time:

    http://www.powershellpro.com/powershell-tutorial-introduction/powershell-functions-filters/

    Learning PowerShell is up to you. You will not get far here or in other forums if you have not spent the time to learn.

    http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx


    ¯\_(ツ)_/¯

    Thursday, May 22, 2014 12:05 PM
  • Hello,

    Still not sure about functions. All I want to do is read in a list of users from a csv file and then check when they lasted logged in.

    Please can someone help?


    Kind Regards, PenDraKon

    Thursday, May 22, 2014 12:38 PM
  • Hello,

    Still not sure about functions. All I want to do is read in a list of users from a csv file and then check when they lasted logged in.

    Please can someone help?


    Kind Regards, PenDraKon

    Did you even look in the repository.

    This forum is for technicians and not for free scripting for end users.  If you are not interested in learning scripting then you will want to call a consultant.

    The original question  you asked has been answered more than once.  If you cannot understand how to use the examples or how to read the learning material then please contact a consultant to help you.


    ¯\_(ツ)_/¯

    Thursday, May 22, 2014 12:47 PM
  • Hello,

    Still not sure about functions. All I want to do is read in a list of users from a csv file and then check when they lasted logged in.

    Please can someone help?


    Kind Regards, PenDraKon

    Have you tried the function and commands I posted?

    You can't just pull a list of users from a CSV file and then check the last logged in date.  The information isn't synched across the domain controllers.  (There are a ton of articles which explain this in depth).

    Thursday, May 22, 2014 12:47 PM
  • Hello Newbie Jones,

    I cannot get the function to work.


    Kind Regards, PenDraKon

    Thursday, May 22, 2014 1:06 PM
  • It is always helpful if you post the error message you get when you try to run the script. :)
    Thursday, May 22, 2014 1:09 PM
  • I cannot get the function to work.

    And what exactly does that mean?

    Are you absolutely sure these users have ever logged in anyway?


    Don't retire TechNet! - (Don't give up yet - 12,830+ strong and growing)

    Thursday, May 22, 2014 1:11 PM
  • Hello Mike,

    I get this error:

    The term 'Get-LastLogon' is not recognized as the name of a cmdlet, function, script file, or operable program. Check t
    he spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:62
    + Import-CSV "c:\scripts\samaccountname.csv" | % {Get-LastLogon <<<<  $_.samaccountname} | Export-CSV "c:\scripts\repor
    t.csv" -noType
        + CategoryInfo          : ObjectNotFound: (Get-LastLogon:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException

    Please can you help?


    Kind Regards, PenDraKon

    Thursday, May 22, 2014 1:17 PM
  • I posted this: http://www.powershellpro.com/powershell-tutorial-introduction/powershell-functions-filters/

    If you are too lazy to read how to use a function thenwe cannot help you.

    Please hire someone to show you how to use this.


    ¯\_(ツ)_/¯

    Thursday, May 22, 2014 1:27 PM
  • Hello,

    I have read the artical but I do not understand what to do.

    Please can you help?


    Kind Regards, PenDraKon

    Thursday, May 22, 2014 1:42 PM
  • Hello,

    I have read the artical but I do not understand what to do.

    Please can you help?


    Kind Regards, PenDraKon

    Try all of the examples until you understand.  If you cannot understand that then go to the learning link I posted and start learning the basics of PowerShell.  We cannot operate your keyboard for you.


    ¯\_(ツ)_/¯

    Thursday, May 22, 2014 2:07 PM
  • Hello,

    I have read the artical but I do not understand what to do.

    Please can you help?


    Kind Regards, PenDraKon

    The function posted has a complete set of examples and help built in.

    I think the issue is that you are not a WIndows technician and not really a user except for possibly being an office user.

    Why is it that you think you need to know the lastlogon dates?  They are not of much use to anyone but a technician.  IS this something your boss asked you to do because you do not have an Admin on site?  If so you might note to your boss that he is asking a lot of an untrained person. Perhaps he does not know how this is not a built in item.


    ¯\_(ツ)_/¯

    Thursday, May 22, 2014 2:29 PM
  • jrv,

    I am a technical Architect. I am clearing down some of out exchange servers to free up some space. I now have a script and it works no thanks to you.

    I would not call this a site when you can get assistance more a site where people poke fun at others for trying to learn.

    Once you have grown up I might talk to you.


    Kind Regards, PenDraKon

    What is a technical architect?  You still do not know how to use Windows or how to use a script. And you do not try to read both the explicit help in the function and the help I posted which clearly tells you  how to use a function.  What else is there?

    You demand help with things that none of us can answer because we cannot see what you are typing. You just keep saying you need some kind of help.  YOu didn't say what you tried.  YOu posted a line that clearly showed that you had not used the function.     How did you load the function?  You didn't.  The link explained how to do that.

    We do not write scripts and it is very hard to answer questions asked by people who are not trained in computers beyond A+ or helpdesk.  Technicians, at least, need to know how to ask questions.

    This is not a support forum.  It is a forum for technicians and for those attempting to learn scripting.  There are numerous support options for Microsoft products.  If you are not a trained technician then you should make a support call or contact a consultant.

    The first option I offered was to look in the repository. You refused to even try that.  I know there are scripts in there because I have posted them before.  They take a file of user names and return dates.  I stil ldon't see why you are so lazy that you cannot even look at a set of scripts that are recommended.

    I suspect you are not used to technical forums and are not versed in any Windows technology.  I recommend getting some extensive training in a technology.  There is no way to wear the hat of a computer system architect without a good amount of knowledge of computers and how they work.


    ¯\_(ツ)_/¯

    Thursday, May 22, 2014 3:11 PM