使用 PowerShell 将数据正确导入数组 [英] Using PowerShell to import data properly into an array

查看:43
本文介绍了使用 PowerShell 将数据正确导入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试组合一个 PowerShell 脚本,该脚本将从 CSV 读取数据(它实际上是制表符分隔而不是 CSV,但对于 SO,我们将使用逗号)并将该数据导入到 PowerShell 多维数组中.我的 CSV 有以下数据:

I am trying to put together a PowerShell script that will read data from a CSV (it is actually tab separated and not CSV but for SO, we'll use commas) and import that data into a PowerShell multidimensional array. My CSV has the following data:

EmpID,Name,Dept
12345,John,Service
56789,Sarah,Sales
98765,Chris,Director

我的脚本如下:

$temp=gc "temp.csv"
$array=@()

$temp | Foreach{
    $elements=$_.split(",")
    $array+= ,@($elements[0],$elements[1],$elements[2])
}

foreach($value in $array)
{
    write-host "EmpID =" $value[0] "and Name =" $value[1] "and Dept =" $value[2]
}

上述工作,但我希望能够通过更合适的名称来引用数组元素,因为元素比上面显示的要多得多,这会让人感到困惑.为此,我尝试使用哈希表,定义新对象、成员、类型等,但它们似乎永远无法正常工作.我可能是错的,但我觉得我在绕圈子跑,现在我可能迷路了.基本上,我想做的是,而不是使用:

The above works, but I would like is to be able to refer to the array elements by a more proper name because there are a lot more elements than are shown above and this gets confusing. To do this, I’ve tried to use hash tables, defining new objects, members, types, etc. but they never seem to work properly. I may be wrong but I feel like I’m running in a circle and now I may be lost. Basically, what I want to do is, instead of using:

write-host "EmpID =" $value[0] "and Name =" $value[1] "and Dept =" $value[2]

我想用这样的东西替换上面的内容:

I would like to replace the above with something like this:

write-host "EmpID =" $value.EmpID "and Name =" $value.Name "and Dept =" $value.Dept

这可能吗?如果是这样,有人可以指出我正确的方向吗?CSV 来自另一个来源,无论如何都带有标题行(除非手动编辑 CSV,否则无法将其删除).所以我想使用标题行来命名数组列,但我不必使用它.我的主要问题(目标)是至少能够命名不同的列.它可以通过使用从 CSV 导入的第一行或通过将名称输入脚本本身来动态完成.

Is this possible? If so, can someone point me in the correct direction? The CSV is coming from another source and comes with the header row anyway (it can’t be removed except by manually editing the CSV). So I would like to use the header row to name the array columns but I don’t have to use it. My primary question (goal) here is to at least be able to name the different columns. It can be done either dynamically by using the first row imported from the CSV or by entering the names into the script itself.

谢谢

推荐答案

你工作太辛苦了.默认情况下,导入 CSV 将使用逗号分隔,您可以使用 -Delimiter 处理制表符分隔.从那里您可以按名称引用列.

You're working too hard. Import-CSV will work with comma separation by default, and you could handle tab delimited using -Delimiter. From there you can reference the columns by name.

Import-CSV "temp.csv" | Write-Host "EmpID=" + $_.EmpID

这篇关于使用 PowerShell 将数据正确导入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆