2

I'm new with powershell and I'm pretty sure my question is quite easy for experts. I have a CSV file with this table. enter image description here

I want to write a script where I give a variable $name, and get its state if it exists in the machine column. I tried to do something like this:

    $csv=Import-Csv C:\data.csv -Delimiter=","
foreach ($row in $csv){

$machine=$row.Machine
If ($machine=$searched_name){
    $searched_state=$row.State}

} 

But this clearly does not work.

Anyone can help me please ?

Thanks. !

7
  • 2
    How about: Import-Csv C:\data.csv | Where-Object { $_.Machine -eq "m1" } Commented May 26, 2021 at 22:05
  • 1
    just FYI - this >>> If ($machine=$searched_name){ <<< is an assignment, not a comparison. [grin] you need to use -eq instead of =. Commented May 26, 2021 at 23:24
  • Import-csv returns an object with properties, methods and so on. I advise you to explore it using Get-Member and according wat you get, start processing it according your needs with Select-object and/or Foreach-object Commented May 27, 2021 at 6:09
  • In addition to what @Lee_Dailey said, you should not use the = on a parameter as well like you do in -Delimiter="," Use a space instead. Besides, if the delimiter used is a comma, you can leave that out entirely, because a comma is the default. Commented May 27, 2021 at 7:52
  • @Theo - i think the delimiter used depends on the locale. from what i have been told, the ; is the default in some locales - kinda like the use of , instead of . for numeric delims. Commented May 27, 2021 at 13:30

1 Answer 1

3

Here, try this, I think it's what you're looking for. Note that I'm using ConvertFrom-Csv instead of importing it from a file but for your test case you can just remove that part and import your Csv as you normally do.

# Use this instead of ConvertFrom-Csv
# $csv = Import-Csv C:\data.csv

$csv = @'
Machine,State
m1,0
m2,1
m3,2
m4,3
'@ | ConvertFrom-Csv

$question = $null

while($question -ne 'X')
{
    Clear-Host
    $question = Read-Host "Enter Machine Name to query or 'X' to Exit"
    
    if($question -eq 'x')
    {
        break
    }
    
    $val = $csv.where({$_.Machine -eq $question}).State
    
    if(-not $val)
    {
        "`nMachine Name '$question' could not be found in CSV file."
        "Press Enter to restart the loop."
        Read-Host
        continue
    }

    "`nState for '$question' is '$val'.`n"
    "Press Enter to restart the loop."
    Read-Host 
}
Sign up to request clarification or add additional context in comments.

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.