0

I'm trying to learn basic powershell loops on CSV files. Tried many tutorials or guides online but no avail. Hope you guys can help. Thanks

Here's my CSV file

csv file

Tried to loop through it to look for vpn_name and display the key but seems it won't find what I'm looking for. The path is correct since I tried to display what's inside $c.'vpn_name' displays list from test to test3.

$csv = import-csv -Path "path.csv"
foreach ($c in $csv) {
    $c.'vpn_name' -contains 'test'
}

Hope you guys can help. Really appreciate it. Thanks

1
  • the -contains operator is for collection objects and requires an exact match. to match test1 with test you must either use the -match regex operator OR the -like wildcard string operator ... with wildcard chars. Commented Jan 25, 2022 at 6:06

1 Answer 1

1

Firstly, the csv file format is:

vpn_name,vpn_key
test,lksajdlksja
test1,lksajdlksja
test2,lksajdlksja

Secondly, use the following to search:

   foreach ($c in $csv) {
        $c.'vpn_name' -like '*test*'   //All three rows of the csv file return true.
    }

    foreach ($c in $csv) {
        $c.'vpn_name' -contains 'test'   //Only first row of the csv file return true.
    }

About your another question, please replace

'*$username*'

with

'*'+$username+'*'
                              
Sign up to request clarification or add additional context in comments.

2 Comments

can you share what's the difference? Thanks
tried using below getting same result $username = Read-Host "Enter username " foreach ($c in $csv) { if ($c.'vpn_name' -like '*$username*') { write-host $c.'vpn_key' } }

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.