locked
Powershell function-get multple values - SOLVED RRS feed

  • Question

  • I have file 1.csv

    number, name # column name
    1,john
    2,mike
    3,test
    4,test2
    ...

    I created function for returning all values from this csv (number,name)

    Function Get-CSV {
    
     [CmdletBinding()]
    
        param (
        # CSV File path
        [Parameter(Mandatory=$true)][string]$path
        )
    
        #Create an hashtable variable
        [hashtable]$return = @{}
    
        Import-Csv $path |  
             ForEach-Object { 
    
             $number = $_.number 
             $name = $_.name
             $return.name = $name
             $return.number = $number
             return $return 
    
         }
    
          # return $return un-commenting this line don't change output 
    
    }
    
    # calling function
    
    $a = Get-CSV "C:\Users\1.csv"
    
    $a.number
    $a.name

    I get only one (last row from CSV) - a.name = test2 and a.number = 4

    How to get all rows from CSV in diffrent variables (a.name, a.number) ?


    • Edited by Dragan979 Wednesday, November 27, 2019 9:06 AM
    Wednesday, November 27, 2019 8:54 AM

Answers

  • The return is inside the loop.

    With PowerShell you do not need a return or anything.

    $a = Import-Csv$path | Select Name, Number

    This does everything you function does.  There is no need for a function.

    To learn how to write PowerShell scripts start with the following free book and do all of the exercises until you understand what PowerShell is and how to use it.

    https://www.sapien.com/books_training/Windows-PowerShell-4

    It is one of the best books written for beginners with no programming experience.


    \_(ツ)_/

    • Marked as answer by jrv Wednesday, November 27, 2019 5:57 PM
    Wednesday, November 27, 2019 9:02 AM