windowsbatch-filecommand-linefindstrnet-use

Batch file user's last logon using net user


I'm using net user command in a batch script to find the last login time of a user :

net user administrator | findstr /B /C:"Last logon"

The result looks like this :

Last logon                   04/23/2020 9:02 AM

I would like to display the date and time only and remove Last logon  

How can i achieve this ?

Thanks.


Solution

  • You could optionally use WMI for this task, which should provide you with a date and time string which is universally parseable.

    If you want a specific user:

    @Set "UsersName=Administrator"
    @For /F Tokens^=2^,4Delims^=^" %%G In ('%__AppDir__%wbem\WMIC.exe UserAccount^
     Where "Name='%UsersName%'" Assoc /AssocClass:Win32_NetworkLoginProfile 2^>NUL'
    )Do @For /F %%I In ('%__AppDir__%wbem\WMIC.exe Path Win32_NetworkLoginProfile^
     Where "Name='%%G\\%%H' And LastLogon Is Not Null" Get LastLogon 2^>NUL^
     ^|%__AppDir__%findstr.exe "[0123456789]"')Do @Echo %%H last logon was %%~nI
    @Pause
    

    Alternatively if you want a listing of users:

    @For /F Tokens^=2^,4Delims^=^" %%G In ('%__AppDir__%wbem\WMIC.exe UserAccount^
     Assoc /AssocClass:Win32_NetworkLoginProfile 2^>NUL')Do @For /F %%I In (
        '%__AppDir__%wbem\WMIC.exe Path Win32_NetworkLoginProfile Where^
         "Name='%%G\\%%H' And LastLogon Is Not Null" Get LastLogon 2^>NUL^
         ^|%__AppDir__%findstr.exe "[0123456789]"')Do @Echo %%H last logon was %%~nI
    @Pause
    

    [Edit /?]
    Based upon the question you've asked in comment to another answer, and because I've already indicated that my solution(s) above provide a universally parseable date and time format, you can further adapt it to output only the hour.

    For example:

    @For /F Tokens^=2^,4Delims^=^" %%G In ('%__AppDir__%wbem\WMIC.exe UserAccount^
     Assoc /AssocClass:Win32_NetworkLoginProfile 2^>NUL')Do @For /F %%I In (
        '%__AppDir__%wbem\WMIC.exe Path Win32_NetworkLoginProfile Where^
         "Name='%%G\\%%H' And LastLogon Is Not Null" Get LastLogon 2^>NUL^
         ^|%__AppDir__%findstr.exe "[0123456789]"')Do @(Set "YYYYmmDDHHMMSS=%%~nI"
         Call Echo(%%H last logged in during the hour of %%YYYYmmDDHHMMSS:~-6,2%%:00)
    @Pause
    

    Of course, this does not identify on which day that logon occurred, but your additional requirement was specific!