0

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

7
  • 1
    Changing ForEach-Object to Where-Object { $_.SourceId -eq 1 } should be it Commented Sep 28, 2022 at 13:03
  • @SantiagoSquarzon so i will need to Import-Csv each time i need to do the query ? or i can do the Import-Csv once and do multiple queries ? Commented Sep 28, 2022 at 13:07
  • 1
    you can store the object produced from CSV parsing in a variable and then just query that variable -> $csv | Where-Object ... Commented Sep 28, 2022 at 13:07
  • @SantiagoSquarzon can you provide more code please? so i do not miss what you are referring to ? Commented Sep 28, 2022 at 13:11
  • 1
    You don't need the continuation mark after the pipe. I would make a hash table. Import-Csv test.csv | foreach-object { $hash = @{} } { $hash[$_.sourceid] = $_.destinationid } Commented Sep 28, 2022 at 13:17

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

can you please check my other question based on your reply stackoverflow.com/questions/73884847/… ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.