1

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?

3
  • 5
    What is reasoning behind not using -Delimiter ";" -Header Name,User,Attribute and then if($_.Attribute -ne "T"){ do-somethingelse }? Commented Jul 28, 2015 at 9:56
  • @MathiasR.Jessen Just make that the answer to this one. Or at least an answer Commented Jul 28, 2015 at 12:06
  • @Matt you're right, done! Commented Jul 28, 2015 at 12:22

2 Answers 2

2

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

Comments

0

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.

Comments

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.