5

Is there a way to catch and save bad names in a foreach loop? I have the following:

$CollectionName = "Import Test"
$PCName = Import-Csv "C:\Powershell\import_test.csv" 
foreach($computer in $PCName) {
Add-CMDeviceCollectionDirectMembershipRule -CollectionName $CollectionName -ResourceID $(Get-   CMDevice -Name $computer.computername).ResourceID
}

What I would like to do is that if there is a bad name in the csv then instead of displaying the "Cannot validate argument" error I currently get, just output the failed name to a text file.

Thanks

1
  • Have you played with -ErrorAction? Also, here's a page about catching exceptions in powershell: stackoverflow.com/questions/4691874/… Commented Jul 22, 2013 at 20:19

1 Answer 1

11

Yes. Put the statement(s) inside the loop in a try..catch block:

foreach($computer in $PCName) {
  try {
    Add-CMDeviceCollectionDirectMembershipRule ...
  } catch {
    "Bad name: $name" | Out-File 'C:\bad_names.txt' -Append
  }
}

If the error is a non-terminating error (i.e. displays an error message, but isn't caught by try..catch), you can turn it into a terminating error by adding -ErrorAction Stop to the command or by setting $ErrorActionPreference = "Stop".

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, works perfect. I've read about try catch but haven't used them before.

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.