Link to home
Start Free TrialLog in
Avatar of SURESH0518
SURESH0518

asked on

PowerShell

I have a text file which have two columns id,name as below
id|name
1|Test1
2|Test2
3|Test3

I want output as
id=1,name=Test1
id=2,name=Test2
id=3,name=Test3

How will I do in Windows PowerShell script. Any help is appreciated.
Avatar of SubSun
SubSun
Flag of India image

I guess you want to convert it in to a csv..
GC C:\input.txt | Select -Skip 1 | % {
$test = $_ -split "\|" | %{$_.Trim()}
	New-Object PSObject -Property @{
	ID = $test[0]
	Name = $test[1]
	}
} | Export-Csv C:\out.csv -nti

Open in new window


But if you want exactly same as you written then try..
$outfile = "C:\Temp\out.txt"
Set-Content $outfile $null
GC c:\temp\input.txt | Select -Skip 1 | % {
$test = $_ -split "\|" | %{$_.Trim()}
Add-Content $outfile "ID=$($test[0]),Name=$($test[1])"
}

Open in new window

Avatar of SURESH0518
SURESH0518

ASKER

Is there any way can I get column heading ID,name automatically without hard code. Sometimes I have two columns and sometimes I have 3 or more columns and I may not know column name upfront.
Example:
I may have
id|name|description
1|test|test1
2|test2|Test3

Sometime I may have
id|name|description|fundname
1|test|Test1|XXX
2|test2|Test3|YYY
Which code you trying? first one or second?
Second one
Somewhat clumsy, but working:

Param (
[string]$originalName = "\path\to\file"
[string]$copyName = "\path\to\copy"
[Int32]$noColumns = 2
)
$arrHeader = @()
$header = (Get-Content $originalName -TotalCount 1).Split("|")
for ($i=0; $i -lt $noColumns; $i++) {
  $arrHeader += $header[$i]
}

$text = ""
foreach ($line in get-content $originalName) {
  $list = $line.Split("|")
  for ($i=0; $i -lt $noColumns; $i++) {
    $text = $text + $arrHeader[$i] + "=" + $list[$i] + ","
  }
  $text = $text.Substring(0, $text.Length - 1)
  $text = $text + "`n"
}
echo $text > $copyName

Open in new window


Save it as whatever.ps1 and run it as whatever.ps1 <original_file> <target_copy> <number_of_columns>
ASKER CERTIFIED SOLUTION
Avatar of SubSun
SubSun
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You are genius and thanks for quick solution and you are really great.