powershell - Powershell脚本给出错误但仍返回 “Successfully”

标签 powershell error-handling active-directory exchange-server

我正在编写一个程序来创建一个AD帐户并启用Exchange邮箱,并且从中得到一些奇怪的行为。

首先,尽管它成功创建了AD用户,但由于“找不到MyPath/先生示例”,因此无法启用邮箱。我认为这是由于AD服务器和Exchange服务器之间的时间差(代码在Exchange服务器上运行)造成的。虽然插休眠眠时间似乎可以解决此问题,但还有其他可能会丢失的可能性吗?

其次,我在Powershell使用的“红色错误文本”中收到此错误消息。看来我的try/catch语句使错误漏了,这导致我的脚本错误地通知我任务已成功完成。如何强制将错误捕获在脚本中而不是在控制台上显示? (我在测试过程中以点源方式运行它,这就是我注意到这一点的方式。)

我在下面包括了相关部分。任何帮助表示赞赏!谢谢=)

Import-Module ActiveDirectory
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin
$errorLog = @()
$masterLog = @()
$time = Get-Date

New-ADUser -SamAccountName "example" -Name "Mr. Example" -Path "DC=MyPath" -Enabled 1 -Server ADServer

try{
    Enable-Mailbox -Identity "MyPath/Mr. Example" -Alias "example" -Database "DatabaseName"
}
catch{
    $myError = $Error[0]
    $errorLog = $errorLog + "[$time] Error enabling mailbox for $fullName`: $myError"
}

if($errorLog.length -eq 0){
    echo "An Active Directory account and Exchange mailbox for Mr. Example has been successfully created!"
}
else{
    foreach($event in $errorLog){
        $masterLog = $masterLog + $event
    }
}

最佳答案

PowerShell中存在终止和非终止错误。 try..catch仅捕获前者。您可以通过设置强制终止错误

... -ErrorAction Stop

用于特定命令,或
$ErrorActionPreference = Stop

整个脚本。请参阅Scripting Guy博客以获取more information

关于powershell - Powershell脚本给出错误但仍返回 “Successfully”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16991045/

相关文章:

powershell - 为什么 Powershell 在我导入私钥后将其删除?

java - Java使用proc.waitFor()调用Powershell,无法获得正确的返回码

error-handling - 为什么 Rust 的 usize 到 u128 转换被认为是失败的?

asp.net-mvc - ASP.NET MVC 4 : Handle exception caused by JsonValueProvider

jquery - 超出的最大上传文件大小将被忽略

active-directory - 通过 ldapmodify 修改 Active Directory 密码

c# - ActiveDirectory 目录搜索器 : why is FindOne() slower than FindAll() and why are properties omitted?

Powershell - 获取广告组成员 - 无法联系服务器

powershell - Get-ChildItem两次返回同一文件夹

Powershell Get-ChildItem 目录中的最新文件