我有一个相当复杂的脚本,其中包含Lync功能。为此,我导入了PSSession。
当其中一个命令出错时,我的错误处理会返回Lync模块中的行和命令失败(例如,行2055 $ steppablePipeline.End())而不是我的代码中的行和命令(例如,第18行启用) -CSUser)
有没有办法捕获我的调用命令和行?
以下是脚本的简化示例
Function Main
{
Try
{
LyncTest
MailboxTest
}
Catch {$rtn = ReturnErrorCatch $_ ; Return $rtn} #Return Failure
}
Function MailboxTest
{
$script:callline = (Get-PSCallStack)[1].ScriptLineNumber
Get-Mailbox "kfsjlxghkjsdh" -ErrorAction:Stop
}
Function LyncTest
{
$script:callline = (Get-PSCallStack)[1].ScriptLineNumber
Enable-CSUser "kfsjlxghkjsdh" -ErrorAction:Stop
}
Function ReturnErrorCatch ($catch)
{
If ($catch.InvocationInfo.InvocationName -eq "throw"){$errorreturn = $catch.Exception.Message.ToString()}
Else
{
$line = "Line: " + $catch.InvocationInfo.ScriptLineNumber.ToString()
$exception = $catch.Exception.Message.ToString() -replace "`n"," "
$command = "Command: " + ($catch.InvocationInfo.Line.ToString() -replace "`t","").Trim()
$activity = " (Activity: " + $catch.CategoryInfo.Activity +")"
$line = $line + "(" + $callline.ToString() + ")"
$errorreturn = $line + " " + $exception + "`r`n" + $command + $activity
}
$Output = New-Object PSObject -Property @{Result=1;ResultReason=$errorreturn}
Return $Output
}
$result = Main
$result | fl
返回:
Result : 1
ResultReason : Line: 2055(5) If SIP address type (SipAddressType) is set to None or is not set, you must specify the SIP address (SipAddress).
Command: $steppablePipeline.End() (Activity: Enable-CsUser)
在我的脚本中,我可以通过在每个子函数中放置$ script:callline行来获取调用行(更好的方法是这样做吗?),所以如果我注释掉LyncTest并运行mailboxtest,我会得到预期的错误返回错误命令,失败的行以及调用函数的行。
由于这是针对Exchange 2010的,我不能使用任何Powershell V3功能,它必须是V2。