GettingStarted
GettingStarted

Reputation: 7625

Parse a multi field CSV file

I have a CSV file that looks like this

WRK-STATION-1, Room 54
WRK-STATION-2, Room 12
WRK-STATION-3, Room 45
WRK-STATION-4, Room 11
WRK-STATION-5, Room 32

My current code assumes there is only 1 column in my CSV file and code looks like this:

$computerlist = Get-Content $COMPUTERLIST -ErrorAction Stop
foreach ($computer in $computerlist) {
    if ((Test-Connection -ComputerName $computer -Quiet) -eq $true) {
        # some stuff happens here
        # I would like to Output to the screen "The computer with tha name
        # WRK-STATION-1 in Room 54 has been completed"
        # Or create an output file that adds a 3rd column to my input saying
        # "COMPLETED"
    } else {
        # I would like to Output to the screen "The computer with tha name
        # WRK-STATION-1 in Room 54 has failed"
        # Or create an output file that adds a 3rd column to my input saying
        # "FAILED"
    }

I would like to figure out how to make it understand that there are 2 columns.

Upvotes: 0

Views: 61

Answers (2)

olegk
olegk

Reputation: 787

Perhaps, you need something like this?

  $computerlist = Get-Content $COMPUTERLIST -ErrorAction Stop
  foreach ($computerInfo in $computerlist) {
       $computer = $computerInfo -split ',' | select -First 1
       if((Test-Connection -ComputerName $computer -Quiet) -eq $true) {
         # some stuff happens here
         # I would like to Output to the screen "The computer with tha name WRK-STATION-1 in Room 54 has been completed"
         # Or create an output file that adds a 3rd column to my input saying "COMPLETED"
       }
       else {
         # I would like to Output to the screen "The computer with tha name WRK-STATION-1 in Room 54 has failed"
         # Or create an output file that adds a 3rd column to my input saying "FAILED"
   }

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200473

Use Import-Csv instead of Get-Content. If the input file doesn't have a header line you can specify the column headers via the -Header parameter.

$computerlist = Import-Csv $COMPUTERLIST -Header Name,Room -ErrorAction Stop

That way you can use it like this:

foreach ($computer in $computerlist) {
    if (Test-Connection -ComputerName $computer.Name -Quiet) {
        ...
    } else {
        "Computer $($computer.Name) in $($computer.Room) has failed."
    }
}

Upvotes: 2

Related Questions