繁体   English   中英

如何使用Powershell从.Csv文件中获取一行信息?

[英]How to get one row of info from .Csv file with Powershell?

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

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行并显示数据

为了演示,我使用带here字符串的内联csv。

$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的原始行,请不要导入,但:

> Get-Content "C:\CSVFiles\test.csv" | Select-String '^n1'

n1;13;computer

^n1是将模式锚定在行开始处的正则表达式。

Select-String -Path "C:\CSVFiles\test.csv" -Pattern '^n1'

没有管道是一样的

因此,您当前的输出是3个对象,这些对象主要包含3个标头。 一个是名字 ; 第二个是Property ,第三个是Location

作为解决方案的一部分,您可以通过指定索引值来提取记录,也可以使用.Headername来提取同一对象的所有集合。 喜欢:

避免使用Foreach并使用$test[0]$test[1]

或者您可以使用: $test.Name直接获取csv中的所有名称

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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