user3175024
user3175024

Reputation: 41

Read an .csv and export it to a brand new csv file - PowerShell

I'm brand new using powershell, and need some help. I have a csv named test.csv and looks like this:

----------------------------------
name         lastname       alias        
John         Smith          John              
Marie        Curie          Mary
----------------------------------

The thing is that i need to export the info of the two rows into two different files. The name of the file should be the one that is under the 'alias' column

Example:

Name: John

-----------------------------------
name         lastname       alias        
John         Smith          John

-----------------------------------

Mary

----------------------------------
name         lastname       alias        
Marie        Curie          Mary

----------------------------------

I tried with the following script:

Import-Csv c:\test\test.csv  | foreach ($line ){New-Item c:\test\$_alias.csv -type file}

Any suggestions?

Upvotes: 0

Views: 265

Answers (2)

MontyX
MontyX

Reputation: 129

My solution uses scripting loops and variables:

$path = "c:\test\"
$csv = Import-Csv "$($path)test.csv"
$csv |
%{
    Export-Csv -InputObject $_ -NoTypeInformation -Path "$($path)$($_.Alias).csv"
}

Upvotes: 0

user189198
user189198

Reputation:

This script ought to work for you. It creates a new file for each line, using the alias field as the file name.

$Data = Import-Csv -Path c:\test\test.csv;

foreach ($Item in $Data) {
    Export-Csv -InputObject $Item -NoTypeInformation -Path ('c:\test\{0}.csv' -f $Item.Alias);
}

Upvotes: 1

Related Questions