2017-10-13 65 views
0

代码:进口-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 

我相信进口CSV是进口不正确的,因为写主机$计算机使我这个:

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

但如果$ Computers被分配了th是这样:

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

输出是正确的:

美国1 US-2 US-3 US-4

所以,我需要从CSV导入为了方便,但有各计算机名保存正确的方式,没有括号或符号。这使得在我的程序中使用计算机名称非常困难。

编辑:作为讨论,我已经正确格式化CSV,现在是这样的:

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

现在获得输出:

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

+0

奇怪的输出。什么数据类型是$电脑? – guiwhatsthat

+0

默认数据类型,最有可能的字符串,不确定。如果我为堆栈溢出创建的整个测试程序看到了什么 – Fingers

+0

发布您的CSV文件样本 – Manu

回答

1

简单CSV

创建CSV(计算机。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 

如果只有计算机/ OperatingSystems感兴趣,你可以做这样的事情:

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 

等等...... :)

+0

comp是什么意思?我也使用了每个循环后,所以我不能指个人电脑 – Fingers

+0

nvm,想通了,我的脚本现在运行良好,谢谢! – Fingers

+0

啊,我的坏!我有$ comp作为我的脚本变量insted $电脑。为了便于阅读,我会编辑我的帖子。 – Akaino

1

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

一旦你有一个正确格式的CSV(或者用手动提供的标题导入),你将能够引用$computers作为一个PSObject的数组,其中每个PSObject包含一个提供名称的成员 - 例如,如果您使用

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

然后您可以参考单个记录为$Computers[$n].RegionName

在对原始问题进行编辑之后,访问数组中单个项目的正确方法是$Computers[$n].Computers。如原来描述的从文本文件中检索计算机,无需使用字段名称,请使用Get-Content而不是Import-CSV

+0

嗨,我已经查找了一个关于创建csv头文件的指南,现在我的csv文件看起来像这样: – Fingers

+0

如果您更改了CSV并仍然有问题,请更新您的问题以反映问题 - 或者提出一个新问题。 –

+0

是的,对不起,我打开注释上的新行输入,我发布了它,我编辑了我原来的帖子 – Fingers