使用powershell读取Csv文件并捕获相应的数据 [英] Read a Csv file with powershell and capture corresponding data
问题描述
使用PowerShell我想捕获用户输入,将输入与逗号分隔的CSV文件中的数据进行比较,并将相应的数据写入变量。
示例:
- 系统提示用户输入
Store_Number
,他们输入10
。 - 输入
10
与CSV文件的第一个位置
或列的数据进行比较。 - 捕获对应位置/
列中的数据,例如District_Number
,并将其写入变量。 / li>
我已经得到这个方法使用Excel文件(.xlsx),但发现它是非常慢。希望PowerShell可以更有效地读取CSV文件。
链接到示例CSV文件这里:
Store_Number,Region,District,NO_of_Devices,Go_Live_Date
1,2,230,10,2 / 21/2013
2,2,230,10,2 / 25/2013
3,2,260,12,3 / 8/2013
4,2,230,10,3 / 4/2013
5,2,260,10,3 / 4/2013
6,2,260,10,3 / 11/2013
7,2,230,10,2 / 25/2013
8, 2,230,10,3 / 4/2013
9,2,260,10,5 / 1/2013
10,6,630,10,5 / 23/2013
解决方案您应该看到的是Import-Csv
导入CSV后,您可以使用列标题作为变量。
示例CSV:
Name |电话号码|电子邮件
Elvis | 867.5309 | Elvis@Geocities.com
Sammy | 555.1234 | SamSosa@Hotmail.com
现在我们将导入CSV,并循环列表添加到数组。然后我们可以比较输入到数组的值:
$ Name = @()
$ Phone = @ )
Import-Csv H:\Programs\scripts\SomeText.csv |`
ForEach-Object {
$名称+ = $ _。名称
$ Phone + = $ _。电话号码
}
$ inputNumber =读主机 - 电话号码
if($ Phone - 包含$ inputNumber)
{
Write-HostCustomer Exists!
$ Where = [array] :: IndexOf($ Phone,$ inputNumber)
写主机客户名称:$ Name [$ Where]
}
这里是输出:
Using PowerShell I would like to capture user input, compare the input to data in a comma delimited CSV file and write corresponding data to a variable.
Example:
- A user is prompted for a "
Store_Number
", they enter "10
".- The input, "
10
" is then compared to the data in the first position or column of the CSV file.- Data, such as "
District_Number
" in the corresponding position / column is captured and written to a variable.I have gotten this method to work with an Excel file (.xlsx) but have found it to be terribly slow. Hoping that PowerShell can read a CSV file more efficiently.
Link to an example CSV file here:
Store_Number,Region,District,NO_of_Devices,Go_Live_Date 1,2,230,10,2/21/2013 2,2,230,10,2/25/2013 3,2,260,12,3/8/2013 4,2,230,10,3/4/2013 5,2,260,10,3/4/2013 6,2,260,10,3/11/2013 7,2,230,10,2/25/2013 8,2,230,10,3/4/2013 9,2,260,10,5/1/2013 10,6,630,10,5/23/2013
解决方案What you should be looking at is Import-Csv
Once you import the CSV you can use the column header as the variable.
Example CSV:
Name | Phone Number | Email Elvis | 867.5309 | Elvis@Geocities.com Sammy | 555.1234 | SamSosa@Hotmail.com
Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:
$Name = @() $Phone = @() Import-Csv H:\Programs\scripts\SomeText.csv |` ForEach-Object { $Name += $_.Name $Phone += $_."Phone Number" } $inputNumber = Read-Host -Prompt "Phone Number" if ($Phone -contains $inputNumber) { Write-Host "Customer Exists!" $Where = [array]::IndexOf($Phone, $inputNumber) Write-Host "Customer Name: " $Name[$Where] }
And here is the output:
这篇关于使用powershell读取Csv文件并捕获相应的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!