Search code examples
powershelltry-catchfile-permissions

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:

  • NA\admin
  • NA\dev

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?


Solution

  • 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"
      }
    }