Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to handle if a foreach loop in PS does not find the value? else does not work

i have a PS script that searches a csv for the computer name. it does that just fine, but i cannot seem to introduce anything to stop the script if it doesn’t find it. I’m probably missing something, but I am new to PS scripting like this. i just need the script to exit if it doesn’t find it.

#pull pc name
$computerid = (hostname)

#pull spreadsheet
$spreadsheet = Import-Csv -Path '\\<redacted>\software\Scripts\x2goScript\WorkstationList.csv'
ForEach ($row in $spreadsheet) { 
  if ($computerid -eq $spreadsheet.name) {
    $orange = $spreadsheet.OrangeID 
    $ipaddr = $spreadsheet.ServerIP
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instead of using a test inside a ForEach-Object call, I suggest finding the matching CSV row (object) using Where-Object first, and then acting based on whether such a row was found or not:

$computerName = hostname

# Find the matching row for $computerName, if any.
$matchingRow = 
  Import-Csv -Path '\\<redacted>\software\Scripts\x2goScript\WorkstationList.csv' |
    Where-Object Name -eq $computerName

if (-not $matchingRow) { 
  Write-Warning "No CSV row found for server $computerName." 
  # Exit the script, for instance.
  exit 1
}

$orange = $matchingRow.OrangeID
$ipaddr = $matchingRow.ServerIP
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading