Home > other >  How to check for a specific value in a specific column of a CSV file (Powershell)
How to check for a specific value in a specific column of a CSV file (Powershell)

Time:03-02

My CSV file looks like this, but with some more content:

id   name      username    password    city
1    Random    Random123   random123   Berlin
2    Madeup    Name123     madeup123   London

Using Powershell, I need to check the "city" column and find all the users who live in "Berlin". Then, I need to create a ".txt" file with their usernames in it.

I know it's such a basic exercise, but I'm just getting started with PowerShell and, although I tried many possible solutions found in Stack Overflow, none of them have worked for me.

Any help is much appreciated!

CodePudding user response:

Try this:

 $mylist = Import-Csv myfile.csv | Where-Object City -eq 'Berlin'

$mylist will contain an array of PSCustomObjects. The properties will be the fields of your csv. For further help on Where-Object see the online help.

CodePudding user response:

After spending all day wondering why all these answers from the internet worked on other CSVs but not in mine, I found out that setting the delimiter was the solution for my problem.

Earlier, I forgot to mention that my CSV was delimited by ';' , so it actually looks like this:

id;name;username;password;city
1;Random;Random123;random123;Berlin
2;Madeup;Name123;madeup123;London

In the end, I ended up using Walter Mitty's answer (thank you, by the way!), with these added modifications, and it just worked out.

In case any student out there is bumping against the same problem as me, this was my solution:

$csv = Import-Csv -Path C:\Users\yourUser\Desktop\your.csv -Delimiter ';' -Encoding Default | Where {$_.city -eq "Berlin"}

After this, you just have to create a new file with the command "New-Item":

New-Item C:\Users\yourUser\Desktop\your.txt

And set its content with "Set-Content":

Set-Content C:\Users\yourUser\Desktop\your.txt $csv.username

Hope this helps anybody in the future. Have a good day!

  • Related