Home > Back-end >  how to add information to a row and csv with powershell?
how to add information to a row and csv with powershell?

Time:03-22

i have csv file with 3 columns SID, SamAccount name, ENABLED. i also have folder containing files that called in a combination of "UVHD-" SID. i try to update the csv file with Length, LastWriteTime so it will be like this for example:

SID     SAMAccountName     Enabled      Length      LastWriteTime
S-...   FelixR             False        205520896   02/02/2021  9:13:40

i tried many things and all failed this is the best i could get:

Import-Csv $path\SID-ListTEST2.csv | select -ExpandProperty SID | ForEach-Object { Get-Childitem –Path $path\"UVHD-"$_.vhdx | Export-Csv $path\SID-ListTEST2.csv -Append | where $_   }

CodePudding user response:

Use calculated properties:

(
  Import-Csv $path\SID-ListTEST2.csv | 
    Select-Object *, 
                  @{ 
                    Name='LastWriteTime';
                    Expression={ (Get-Item "$path\UVHD-$($_.SID).vhdx").LastWriteTime } 
                  }
) | # Export-Csv -NoTypeInformation -Encoding utf8 $path\SID-ListTEST2.csv

Outputs to the display; remove the # from the last line to export to a CSV file instead.
Note the (...) around the pipeline, which ensures that all output is collected up front, which is the prerequisite for saving the results back to the original input file. Note that the original character encoding isn't necessarily preserved - use -Encoding to specify the desired one.

This adds one additional property, LastWriteTime; construct the other ones analogously.

For improved performance, you could cache the result of the Get-Item call, so that it doesn't have to be repeated in every calculated property: In the simplest case, use ($script:file = Get-Item ...) in the first calculated property, which you can then reuse as $script:file (or just $file) in the subsequent ones. Note that the $script: scope modifier is necessary, because the script blocks of calculated properties run in child scopes.[1]

Note that if no matching file exists, the Get-Item call fails silently and defaults to $null.


[1] Therefore, the more robust - but more cumbersome - approach would be to use Set-Variable -Scope 1 file (Get-Item ...) instead of $script:file = Get-Item ..., to ensure that the variable is created in the immediate parent scope, whatever it happens to be.

  • Related