如何使用Powershell从.Csv文件中获取一行信息? [英] How to get one row of info from .Csv file with Powershell?
本文介绍了如何使用Powershell从.Csv文件中获取一行信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
powershell脚本:
$test = import-csv "C:\CSVFiles\test.csv"
ForEach ($item in $test)
{
$Name = $item.("Name")
$property = $item.("property")
$location = $item.("location")
Write-Output "$Name=$Name"
Write-Output "Property=$property"
Write-Output "Location=$location"
}
此脚本显示每一行的名称,属性和位置的所有数据.我希望结果只显示一行的数据;例如,行:n1; 13; computer
This script shows all the data for name,property and location for each row. I want the results to only show the data of one row;for example the row: n1;13;computer
Cvs文件=
Name;property;location
n1;13;computer
n2;65;computer
n3;12;tablet
n4;234;phone
n5;123;phone
n6;125;phone
当前脚本显示的内容:
Name=n1
Property=13
Location=computer
Name=n2
Property=65
Location=computer
Name= n3
Property=12
Location=tablet
Name=n4
Property=234
Location=phone
Name=n5
Property=123
Location=phone
Name=n6
Property=125
Location=phone
推荐答案
有很多方法可以选择csv的行并显示数据
There are many ways to select a Row of a csv and to present the data
为演示起见,我将内联csv与here字符串一起使用.
For demonstration I use an inline csv with a here string.
$Test = @"
Name;property;location
n1;13;computer
n2;65;computer
n3;12;tablet
n4;234;phone
n5;123;phone
n6;125;phone
"@ | ConvertFrom-Csv -delimiter ';'
> $test[0]
Name property location
---- -------- --------
n1 13 computer
> $test | where-object Name -eq 'n1'
Name property location
---- -------- --------
n1 13 computer
> $test | where-object Name -eq 'n1' | Select-Object Name,property
Name property
---- --------
n1 13
> $test | where-object Name -eq 'n1' | ForEach-Object {"Name:{0} has property: {1}" -f $_.Name,$_.property}
Name:n1 has property: 13
一旦导入了csv行内容,便会转换为对象
如果要获取与条件匹配的csv的原始行,请不要导入,但:
If you want to get the original row of the csv matching a criteria don't import but:
> Get-Content "C:\CSVFiles\test.csv" | Select-String '^n1'
n1;13;computer
^ n1
是在行首定位模式的正则表达式.
^n1
is a regular expression anchoring the pattern at line begin.
Select-String -Path "C:\CSVFiles\test.csv" -Pattern '^n1'
没有管道就一样
这篇关于如何使用Powershell从.Csv文件中获取一行信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文