Powershell $?变量不符合预期

时间:2013-05-20 15:31:09

标签: powershell powershell-v2.0

我有一个用于创建邮箱的脚本。我刚刚发现我的错误处理没有按预期工作。

Write-Host "Attempting to create mailbox."
[void](Enable-Mailbox johndoe `
    -DisplayName "Doe,John" `
    -Alias johndoe `
    -RetentionPolicy 'Custom Retention Policy' `
    -ActiveSyncMailboxPolicy 'Default')
if($?){
    Write-Host "User & mailbox created"; Write-Host}
else{
    Write-Host "Error creating user/mailbox" -ForegroundColor Red -BackgroundColor Yellow
    exit}
Add-MailboxPermission -Identity johndoe -User 'DOMAIN\ExchangeFullAdmins' -AccessRights 'FullAccess'
if($?){
    Write-Host "Permissions set on mailbox"; Write-Host}
else{
    Write-Host "Error setting ExchangeFullAdmins permissions on mailbox" -ForegroundColor Red -BackgroundColor Yellow
exit}

如果创建邮箱时出错,则第一个if($?)评估为$true,第二个评估为$false(因为没有邮箱可以执行操作)。我希望两者都评估为$false。任何想法为什么第一个没有正确解雇?

这些是每个命令产生的错误:

Enable-Mailbox : Unable to generate the e-mail address. Unable to load address module 'C:\Program Files\Microsoft\Excha
nge Server\V14\Mailbox\address\SMTP\AMD64\inproxy.dll' for address type 'SMTP'. Additional message: 'Access is denied'.
At \\server\share\temp.ps1:2 char:22
+ [void](Enable-Mailbox <<<<  johndoe `
+ CategoryInfo          : NotSpecified: (0:Int32) [Enable-Mailbox], RusException
+ FullyQualifiedErrorId : 385E7D70,Microsoft.Exchange.Management.RecipientTasks.EnableMailbox

Add-MailboxPermission : Cannot bind argument to parameter 'Identity' because it is null.
At \\server\share\temp.ps1:13 char:33
+     Add-MailboxPermission -Identity <<<<  johndoe -User 'DOMAIN\ExchangeFullAdmins' -AccessRights 'FullAccess'
    + CategoryInfo          : InvalidData: (:) [Add-MailboxPermission], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.Exchange.Management.RecipientTa
   sks.AddMailboxPermission

1 个答案:

答案 0 :(得分:2)

我认为因为类型转换是成功的。删除[void]然后重试。

如果有效,那么您可以尝试代替[void]管道到Out-Null并查看是否收到错误:

Enable-Mailbox johndoe ` -DisplayName "Doe,John" ` -Alias johndoe ` -RetentionPolicy 'Custom Retention Policy' ` -ActiveSyncMailboxPolicy 'Default' | Out-Null

相关问题