一次尝试捕获多个错误

时间:2019-06-26 20:12:28

标签: powershell try-catch file-permissions

因此,尝试通过简单的try / catch更新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
}

是否可以捕获特定的授权访问语句并打印失败的组名。

说我有两个小组:

  • NA \ admin
  • NA \ dev

并且两个组的Grant-SmbShareAccess都失败了,我可以捕获并打印出来吗:

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

仅使用一次尝试捕获?

1 个答案:

答案 0 :(得分:5)

查看参数:

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