Home > Software engineering >  Query CSV file based on a column value using Power Shell
Query CSV file based on a column value using Power Shell

Time:09-29

I have this C:\test.csv file:-

enter image description here

and i am importing this file and read the data as follow:-

$SourceID = @()
$DestinationID = @()

Import-Csv C:\test.csv |`
    ForEach-Object {
        $SourceID  = $_.SourceID
        $DestinationID  = $_."DestinationID"
    }

but how i can query the .CSV file based on the source ID? for example to get the DestinationID for the SourceID = 1?

Thanks

CodePudding user response:

I would make a hash table. The first script block is a 'begin' clause. This can be a good time saver with a large file. $hash[1] doesn't work.

Import-Csv c:\test.csv |
  foreach-object { $hash = @{} } { $hash[$_.sourceid] = $_.destinationid }


$hash['1']
 
10


$hash['2']

20


$hash.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object
  • Related