Read a Csv file with powershell and capture corresponding data
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 | EmailElvis | 867.5309 | Elvis@Geocities.comSammy | 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:
Old topic, but never clearly answered. I've been working on similar as well, and found the solution:
The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:
Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`ForEach-Object { $Name += $_.Name $Phone += $_."Phone Number"}
Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes!(Sorry for expanding on your comment Austin)
So I figured out what is wrong with this statement:
Import-Csv H:\Programs\scripts\SomeText.csv |`
(Original)
Import-Csv H:\Programs\scripts\SomeText.csv -Delimiter "|"
(Proposed, You must use quotations; otherwise, it will not work and ISE will give you an error)
It requires the -Delimiter "|"
, in order for the variable to be populated with an array of items. Otherwise, Powershell ISE does not display the list of items.
I cannot say that I would recommend the |
operator, since it is used to pipe cmdlets into one another.
I still cannot get the if statement to return true and output the values entered via the prompt.
If anyone else can help, it would be great. I still appreciate the post, it has been very helpful!