Greg`s Tech blog

Processing Object Properties in the PowerShell Pipeline

Sunday 21 of October, 2012
I was running a quick AD query via Powershell today and needed to export the results to a csv. The results contained two fields (lastLogonTimestamp and pwdLastSet) that are not human readable, but I needed them to be. There is a quick transform you can make on these field to convert them to a datetime value. It is simply:
Convert system time to datetime

That part is easy, but how do we do that in the pipeline so all the objects get converted before the export? To do so, we can create a calculated field using a specially crafted hash-table to describe the members to Select-Object. So this:

Select 'before'
select name, description, distinguishedname,pwdlastset,lastLogonTimestamp

Select after
select name, description, distinguishedname,@{LABEL='pwdlastset';EXPRESSION={[datetime]::FromFileTimeUTC($_.pwdlastset)}},@{LABEL='lastLogonTimestamp';EXPRESSION={[datetime]::FromFileTimeUTC($_.lastLogonTimestamp)}}

Looking a bit more in-depth, the pwdLastSet was modified to specify the column LABEL and the EXPRESSION in an array, with the EXPRESSION now set to the new, calculated value.

in case you are wondering, my full, one-liner, is a report on all disabled accounts in our directory

Get-Disabled Accounts
Get-ADUser -LDAPFilter {(useraccountcontrol:1.2.840.113556.1.4.803:=2)} -properties pwdlastset,lastLogonTimestamp,description| select name, description, distinguishedname,@{LABEL='pwdlastset';EXPRESSION={[datetime]::FromFileTimeUTC($_.pwdlastset)}},@{LABEL='lastLogonTimestamp';EXPRESSION={[datetime]::FromFileTimeUTC($_.lastLogonTimestamp)}}|export-csv d:\data\disabled_accts.csv -notypeinformation