[英]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?如何将第一个字符串的值传递给 $group 变量,将第二个字符串传递给 $name 变量,以便我可以在以下脚本的循环中使用它?
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?因为它是 csv 为什么不使用 import-csv 而不是 get-content? furthermore, foreach is not necesary, you can filter with a simple where-object
.此外, foreach 不是必需的,您可以使用简单的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
这将获取文件中的每一行并使用,
作为分隔符将其拆分,然后将第一个值分配给$group
数组,与$name
相同
Tested with exact csv
file, working powershell version 5.1.18362.752使用精确的csv
文件进行测试,工作 powershell 版本 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添加 for 循环后,它逐行传递 arrays
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.