PowerShell脚本 - 如果命令失败,请尝试另一个

时间:2016-02-16 13:29:40

标签: powershell exchange-server

我正在尝试使用Add-MailboxFolderPermission cmdlet让PowerShell授予日历权限,但是,如果已设置权限,我希望它使用Set-MailboxFolderPermission cmdlet。

到目前为止,我的脚本看起来像这样:

$OU = Read-Host 'Type OU Name Here'
$allmailbox = Get-Mailbox -OrganizationalUnit "OU=$OU,OU=Users,DC=Contoso,DC=com"
$User = Read-Host 'Type the username of the user that needs access to the other calendars here. This is typically a manager'
$Rights = Read-Host 'Type the level of access the user should have. Examples include Reviewer, Editor etc'

Foreach ($Mailbox in $allmailbox)

{Add-MailboxFolderPermission –identity ($Mailbox.alias+’:\calendar’) –user "<domain>\$user" –Accessrights $Rights}

我不确定我是否需要Try Catch类的东西(脚本新手)。也许是这样的?

$OU = Read-Host 'Type OU Name Here'
$allmailbox = Get-Mailbox -OrganizationalUnit "OU=$OU,OU=Users,DC=Contoso,DC=com"
$User = Read-Host 'Type the username of the user that needs access to the other calendars here. This is typically a manager'
$Rights = Read-Host 'Type the level of access the user should have. Examples include Reviewer, Editor etc'

Foreach ($Mailbox in $allmailbox)

Try

{Add-MailboxFolderPermission –identity ($Mailbox.alias+’:\calendar’) –user "<domain>\$user" –Accessrights $Rights}

Catch

{Set-MailboxFolderPermission –identity ($Mailbox.alias+’:\calendar’) –user "<domain>\$user" –Accessrights $Rights}

任何建议都将不胜感激!

2 个答案:

答案 0 :(得分:1)

可能不是尝试捕获,因为你可以很好地隐藏合法错误,虽然在那种情况下该集合可能也会失败,但你不能使用:

$permission = Get-MailboxFolderPermission -identity ($Mailbox.alias+’:\calendar’) -User "<domain>\$user"
if($permission -eq $null){
    Add-MailboxFolderPermission –identity ($Mailbox.alias+’:\calendar’) –user "<domain>\$user"  –Accessrights $Rights
}else{
    Set-MailboxFolderPermission –identity ($Mailbox.alias+’:\calendar’) –user "<domain>\$user" –Accessrights $Rights
}

答案 1 :(得分:0)

@Alexis

很抱歉,评论中的格式很糟糕。

只是为了检查一下,整个脚本会是这样的吗?

$OU = Read-Host 'Type Bureau Short Code Here'
$allmailbox = Get-Mailbox -OrganizationalUnit "OU=$OU,OU=All Scottish CABs,DC=internal,DC=scottishcabs,DC=org,DC=uk"
$User = Read-Host 'Type the username of the user that needs access to the other calendars here. This is typically a bureau manager'
$Rights = Read-Host 'Type the level of access the user should have. Examples include Reviewer, Editor etc'

Foreach ($Mailbox in $allmailbox){

    $Permission = Get-MailboxFolderPermission -identity ($Mailbox.alias+’:\calendar’) -User "<domain>\$user" 

    if ($Permission -eq $null)

    {Add-MailboxFolderPermission –identity ($Mailbox.alias+’:\calendar’) –user "<domain>\$user" –Accessrights $Rights}

    Else

    {Set-mailboxfolderpermission –identity ($Mailbox.alias+’:\calendar’) –user "<domain>\$user" –Accessrights $Rights}
}