简体   繁体   中英

Foreach error handling in Powershell

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

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 (ie 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" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM