<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>powershell script to get last logon user on computer Archives - the Sysadmin Channel</title>
	<atom:link href="https://thesysadminchannel.com/tag/powershell-script-to-get-last-logon-user-on-computer/feed/" rel="self" type="application/rss+xml" />
	<link>https://thesysadminchannel.com/tag/powershell-script-to-get-last-logon-user-on-computer/</link>
	<description>Documenting My Life as a System Administrator</description>
	<lastBuildDate>Thu, 18 Mar 2021 01:28:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
<site xmlns="com-wordpress:feed-additions:1">144174110</site>	<item>
		<title>Get Computer Last Login Information Using Powershell</title>
		<link>https://thesysadminchannel.com/get-computer-last-login-information-using-powershell/</link>
					<comments>https://thesysadminchannel.com/get-computer-last-login-information-using-powershell/#comments</comments>
		
		<dc:creator><![CDATA[Paul Contreras]]></dc:creator>
		<pubDate>Tue, 16 Mar 2021 18:41:15 +0000</pubDate>
				<category><![CDATA[Powershell]]></category>
		<category><![CDATA[Get Computer Last Login Information Using Powershell]]></category>
		<category><![CDATA[powershell get last logged on user remote computer]]></category>
		<category><![CDATA[powershell last logon user computer]]></category>
		<category><![CDATA[powershell script to get last logon user on computer]]></category>
		<guid isPermaLink="false">https://thesysadminchannel.com/?p=3054</guid>

					<description><![CDATA[<p>I recall back in the days of Windows Server 2000 where it was the norm to see the last user that logged into a machine. Whilst that option is still available using group policy, I wanted to get a timestamp&#8230; <a href="https://thesysadminchannel.com/get-computer-last-login-information-using-powershell/" class="more-link">Continue Reading <span class="meta-nav">&#8594;</span></a></p>
<p>The post <a href="https://thesysadminchannel.com/get-computer-last-login-information-using-powershell/">Get Computer Last Login Information Using Powershell</a> appeared first on <a href="https://thesysadminchannel.com">the Sysadmin Channel</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I recall back in the days of Windows Server 2000 where it was the norm to see the last user that logged into a machine.  Whilst that option is still available using group policy, I wanted to get a timestamp of a machine&#8217;s login history using Powershell in order to get more information on what&#8217;s happening.  Furthermore, I wanted to share <strong>get computer last login information using Powershell</strong>.</p>
<p>I should explicitly note that this script is not the same as the <a href="https://thesysadminchannel.com/get-last-logon-date-for-all-users-in-your-domain/" rel="noopener" target="_blank">Get Last Logon Date For All Users in Your Domain</a>.  That script checks Active Directory for last login information, while this script specifically checks a local or remote computer&#8217;s last login info.  With that said, the machine you want to query must be online since we&#8217;re going to be checking the event logs to get this data.</p>
<h2>Script Prerequisites</h2>
<p>This script uses the machine&#8217;s Event Security log so you will need run with Administrator rights.  This is built-in to the function using the #requires -RunasAdministrator.</p>
<h2>Powershell Parameters</h2>
<p>I thought it would be helpful to get as much useful data so I added several useful parameters. Let&#8217;s go over them now.</p>
<h3>    -ComputerName</h3>
<p>Description: By default this will use the local computer, but you can specify other computers in a comma separated format or through an array variable.</p>
<h3>    -SamAccountName</h3>
<p>Description: This will only output the SamAccountName that you specified.  All other users would be excluded and cannot be used with ExcludeSamAccountName</p>
<h3>    -ExcludeSamAccountName</h3>
<p>Description: This will exclude the SamAccountName that you specified.  All other users would be displayed and cannot be used with SamAccountName</p>
<h3>    -LoginEvent</h3>
<p>Description: This will filter which event types you would like to display.  Only one option can be selected and the only valid options are &#8216;SuccessfulLogin&#8217;, &#8216;FailedLogin&#8217;, &#8216;Logoff&#8217;, &#8216;DisconnectFromRDP&#8217;.  If a value is not specified, it will default to &#8216;SuccessfulLogin&#8217;</p>
<h3>    -DaysFromToday</h3>
<p>Description: This will query how many days back you would like to search for.  The default is 3 days.</p>
<h3>    -MaxEvents</h3>
<p>Description: This will set the maximum number of events to display.</p>
<h3>    -Credential</h3>
<p>Description: Allow other credentials to be used for remote machines.</p>
<p>&nbsp;</p>
<h2>Get Computer Last Login Information Using Powershell</h2>
<pre class="brush: powershell; title: ; notranslate">

Function Get-LastLoginInfo {
#requires -RunAsAdministrator
&lt;#
.Synopsis
    This will get a Information on the last users who logged into a machine.
    More info can be found: https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/basic-audit-logon-events


.NOTES
    Name: Get-LastLoginInfo
    Author: theSysadminChannel
    Version: 1.0
    DateCreated: 2020-Nov-27


.EXAMPLE
    Get-LastLoginInfo -ComputerName Server01, Server02, PC03 -SamAccountName username

.LINK
    https://thesysadminchannel.com/get-computer-last-login-information-using-powershell -
#&gt;


    [CmdletBinding(DefaultParameterSetName=&quot;Default&quot;)]
    param(
        [Parameter(
            Mandatory = $false,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true,
            Position = 0
        )]
        [string[]]  $ComputerName = $env:COMPUTERNAME,


        [Parameter(
            Position = 1,
            Mandatory = $false,
            ParameterSetName = &quot;Include&quot;
        )]
        [string]    $SamAccountName,


        [Parameter(
            Position = 1,
            Mandatory = $false,
            ParameterSetName = &quot;Exclude&quot;
        )]
        [string]    $ExcludeSamAccountName,


        [Parameter(
            Mandatory = $false
        )]
        [ValidateSet(&quot;SuccessfulLogin&quot;, &quot;FailedLogin&quot;, &quot;Logoff&quot;, &quot;DisconnectFromRDP&quot;)]
        [string]    $LoginEvent = &quot;SuccessfulLogin&quot;,


        [Parameter(
            Mandatory = $false
        )]
        [int]       $DaysFromToday = 3,


        [Parameter(
            Mandatory = $false
        )]
        [int]       $MaxEvents = 1024,


        [System.Management.Automation.PSCredential]
        $Credential
    )


    BEGIN {
        $StartDate = (Get-Date).AddDays(-$DaysFromToday)
        Switch ($LoginEvent) {
            SuccessfulLogin   {$EventID = 4624}
            FailedLogin       {$EventID = 4625}
            Logoff            {$EventID = 4647}
            DisconnectFromRDP {$EventID = 4779}
        }
    }

    PROCESS {
        foreach ($Computer in $ComputerName) {
            try {
                $Computer = $Computer.ToUpper()
                $Time = &quot;{0:F0}&quot; -f (New-TimeSpan -Start $StartDate -End (Get-Date) | Select -ExpandProperty TotalMilliseconds) -as [int64]

                if ($PSBoundParameters.ContainsKey(&quot;SamAccountName&quot;)) {
                    $EventData = &quot;
                        *[EventData[
                                Data[@Name='TargetUserName'] != 'SYSTEM' and
                                Data[@Name='TargetUserName'] != '$($Computer)$' and
                                Data[@Name='TargetUserName'] = '$($SamAccountName)'
                            ]
                        ]
                    &quot;
                }

                if ($PSBoundParameters.ContainsKey(&quot;ExcludeSamAccountName&quot;)) {
                    $EventData = &quot;
                        *[EventData[
                                Data[@Name='TargetUserName'] != 'SYSTEM' and
                                Data[@Name='TargetUserName'] != '$($Computer)$' and
                                Data[@Name='TargetUserName'] != '$($ExcludeSamAccountName)'
                            ]
                        ]
                    &quot;
                }

                if ((-not $PSBoundParameters.ContainsKey(&quot;SamAccountName&quot;)) -and (-not $PSBoundParameters.ContainsKey(&quot;ExcludeSamAccountName&quot;))) {
                    $EventData = &quot;
                        *[EventData[
                                Data[@Name='TargetUserName'] != 'SYSTEM' and
                                Data[@Name='TargetUserName'] != '$($Computer)$'
                            ]
                        ]
                    &quot;
                }

                $Filter = @&quot;
                    &lt;QueryList&gt;
                        &lt;Query Id=&quot;0&quot;&gt;
                            &lt;Select Path=&quot;Security&quot;&gt;
                            *[System[
                                    Provider[@Name='Microsoft-Windows-Security-Auditing'] and
                                    EventID=$EventID and
                                    TimeCreated[timediff(@SystemTime) &amp;lt;= $($Time)]
                                ]
                            ]
                            and
                                $EventData
                            &lt;/Select&gt;
                        &lt;/Query&gt;
                    &lt;/QueryList&gt;
&quot;@

                if ($PSBoundParameters.ContainsKey(&quot;Credential&quot;)) {
                    $EventLogList = Get-WinEvent -ComputerName $Computer -FilterXml $Filter -Credential $Credential -ErrorAction Stop
                  } else {
                    $EventLogList = Get-WinEvent -ComputerName $Computer -FilterXml $Filter -ErrorAction Stop
                }


                $Output = foreach ($Log in $EventLogList) {
                    #Removing seconds and milliseconds from timestamp as this is allow duplicate entries to be displayed
                    $TimeStamp = $Log.timeCReated.ToString('MM/dd/yyyy hh:mm tt') -as [DateTime]

                    switch ($Log.Properties[8].Value) {
                        2  {$LoginType = 'Interactive'}
                        3  {$LoginType = 'Network'}
                        4  {$LoginType = 'Batch'}
                        5  {$LoginType = 'Service'}
                        7  {$LoginType = 'Unlock'}
                        8  {$LoginType = 'NetworkCleartext'}
                        9  {$LoginType = 'NewCredentials'}
                        10 {$LoginType = 'RemoteInteractive'}
                        11 {$LoginType = 'CachedInteractive'}
                    }

                    if ($LoginEvent -eq 'FailedLogin') {
                        $LoginType = 'FailedLogin'
                    }

                    if ($LoginEvent -eq 'DisconnectFromRDP') {
                        $LoginType = 'DisconnectFromRDP'
                    }

                    if ($LoginEvent -eq 'Logoff') {
                        $LoginType = 'Logoff'
                        $UserName = $Log.Properties[1].Value.toLower()
                    } else {
                        $UserName = $Log.Properties[5].Value.toLower()
                    }


                    [PSCustomObject]@{
                        ComputerName = $Computer
                        TimeStamp    = $TimeStamp
                        UserName     = $UserName
                        LoginType    = $LoginType
                    }
                }

                #Because of duplicate items, we'll append another select object to grab only unique objects
                $Output | select ComputerName, TimeStamp, UserName, LoginType -Unique | select -First $MaxEvents

            } catch {
                Write-Error $_.Exception.Message

            }
        }
    }

    END {}
}

</pre>
<p>&nbsp;<br />
Now let&#8217;s see what kind of output we get when we run this script on a remote computer.  This may take some time depending on the speed of the remote machine. While you have the ability to do more than one at a time but I would probably recommend only doing one a time because these are pretty noisy.</p>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2021/03/Last-Login-Info.png" target="_blank" rel="noopener"><img fetchpriority="high" decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2021/03/Last-Login-Info.png" alt="Computer Last Login Information" width="900" height="340" class="aligncenter size-full wp-image-3061" srcset="https://thesysadminchannel.com/wp-content/uploads/2021/03/Last-Login-Info.png?v=1616029010 900w, https://thesysadminchannel.com/wp-content/uploads/2021/03/Last-Login-Info-768x290.png?v=1616029010 768w" sizes="(max-width: 900px) 100vw, 900px" /></a></p>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2021/03/Last-Login-Info-samaccountname.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2021/03/Last-Login-Info-samaccountname.png" alt="Computer Last Login Information - samaccountname" width="921" height="387" class="aligncenter size-full wp-image-3062" srcset="https://thesysadminchannel.com/wp-content/uploads/2021/03/Last-Login-Info-samaccountname.png?v=1616029047 921w, https://thesysadminchannel.com/wp-content/uploads/2021/03/Last-Login-Info-samaccountname-768x323.png?v=1616029047 768w" sizes="(max-width: 921px) 100vw, 921px" /></a></p>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2021/03/Get-Last-Login-Info-Failed-Logins.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2021/03/Get-Last-Login-Info-Failed-Logins.png" alt="Computer Last Login Information - Failed Logins" width="900" height="340" class="aligncenter size-full wp-image-3063" srcset="https://thesysadminchannel.com/wp-content/uploads/2021/03/Get-Last-Login-Info-Failed-Logins.png?v=1616029069 900w, https://thesysadminchannel.com/wp-content/uploads/2021/03/Get-Last-Login-Info-Failed-Logins-768x290.png?v=1616029069 768w" sizes="(max-width: 900px) 100vw, 900px" /></a></p>
<p>One item I would eventually want to fix is to consolidate the items that are created at the same time.  Currently there is one entry for each individual event but that would take a bit more time and logic to construct.</p>
<p>&nbsp;<br />
Anwway, I hope you were able to find use in our Powershell script to get last logon user on computers. There are a ton of creative use cases and luckily the foundational code is available to use.  Be sure to check out our own <a href="https://thesysadminchannel.com/powershell/" rel="noopener" target="_blank">Powershell gallery</a> for useful, real world scripts.  Finally, don&#8217;t forget to check out our <a href="https://www.youtube.com/c/theSysadminChannel" rel="noopener" target="_blank">YouTube Channel</a> where we post sysadmin content in video form.  This get computer last login information using Powershell function has come in handy from time to time and wanted to share.</p>
<p>The post <a href="https://thesysadminchannel.com/get-computer-last-login-information-using-powershell/">Get Computer Last Login Information Using Powershell</a> appeared first on <a href="https://thesysadminchannel.com">the Sysadmin Channel</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://thesysadminchannel.com/get-computer-last-login-information-using-powershell/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3054</post-id>	</item>
	</channel>
</rss>
