Cheries
Cheries

Reputation: 902

How to set as variable csv column using powershell?

I have csv file like this

ID Name
4  James
6  John
1  Cathy

I want to save those file as .cmd with this format

SET NUMBER1=4
SET NUMBER2=6
SET NUMBER3=1

The total of ID in the csv file is not always 3. If the ID more than 3, it means my cmd file be like this

SET NUMBER1=4
SET NUMBER2=6
SET NUMBER3=1
SET NUMBERN=N

Anyone can help please. I really new in powershell, really need help and advice please. Thanks

$ID = Import-Csv .\Data.csv | Select-Object -ExpandProperty ID
$ID.Count 

ForEach ( $id in $ID ) {

}

I am stuck here

Upvotes: 2

Views: 1653

Answers (2)

AdminOfThings
AdminOfThings

Reputation: 25041

An alternative approach is below if your headers are always present in the file. It doesn't matter what the delimiter is as long as it isn't a number. Your delimited data in the sample is not consistent. Otherwise, Import-Csv would be a safer option.

$fileData = Get-Content file.csv
$output = for ($i = 1; $i -lt $fileData.count; $i++) {
        "SET NUMBER{0}={1}" -f $i,($fileData[$i] -replace "(?<=^\d+).*")
      }
$output | Out-File file.cmd

Explanation:

The format operator (-f) is used to help construct the output strings. The ID numbers are selected using regex by replacing everything that comes after the beginning digits on each line.

Upvotes: 3

f6a4
f6a4

Reputation: 1782

Try this:

# set current directory to script directory
Set-Location $PSScriptRoot

# import csv-file, delimiter = space
$content = Import-Csv 'test.csv' -Delimiter ' '
$output  = ''

# create output lines
for( $i = 1; $i -le $content.Count; $i++ ) {
    $output += 'SET NUMBER' + $i.ToString() + '=' + $content[$i-1].ID.ToString() + [environment]::NewLine
}

# output to file
$output | Out-File 'result.bat' -Force

Upvotes: 2

Related Questions