Search code examples
powershellcsvkeyvaluepair

Powershell - create key/value pair from CSV variable


I have following CSV file:

link,user,password
http://1.1.1.1,user1,password1
http://2.2.2.2,user2,password2

Using this script i can extract values of link,user and password headers

# Constants.
$DELIM = ','
#$CSV_F = 'C:\Users\user\Desktop\1.csv' 

# Parse keys
$keys = (gc "${CSV_F}" -TotalCount 1).Split($DELIM)
$csv = Import-CSV "${CSV_F}"
$data = @()

# Iterate through CSV to build array of hashtables.
ForEach ($r in $csv) {
    $tmp_h = @{}

    # Create hash of key-value pairs.
    ForEach($k in $keys) {
        $tmp_h[$k] = $r.($k)
    }

    # Add hash to array of hashes.
    $data += $tmp_h
}

# Display data

foreach($i in $data){

$link = $i.link

$user = $i.user

$password = $i.password

}

Output:

http://1.1.1.1

user1

password1

http://2.2.2.2

user2

password2

Because this CSV contains sensitive data i want to hide it's content.

I accomplished it in following way:

Protect-CmsMessage -To "*youralias@emailaddress.com*" -Path C:\Users\user\Desktop\1.csv -OutFile C:\Users\user\Desktop\1.csv.cms

I also can decrypt it:

$CSV_F = Unprotect-CmsMessage -To "*youralias@emailaddress.com*" -Path .\1.csv.cms

i stored unencrypted content of 1.csv.cms file into $CSV_F variable

$CSV_F
link,user,password
http://1.1.1.1,user1,password1
http://2.2.2.2,user2,password2

How to parse $CSV_F variable to get same key:value pair as i got when parsed CSV file ?

I want to avoid storing unencrypted CSV content to file.

Desired output:

http://1.1.1.1

user1

password1

http://2.2.2.2

user2

password2


Solution

  • After running Unprotect-CmsMessage you are saving the contents of the file as plain text in the $CSV_F variable. You simply have to convert it from CSV into an object that you can work with:

    ...
    $CSV_F = Unprotect-CmsMessage -To "*youralias@emailaddress.com*" -Path .\1.csv.cms
    
    $Data = $CSV_F | ConvertFrom-Csv
    
    $Data