【问题标题】:PowerShell try/catch statement on olSync serverolSync 服务器上的 PowerShell tr​​y/catch 语句
【发布时间】:2013-06-20 23:33:14
【问题描述】:

我在连接到 live@edu 的 olSync 服务器上使用 PowerShell 2.0。我正在尝试使用 try/catch 语句。

为了在 live@edu 服务器上运行,我们必须运行一个使用 Import-PSSession 命令的脚本。

我遇到的问题是 try/catch 语句在我连接到另一个会话之前运行良好,但在我连接后错误没有被捕获并像正常一样显示。

(我所说的完美工作的意思是它们没有出现,而我对用户更友好的回复显示)

我错过了什么?是我对 PSSession 命令的理解不够吗?

连接代码(出于显而易见的原因,我没有包含凭据)

$Session = New-PSSession -ConfigurationName Microsoft.Exchange 
           -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred 
          -Authentication Basic -AllowRedirection  

Import-PSSession $Session

我正在测试的示例代码

$count = 0  
$name = "quit"  
$x  

do  
{   
try    
{  
    $name = Read-Host 'What is the username?'  
    $x = get-mailbox $name  
    write-host $x  
}  
catch  
{  
       Write-Host "Oh No!`n $error[0].exception"  
       $count++  
}  
}  
while ($name -ne "quit")  

write-host "$count errors happened"  

连接时输出

What is the username?: test  
test, test  

What is the username?: test2  
The operation couldn't be performed because object 'test2' couldn't be found on ...  

What is the username?: quit  
The operation couldn't be performed because object 'quit' couldn't be found on ...  

0 errors happened  
test  

.
未连接时输出

用户名是什么?:test
哦不!
术语“get-mailbox”未被识别为 cmdlet、函数、脚本文件、> 或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证
路径正确,然后重试。术语“获取邮箱”
未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。
检查名称的拼写,或者如果包含路径,请验证
路径正确,然后重试。[0].exception

【问题讨论】:

    标签: powershell try-catch powershell-2.0 powershell-remoting


    【解决方案1】:

    你得到的错误可能是一个非终止错误,try..catch 只捕获终止错误。解决方案是在终止错误中转换所有错误。这可以通过使用 ErrorAction 参数或使用$ErrorActionPreference = 'Stop'为您的脚本设置它来完成

    $x = get-mailbox $name -ErrorAction Stop
    

    hereherehere

    【讨论】:

    • 所以基本上在我连接后错误类型发生了变化,这样就不会发现错误。感谢添加,使它像我预期的那样工作
    • 是的,您遇到了另一个错误。其中一个错误正在终止,而另一个则没有。
    猜你喜欢
    • 2011-10-10
    • 2020-02-09
    • 2022-12-03
    • 1970-01-01
    • 2015-12-14
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多