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 ','
A CSV (Comma Separated Values) file is a special type of file that you can create or edit in Excel. Rather than storing information in columns, CSV files store information separated by commas.
The easiest way to edit a text file in PowerShell on your Windows machine is to run the command notepad.exe my_text_file. txt , or simply notepad my_text_file. txt , in your PowerShell terminal to open the text file with the visual editor Notepad.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With