SimonS
SimonS

Reputation: 1973

Add or Change Values to CSV

I import a CSV in PowerShell, and want to export it again by either adding or changing content.

That's how I import it:

$csv = Import-Csv $csvFile -Delimiter ";"

The CSV has three colums, UserName, Pass and Key.

When I want to change one row:

$csv = $csv | ? { $_.UserName -eq $UserName } | % {
    $_.pass = $PasName
    $_.key  = $KeyName
} 
$csv | Export-Csv $csvFile -Delimiter ";" -Force -NoTypeInformation

it leaves me with a CSV without any content. Why is that?

Also, when I just want to add one row

$csv += [PSCustomObject]@{
    UserName = $UserName
    pass     = $PasName
    key      = $KeyName
}
$csv | Export-Csv $csvFile -Delimiter ";" -Force -NoTypeInformation

it returns an error, saying:

Fehler beim Aufrufen der Methode, da [System.Management.Automation.PSObject] keine Methode mit dem Namen "op_Addition" enthält.
In Zeile:44 Zeichen:13

Does anybody know why this happens?

I know I could just add Content like so:

$xy = "{0};{1};{2}" -f xy,xy,xy
Add-Content -Path $csvFile -Value $xy

but I'd rather go with exporting the CSV completely new

Upvotes: 0

Views: 76

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Your second code snippet leaves you with an empty result because you assign the loop output back to the variable $csv. However, the loop does not produce any output, so you're effectively clearing the variable by doing that. To fix this simply remove the assignment. The loop updates the variable in-place.

$csv | Where-Object {
    $_.UserName -eq $UserName
} | ForEach-Object {
    $_.pass = $PasName
    $_.key  = $KeyName
} 
$csv | Export-Csv $csvFile -Delimiter ";" -Force -NoTypeInformation

The error from your 3rd code snippet can occur if $csv is not an array (e.g. when it's empty or contains just a single record). You can mitigate that by forcing it to be an array upon import:

$csv = @(Import-Csv $csvFile -Delimiter ";")

Also, for appending a new record to your CSV it's cleaner and more straightforward to actually append to the CSV:

[PSCustomObject]@{
    UserName = $UserName
    pass     = $PasName
    key      = $KeyName
} | Export-Csv $csvFile -Delimiter ";" -Force -NoTypeInformation -Append

Upvotes: 1

Related Questions