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 :
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