Help
Help

Reputation: 181

PowerShell 2 - How To View User Accounts That Have Been Inactive For 90 Days

I am limited to PowerShell Version 2.

I am trying to list out user accounts that have not logged in for more than 90 days.

I have been trying to craft the command for this but have failed, so far I have managed to craft the following:

Get-WmiObject Win32_UserAccount -Filter "LocalAccount=True" | Where-Object { (New-Timespan -Start $_.LastLogon -End (Get-Date)).Days -ge 90 }

Can you please help me? :)

Upvotes: 0

Views: 880

Answers (1)

Theo
Theo

Reputation: 61068

For PowerShell version 2, you could use Adsi like below:

function Get-LocalUsers {
    Param([string]$ComputerName=$env:COMPUTERNAME)

    [ADSI]$computer="WinNT://$ComputerName"

    $computer.PsBase.Children | Where-Object {$_.SchemaClassName -match "user"} |
    Select-Object @{Name="ComputerName"; Expression={$computer.Name}},
                  @{Name="User"; Expression={$_.PsBase.Properties.Name.Value}},
                  @{Name="Description"; Expression={$_.PsBase.Properties.Description.Value}},
                  @{Name="Disabled"; Expression={[bool]($_.PsBase.Properties.Item("userflags").Value -band 2)}},
                  @{Name="LastLogin"; Expression={ if ($_.PsBase.Properties.LastLogin.Value) {
                                                        [datetime]$_.PsBase.Properties.LastLogin.Value
                                                   } else { "Never" }}}
}

# set the date to compare against to midnight using '.Date'
$refDate = (Get-Date).AddDays(-90).Date
Get-LocalUsers | Where-Object { $_.LastLogin -eq 'Never' -or $_.LastLogin -lt $refDate }

Upvotes: 1

Related Questions