简体   繁体   中英

Assign variable value from a text file in Powershell

I have this sample text file contains the following line

group1,name1
group2,name2
group3,name3

How to pass the value of first string to $group variable and second string to $name variable so I can use it in loop in the following script?

get-content data.csv -ReadCount 1000 | foreach { $_ -match "$group" } | Out-File $name.txt -encoding Utf8

as it is a csv why not use import-csv instead of get-content? furthermore, foreach is not necesary, you can filter with a simple where-object .

import-csv data.csv -delimiter "," -header group,name|where{$_.group -match "group1"}

You can use:

$file = get-content data.csv
$group = @()
$name = @()
foreach($line in $file){
$line = $line -split ","
$group += $line[0]
$name += $line[1]
}
$name > name.txt 
$group > group.txt
# Use ">>" if name or group.txt already exist

This will take every line in the file and split it up using , as a delimiter then assign the first value into the $group array and the same with $name

Tested with exact csv file, working powershell version 5.1.18362.752

Update : If you want to pass the array line by line, you can use:

$file = get-content data.csv
$group = @()
$name = @()
foreach($line in $file){
$line = $line -split ","
$group += $line[0]
$name += $line[1]
}
for($i=0;$i -lt group.length;$i++){
$group[$i] >> group.txt
}
for($i=0;$i -lt name.length;$i++){
$name[$i] >> name.txt
}

With the added for loop, it passes the arrays line by line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM