繁体   English   中英

进口-CSV Powershell

[英]Import-Csv Powershell

代码:

$Computers = Import-Csv -Path C:\temp\Computers.csv
write-host $Computers

CSV 文件(其中 US-1 是 A1,US-2 是 A2,依此类推)

US-1
US-2
US-3
US-4

我相信 Import-Csv 导入不正确,因为 Write-Host $Computers 给了我这个:

@{US-1=US-2} @{US-1=US-3} @{US-1=US-4}

但是如果 $Computers 以这种方式分配:

$Computers = "US-1", "US-2", "US-3", "US-4"

output 是正确的:

US-1 US-2 US-3 US-4

因此,为了方便起见,我需要从 CSV 导入,但要以正确的方式保存每个计算机名称,不带括号或符号。 这使得在我的程序的 rest 中使用计算机名称非常困难。

编辑:如上所述,我已经正确格式化了 csv,现在是这样的:

Computers,
US-1
US-2
US-3
US-4

现在得到 output:

@{计算机=US-1} @{计算机=US-2} @{计算机=US-3} @{计算机=US-4}

您的CSV文件格式错误; 它没有标题行。 重新生成文件以使其具有标题行,或者将-Header参数用于Import-CSV

拥有正确格式的CSV(或使用手动提供的标头导入)后,您就可以将$computers引用$computers PSObjects数组,其中每个PSObject包含一个具有提供名称的成员-例如,如果您用过的

$Computers = Import-CSV -Header "RegionName" -Path C:\TEMP\Computers.CSV

那么您可以将各个记录称为$Computers[$n].RegionName

编辑原始问题之后,访问数组中各个项目的正确方法是$Computers[$n].Computers 要按照最初描述的从文本文件中检索计算机,而无需使用字段名,请使用Get-Content而不是Import-CSV

简单的CSV

创建您的CSV(computers.csv):

Computer
US-1
US-2
US-3

导入您的CSV:

$computers = Import-Csv Computers.csv

访问您的值:

Write-Host $computers # This results to something like this: @{Computers=US-1} @{Computers=US-2} @{Computers=US-3} @{Computers=US-4}
# This is perfectly fine. It's all of your computer-objects

访问每个值:

write-host $computers[n] # replace n with your index, starting at 0 to n-1
write-host $computers[1] # results in US-2

如果只对计算机感兴趣,则可以执行以下操作:

write-host $computers.Computer # restults in US-1 US-2 US-3 US-4

同样,对于更大的CSV:

Computers, OperatingSystem
US-1, Windows
US-2, Linux
US-3, SomeOtherUnix
US-4, MacOS

导入CSV:

$computers = Import-Csv Computers.csv

访问您的值:

Write-Host $computers # This results to something like this: 
# @{Computers=US-1; OperatingSystem=Windows} @{Computers=US-2; OperatingSystem=Linux} @{Computers=US-3; OperatingSystem=SomeOtherUnix} @{Computers=US-4; OperatingSystem=MacOS}
# This is perfectly fine. It's all of your computer-objects

访问每个值:

write-host $computers[n] # replace n with your index, starting at 0 to n-1
write-host $computers[1] # results in 

Computers OperatingSystem
--------- ---------------
US-1      Windows

如果仅对计算机/操作系统感兴趣,则可以执行以下操作:

write-host $computers.Computers # restults in US-1 US-2 US-3 US-4
write-host $computers.OperatingSystem # restults in US-1 US-2 US-3 US-4

等等... :)

赤野简短回答的总结!

在此处输入图像描述

暂无
暂无

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

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