6

I need to do below using PowerShell scripting.

I have the below data in CSV file. I need to append another prefix to the name according to the subject supplied

Name,Subject,Roll,Div
Mark,Agri,3,Div1,
Tom,CS,6,Div3,
Alex,Aero,9,Div6

Suppose i am supplied the subject as Agri, the name should have prefix as P-. So the same CSV file will be saved and have below content

Name,Subject,Roll,Div
P-Mark,Agri,3,Div1,
Tom,CS,6,Div3,
Alex,Aero,9,Div6

Here's what I have so far:

(Import-Csv E:\Test.csv -Delimiter ',') | ForEach-Object{

    if($_.Subject -match "Agri" )
    {
      $_ = "P-" + "$_";

    }
    else
    {
     $_ = "F-" + "$_";

    }

} | Export-Csv E:\Test.csv -Delimiter ',' 
1
  • Can we see what you've tried so far? Commented Dec 27, 2013 at 22:01

2 Answers 2

6

I wasn't able to pipe this together - might just be ignorance on my part about powershell syntax. I was able to do it with the following using two lines:

($csv = Import-Csv E:\Test.csv -Delimiter ',') | ForEach {
    if ($_.Subject -match "Agri") {
        $_.Name = 'P-' + $_.Name
    } else {
        $_.Name = 'F-' + $_.Name
    }

}
$csv | Export-Csv E:\Test.csv -Delimiter ',' -NoType

Notice:

$_ = "P-" + $_;

Becomes

$_.Name = "P-" + $_.Name;
Sign up to request clarification or add additional context in comments.

5 Comments

I am getting blank file as out put. I need the same file to be modified as out put. Am I missing something?
Let me try testing it with files. I tested it keeping everything in powershell and using ConvertFrom-Csv.
I'm having trouble piping this all into a single line. If I store the $csv into a variable first, and then do $csv | Export-Csv E:\Test.csv -Delimiter ',' then it works fine...
Updated with two line answer
This deletes what's on the file when exported.
2

It seems to me the use of paren's in the following clause.

($csv = Import-Csv E:\Test.csv -Delimiter ',')

will assign to $csv the output of Import-Csv PRIOR to the ForEach processing and therefore the ForEach effects are completely lost. Not sure what you purpose is in using those paren's.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.