SeattleITguy
SeattleITguy

Reputation: 25

Extracting only date portion from LastLogonDate

I want to be able to isolate the date from the output of this Get-ADUser command:

Get-ADUser -identity johnd -properties LastLogonDate | Select-Object name, LastLogonDate

Which results in this:

name                                                        LastLogonDate
----                                                        -------------
John Doe                                                3/21/2016 10:01:36 AM

I want to be able to strip all the text and be left with only the date:

3/21/2016

I've tried adding this split filter to the end of the above command, which is similar to awk in unix. (#2 is off, just for example)

%{ $_.Split(',')[2]; }

Which results in this error:

[Microsoft.ActiveDirectory.Management.ADUser] doesn't contain a method named 'Split'

Upvotes: 2

Views: 15115

Answers (3)

Nikolay
Nikolay

Reputation: 21

I'ts hard way, more seamply way is:

Get-ADUser -SearchBase 'OU=Users,OU=Home,DC=Domain,DC=local' -filter {Enabled -eq $True} -Properties * | 
ForEach-Object {$_.whenChanged.ToShortDateString() + ',' + $_.SamAccountName}

Upvotes: 0

LinuxDisciple
LinuxDisciple

Reputation: 2379

Can you use variables? If so,

PS>$hi=Get-ADuser -identity johnd -properties LastLogonDate|select-object name,LastLogonDate
PS>$hi.LastLogonDate.ToShortDateString()
3/21/2016
PS>$hi.name
John Doe

Upvotes: 1

briantist
briantist

Reputation: 47832

The result of that cmdlet is an object with a set of properties. The output you see in table format is not what is literally contained in the object; it's a display representation of it.

So to first get the date object only, you can modify your Select-Object call (which is already paring down the properties) like this:

$lastLogon = Get-ADUser -identity johnd -properties LastLogonDate | 
    Select-Object -ExpandProperty LastLogonDate

$lastLogon now contains a [DateTime] object.

With that you can format it using format strings:

$lastLogon.ToString('MM/dd/yyyy')

Or even better:

$lastLogon.ToShortDateString()

(these are slightly different representations; the latter doesn't zero-pad).

The format strings give you complete control over the representation.

Upvotes: 7

Related Questions