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是在行开始处 anchor 定模式的正则表达式。
Select-String -Path "C:\CSVFiles\test.csv" -Pattern '^n1' 

没有管道也一样


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!