function Get-AllUsersNotLoggedInSince { [CmdLetBinding()] [OutputType([object[]])] param( [Parameter()] [ValidateNotNullOrEmpty()] [DateTime]$LastLoginDate = [DateTime]::Now.AddMonths(-3) ) $userLookup = @() $domainControllerLookup = @{} # aka not a system account, like LOCALSYSTEM or NETWORKSERVICE $isUser = 1 # aka not IIS services $passwordCannotChange = 64 # aka not gMSA $workstationTrustAccount = 4096 # aka not local accounts for things like machine recovery $passwordDoesNotExpire = 65536 $allLoginProfiles = Get-CimInstance -ClassName Win32_NetworkLoginProfile $users = $allLoginProfiles.Where({ ($_.Flags -band $isUser) -and -not ($_.Flags -band $passwordCannotChange) -and -not ($_.Flags -band $workstationTrustAccount) -and -not ($_.Flags -band $passwordDoesNotExpire) }) foreach ($user in $users) { $domain = ($user.Name -split '\\')[0] $username = ($user.Name -split '\\')[1] $server = $domainControllerLookup.$domain if ($null -eq $server) { $server = (Get-ADDomainController -Discover -DomainName $domain).Hostname[0] $domainControllerLookup.$domain = $server } $domainUser = Get-ADUser -Server $server -Identity $username if ($null -ne $domainUser) { # calculate directory size $homeDirectoryPath = Join-Path -Path C:\Users\ -ChildPath $username $sizeInMbs = [System.Math]::Round( ((Get-ChildItem -Path $homeDirectoryPath -Recurse -ErrorAction SilentlyContinue -Force) | Measure-Object -Property Length -Sum).Sum / 1Mb, 2) if ($user.LastLogon -lt $LastLoginDate) { $userLookup += @{ Username = $user.Name LastLogon = $user.LastLogon HomeFolderMB = $sizeInMbs } } } else { Write-Host "Could not find $($user.Caption) in $domain" } } return $userLookup }