riahc3
riahc3

Reputation: 878

Go through a CSV line by line and see if there is a string

I'm running the following command:

Import-Csv .\list.csv -Encoding UTF8 -Header "Users"

which is a list basically with names, users and a attribute

Users
-----
Bob;User1;T
Max;User2;
Jordon:User3;T
Angel;User4;T

As you can see there are 3 users with a ;T. I should be able to able to search through that line (string) and if I find that ;T I'll do something. If I don't find that ;T I'll do something else.

What is the best way to do it?

Upvotes: 1

Views: 66

Answers (2)

Dave Sexton
Dave Sexton

Reputation: 11188

How about using a Select-String instead like this:

Select-String .\list.csv -Encoding UTF8 -Pattern '^([^;]+);([^;]+)(?=;T$)' | % {
  $name = $_.matches.Groups[1].value
  $login = $_.matches.Groups[2].value
  #do stuff
}

You can just repeat the above code for every other type you want to process by just adjusting the regex pattern.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Supply a Header field per column, otherwise you're not really getting any value from using Import-Csv. You can also specify a custom delimiter, in your example, a semicolon (;):

foreach($Row in Import-Csv .\list.csv -Encoding UTF8 -Header Name,User,Attribute -Delimiter ";") {
    if($Row.Attribute -eq 'T'){
        Do-Something -User $Row.User
    } else {
        Do-SomethingElse -Name $Row.Name
    }
}

If the statements you want to execute are very concise, you could also use a switch:

foreach($Row in Import-Csv .\list.csv -Encoding UTF8 -Header Name,User,Attribute -Delimiter ";") {
    switch($Row.Attribute){
        'T'     { Do-Something -User $Row.User }
        default { Do-SomethingElse -Name $Row.Name }
    }
}

Upvotes: 2

Related Questions