【发布时间】: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