Read a Csv file with powershell and capture corresponding data

后端 未结 3 2028
北恋
北恋 2020-12-03 05:12

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:

相关标签:
3条回答
  • 2020-12-03 05:51

    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:

    I Found Sammy

    0 讨论(0)
  • 2020-12-03 06:01

    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!

    0 讨论(0)
  • 2020-12-03 06:07

    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)

    0 讨论(0)
提交回复
热议问题