none
using CMD or powershell read .csv column A and output column B RRS feed

  • Question

  • Hi All
    i have a .csv like below
    Column1 Column2
    data1   abc
    data2   def
    data3   ghi
    data4   jkl
    data5   mno
    :       :


    how can i using CMD or powershell to read the column1 and output the coulum2???
    like when i input the data2 and script will echo def????

    i have a powershell work with excel but if the file is csv how to make it work???

    have a good day!

    Friday, May 25, 2018 3:23 AM

All replies

  • We cannot understand your question. Please have someone help you with your English.


    \_(ツ)_/

    Friday, May 25, 2018 3:28 AM
    Moderator
  • sorry for my bad English

    here is the question

    i have csv like below

    column1    column2

    data1        abc

    data2        def

    data3        ghi

    :               :

    how to import this csv in the script and when i input "data2", script will echo "def"

    Friday, May 25, 2018 3:41 AM
  • OK, then the text file to called "input.csv":

    Column1, Column2
    data1,   abc
    data2,   def
    data3,   ghi
    data4,   jkl
    data5,   mno

    If you want to read the Column1 as a "key", and input (1 parameter called "in")

    [CmdletBinding()]
    param(
        [Parameter(Position=0,Mandatory=$true)][string]$in
    )
    
    $selected=@()
    Import-csv .\file.csv| ForEach-Object{
        if($_.Column1 -match $in){
            $selected+= $_
        }
        
    }
    Write-Output $selected.Column2
    Remove-Variable Selected

    Save it as any name you want (ex: script.ps1)

    .\script.ps1 -in "data2"




    • Proposed as answer by j0rt3g4 Friday, May 25, 2018 6:12 AM
    • Edited by j0rt3g4 Friday, May 25, 2018 6:13 AM
    Friday, May 25, 2018 6:12 AM
  • sorry for my bad English

    here is the question

    i have csv like below

    column1    column2

    data1        abc

    data2        def

    data3        ghi

    :               :

    how to import this csv in the script and when i input "data2", script will echo "def"

    Import-Csv yourfile.csv | ?{$_.Column1 -eq 'data2' } | select -expand column2

    Yes that is very easy.  It takes only one line of code.


    \_(ツ)_/

    Friday, May 25, 2018 6:37 AM
    Moderator
  • Great,thanks!!!!!!!!!
    Friday, May 25, 2018 9:51 AM
  • it work!!!!!!!thanks!
    Friday, May 25, 2018 9:51 AM