Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Retrieve user logon events from SCCM WMI
Function Get-CMUserLogonEvents {
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
$ComputerName,
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
$MaximumEvents = 50
)
If ($ComputerName)
{
[array]$LastLogons = Get-WmiObject -ComputerName $ComputerName -Namespace ROOT\CCM -Class CCM_UserLogonEvents | Select -last $MaximumEvents
}
Else
{
[array]$LastLogons = Get-WmiObject -Namespace ROOT\CCM -Class CCM_UserLogonEvents | Select -last $MaximumEvents
}
Foreach ($Logon in $LastLogons)
{
If ($Logon.LogoffTime -ne $null)
{
[pscustomobject]@{
LogonTime = [System.TimeZoneInfo]::ConvertTimeFromUtc(([datetime]::new(1970,01,01,00,00,00,[System.DateTimeKind]::Utc)).AddSeconds($Logon.LogonTime),[System.TimeZoneInfo]::Local)
LogoffTime = [System.TimeZoneInfo]::ConvertTimeFromUtc(([datetime]::new(1970,01,01,00,00,00,[System.DateTimeKind]::Utc)).AddSeconds($Logon.LogoffTime),[System.TimeZoneInfo]::Local)
User = [System.Security.Principal.SecurityIdentifier]::new($Logon.UserSID).Translate([System.Security.Principal.NTAccount]).Value
DurationInHours = [math]::Round([System.TimeSpan]::FromSeconds(($Logon.LogoffTime - $Logon.LogonTime)).TotalHours,2)
}
}
Else
{
[pscustomobject]@{
LogonTime = [System.TimeZoneInfo]::ConvertTimeFromUtc(([datetime]::new(1970,01,01,00,00,00,[System.DateTimeKind]::Utc)).AddSeconds($Logon.LogonTime),[System.TimeZoneInfo]::Local)
LogoffTime = $null
User = [System.Security.Principal.SecurityIdentifier]::new($Logon.UserSID).Translate([System.Security.Principal.NTAccount]).Value
DurationInHours = [math]::Round(((Get-Date) - ([System.TimeZoneInfo]::ConvertTimeFromUtc(([datetime]::new(1970,01,01,00,00,00,[System.DateTimeKind]::Utc)).AddSeconds($Logon.LogonTime),[System.TimeZoneInfo]::Local))).TotalHours,2)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.