Tuesday, 11 September 2012

How to split one file into many based on condition using PowerShell


I have been in a scenario where I have to spilt the CSV file content into many .CSVs based on some condition.
Below are the steps I have followed to achieve this using PowerShell.

At First I import the CSV file which I need to spit and then for each data row in the csv file call the function “CreateOrAppendCSV “  by passing two parameters each data row entry and filename.

IMPORT-CSV “C:\Source.csv” | Foreach-Object { $path=$filePath+".csv"; select-object -input $_ -prop @{Name='Name';expression={$_.Name;}},@{Name='Url';expression={$_.Url;}} |  CreateOrAppendCSV  $_ $path }

# This will create the new csv file if not exists or append to the existing csv file for position
Function CreateOrAppendCSV{
Param($item,$path)
If(Test-Path $path -PathType Leaf) # This Test-Path command checks for file exists or not
{
    # If file exists then append using ADD-Content Command  
   $fileImport= Import-Csv $path
   $newItem= New-Object PsObject     
   $newItem | Add-Member -MemberType NoteProperty -Name "Name" -Value $item.Name
   $newItem | Add-Member -MemberType NoteProperty -Name "Url" -Value $item.Url
   $newItem | ConvertTo-Csv  -NoTypeInformation|select -Skip 1 | Add-Content $path
}
Else
{
   $item | Export-Csv -Path $path -NoTypeInformation #Export if file not exists.
}
}

Hope this help.
Isha Jain

No comments:

Post a Comment