0
votes

I have a powershell script that is supposed to export AD users created after a specified date and it used to work, but suddenly it has been giving me problems so I have been trying to rework it with no success. Any help would be greatly appreciated. Original code

Get-ADUser -Filter {whencreated -gt $start} -Properties Whencreated | where enabled -eq $true | select SamAccountName, whenCreated,@{n='OU';e={$_.DistinguishedName.Split(',')[1].replace('OU=','')}} | Sort whenCreated -Descending SamAccountName | export-csv $env:TEMP\ADUsers.csv -NoTypeInformation

New code

Get-ADUser -Filter * -Property SamAccountName, whenCreated | Where {$_.whenCreated -gt $start} | where enabled -eq $true | FT SamAccountName, whenCreated,@{n='OU';e={$_.DistinguishedName.Split(',')[1].replace('OU=','')}} | export-csv $env:TEMP\ADUsers.csv

Which the new code works perfectly until I add | export-csv $env:TEMP\ADUsers.csv -NoTypeInformation which the result in the CSV looks like

ClassId2e4f51ef21dd47e99d3c952918aff9cd pageHeaderEntry pageFooterEntry autosizeInfo shapeInfo groupingEntry 033ecb2bc07a4d43b5ef94ed5a35d280 Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo
9e210fe47d09416682b841769c78b8a3
27c87ef9bbda4f709f6b4002fa4af63c

1
Replace FT with Select-Object - Mathias R. Jessen

1 Answers

0
votes

The issue is the FT in there. That's short for Format-Table, and is intended to format data for display. You should never pipe any Format-* command to other things, or capture them in a variable.

Change that FT to Select and you'll be all set.

Get-ADUser -Filter * -Property SamAccountName, whenCreated | 
    Where {$_.whenCreated -gt $start -and $_.enabled} | 
    Select SamAccountName, whenCreated,@{n='OU';e={$_.DistinguishedName.Split(',')[1].replace('OU=','')}} | 
    export-csv $env:TEMP\ADUsers.csv -NoType

Though you'll get much faster results filtering at the Get-ADUser level, not getting all results and then filtering afterwards.

Get-ADUser -Filter "whenCreated -gt $start -and enabled -eq $true" | 
    Select SamAccountName, whenCreated,@{n='OU';e={$_.DistinguishedName.Split(',')[1].replace('OU=','')}} | 
    export-csv $env:TEMP\ADUsers.csv -NoType