Search code examples
powershellcsvexport-csv

Allocating values to specific csv columns in Powershell


I'd like to ask if anybody can please advise a way how to allocate a value in variable to a column in csv.

For example:

TriggeredBy | TriggeredTime | Firstname | Lastname | Username | ....

Throughout my script I'm modifying input data and on the go I'd like it to fill in the row to the relevant column. Then another script from a different server has to take over, read the calculated values and add its calculated results into its dedicated columns. The output would be a row where I can see that all the results.

In the end it's supposed to serve as a sort of database.

Sample of script here would be:

$aduser = Get-ADUser -Filter {sAMAccountName -like $username} -Properties *
$Firstname = $aduser.GivenName 
$Firstname | Export-CSV -Path $filepath | Select-Object "First Name" 

$Lastname = $aduser.Surname 
$Lastname | Export-CSV -Path $filepath | Select-Object "Last Name" 

$TriggeredBy = $env:UserName 
$TriggeredBy | Export-CSV - Path $filepath | Select-Object "TriggeredBy" 

...

Throughout the process all saved in one relevant row. Next process does the same for the following row etc...

The "Export-CSV ...." part is obviously wrong, I would need some alternative

Many thanks!


Solution

  • Use Select-Object with calculated properties:

    Get-ADUser -Properties * -Filter "sAMAccountName -eq `"$username`"" |                            #`
      Select-Object @{ n='FirstName'; e='GivenName' },
                    @{ n='Last Name'; e='Surname' },
                    @{ n='TriggeredBy'; e={ $env:UserName } } |
        Export-Csv -NoTypeInformation -Literalpath $filePath
    

    Note that I've used a string as the -Filter argument, because that's what it ultimately becomes anyway. Using script-block literal syntax { ... } is tempting, but ultimately causes more problems than it solves - see this answer.

    Note that in Windows PowerShell Export-Csv creates ASCII(!)-encoded files by default, which can result in loss of information; use the -Encoding parameter to change that.

    PowerShell [Core] v6+, by contrast, commendably defaults to (BOM-less) UTF-8; also, the
    -NoTypeInformation switch is no longer necessary there.

    If you want to append to an existing CSV file (which needs to have the same column structure), use the -Append switch.