Jump to content

Script help please : split a file in batches of two rows.


Recommended Posts

Posted

I have a CSV file of data in a single column.

 

EG.

 

User1

Number1

User2

Number2

User3

Number3

 

I'd like the CSV file split in to multiple files named; User1.csv, User2.csv etc - the contents of each being Number1, Number2 respectively.

 

Has anyone got any ideas how to achieve this?

 

I then would want a script to copy from the folder containing these files in to the user(x)'s home drives; eg copy User1.csv to \\servername\user1$\documents\user1.csv

 

Not much to ask right haha

Posted
Is it always going to be a single number after a user? Or could it be 2+?

 

Steve

 

Hi,

 

The actual file of data will be like this:

 

 

Where will be between 2 and 3 characters & will be 6 digits.

 

 

I'm trying to make a variance of this code, but I'm not getting anywhere.

 

$csv = Import-CSV "file.csv"
$i = $null
$j = $null
$k = 2
ForEach ($row in $csv) {
   $i++
   $list += $row   
   if ($i -eq $k) {      
        $j++
        $path = "H:\csv\csv"+$j+".txt"     
        Out-File -Filepath $path -encoding ascii -inputobject $list      
        $list = $null      
        $k = $k + 2
   }
}

Posted (edited)

Basically in a real quick bodged way I'd just do it like this:

 

$file = Import-CSV "test.csv" -header Demo
$userName = ""
$outputFile = ""
$counter = 1

foreach($line in $file)
{

$checkCounter = $counter % 2

if ($checkCounter -eq 0)
{
	New-Item "C:\test\$username\$outputFile"
	Set-Content "C:\test\$username\$outputFile" $line.Demo
}

if ($checkCounter -eq 1)
{
	$userName = $line.Demo
	$outputFile = $line.Demo + ".csv"
	Write-Host $outputFile
}

$counter++
}

 

basically, loops through it, looks if it's odd if so creates file, if it's even writes to last file it made etc

 

Obviously a lot "neater" routes but it works just need to modify your paths :p

 

Steve

Edited by Steve21
  • Thanks 1
Posted (edited)

$x = Import-Csv -Path .\test.csv -Header 'column1'

for ($i=0; $i -lt $x.Length; $i=$i+2) {
 $line = [pscustomobject]@{'number' = $x[$i+1].column1}
 $filename = $x[$i].column1+".csv"
 write-host $filename
 $line | export-csv $filename  -notypeinformation
}

 

don't use ForEach when you're not using 1 line at a time, back to basics

Edited by mavhc
  • Thanks 1
Posted
$x = Import-Csv -Path .\test.csv -Header 'column1'

for ($i=0; $i -lt $x.Length; $i=$i+2) {
 $line = [pscustomobject]@{'number' = $x[$i+1].column1}
 $filename = $x[$i].column1+".csv"
 write-host $filename
 $line | export-csv $filename  -notypeinformation
}

 

don't use ForEach when you're not using 1 line at a time, back to basics

 

Worked perfectly.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...