1

I create a script that shows me a list of users starting with letter A. Now I want to export them to a CSV file with columns named full name, username, creation date.

The following exports the desired column values, but doesn't have the column names (headers) that I want.

Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} | 
  Select-Object name, SamAccountName, whenCreated | 
    export-csv -path c:\userexport.csv
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Can you show what you want the CSV file to look like? Including the header record and at least one dummy data record. – Walter Mitty Mar 02 '20 at 12:03
  • As an aside: While seductively convenient, it's best to [avoid the use of script blocks (`{ ... }`) as `-Filter` arguments](https://stackoverflow.com/a/44184818/45375). – mklement0 Mar 02 '20 at 16:26
  • As Vad's answer shows, properties can be renamed via [calculated properties](https://stackoverflow.com/a/39861920/45375). – mklement0 Mar 02 '20 at 16:28

1 Answers1

4

Rename output properties like this:

Get-ADUser -Properties whenCreated -Filter {samaccountname -like 'A*'} | 
  Select-Object @{n='FullName';e={$_.Name}},@{n='Login';e={$_.SamaccountName}},@{n='When was Created';e={$_.WhenCreated}} |
    Export-Csv -path c:\userexport.csv -NoTypeInformation -Delimiter ';' -Encoding UTF8

To later read in the resulting CSV filter and filter chronologically by the When was Created column, as requested in a follow-up question in the comments:

Import-Csv -Path D:\testdir\userexport.csv -Delimiter ';' |
  Where-Object {[datetime]::parseexact($_.'When was Created','dd/MM/yyyy HH:mm:ss',$null) -le (Get-Date).AddYears(-2)} |
    Select-Object FullName
mklement0
  • 382,024
  • 64
  • 607
  • 775
Vad
  • 693
  • 3
  • 13
  • Question, Now do I need to import the file and output anyone who works over two years just his full name how do I do it? i think that i need start the script Import-Csv -Path C:\userexport.csv – nadav shlomo Mar 02 '20 at 12:57
  • 1
    Please don't use the curly brackets in the Filter. That parameter should be a **string**, not a script block. Write `-Filter "samaccountname -like 'A*'"` instead. Also add the `-NoTypeInformation` switch to the Export-Csv cmdlet. – Theo Mar 02 '20 at 14:36
  • Nice; aside from @Theo's comment it's also worth noting that you don't need a script block if _renaming_ is the only thing the calculated property does - the _name_ of the input property as a _string_ will do; e.g., `@{n='FullName';e={$_.Name}}` can be simplified to `@{n='FullName';e='Name'}` – mklement0 Mar 02 '20 at 17:00
  • 1
    @nadavshlomo Please do not ask a new question as comment to an answer of your original question. – Theo Mar 02 '20 at 19:19