lmurdock12
lmurdock12

Reputation: 1021

Catching multiple errors in one try/catch

So trying to do a simple try/catch updating the share access for a folder on a server in PowerShell.

try {
    Grant-SmbShareAccess -Name [FolderName] -AccountName [GroupToShare] -AccessRight Read -Force
    Grant-SmbShareAccess -Name [FolderName] -AccountName [GroupToShare] -AccessRight Read -Force
} catch {
    Write-Host "Error Granting one or more permission: $_" -ForegroundColor DarkMagenta
}

Is it possible to catch the specific grant access statement and print the group name it failed on.

Say I had the two groups:

and that the the Grant-SmbShareAccess failed for both groups, could I catch and print out:

Permission Failed for: NA\admin
Permission Failed for: NA\dev

using only one try catch?

Upvotes: 0

Views: 586

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174730

Loop over the arguments:

foreach($group in 'NA\admin','NA\dev'){
  try {
    Grant-SmbShareAccess -Name [FolderName] -AccountName $group -AccessRight Read -Force
  }
  catch {
    Write-Host "Failed to grant permission to: $group"
  }
}

Upvotes: 5

Related Questions