【发布时间】:2016-03-14 08:17:00
【问题描述】:
我正在编写一个 Powershell 脚本,它执行我的构建/部署过程中的一个步骤,它需要在远程机器上运行一些操作。该脚本相对复杂,因此如果在该远程活动期间发生错误,我需要详细的堆栈跟踪来了解脚本中错误发生的位置(在已经生成的日志记录之上)。
问题在于 Invoke-Command 在从远程机器中继终止异常时丢失堆栈跟踪信息。如果在本地机器上调用了脚本块:
Invoke-Command -ScriptBlock {
throw "Test Error";
}
返回所需的异常详细信息:
Test Error
At C:\ScriptTest\Test2.ps1:4 char:2
+ throw "Test Error";
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Test Error:String) [], RuntimeException
+ FullyQualifiedErrorId : Test Error
但如果远程运行:
Invoke-Command -ComputerName $remoteComputerName -ScriptBlock {
throw "Test Error";
}
异常堆栈跟踪指向整个 Invoke-Command 块:
Test Error
At C:\ScriptTest\Test2.ps1:3 char:1
+ Invoke-Command -ComputerName $remoteComputerName -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Test Error:String) [], RuntimeException
+ FullyQualifiedErrorId : Test Error
我可以手动将异常传输回本地机器:
$exception = Invoke-Command -ComputerName $remoteComputerName -ScriptBlock {
try
{
throw "Test Error";
}
catch
{
return $_;
}
}
throw $exception;
但重新抛出它会丢失堆栈跟踪:
Test Error
At C:\ScriptTest\Test2.ps1:14 char:1
+ throw $exception;
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Test Error:PSObject) [], RuntimeException
+ FullyQualifiedErrorId : Test Error
如果我将异常写入输出:
$exception = Invoke-Command -ComputerName $remoteComputerName -ScriptBlock {
try
{
throw "Test Error";
}
catch
{
return $_;
}
}
Write-Output $exception;
我得到了正确的堆栈跟踪信息:
Test Error
At line:4 char:3
+ throw "Test Error";
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Test Error:String) [], RuntimeException
+ FullyQualifiedErrorId : Test Error
但由于它不在错误流中,我的构建工具没有正确识别它。如果我尝试 Write-Error,我会遇到与重新抛出异常类似的问题,并且堆栈跟踪指向脚本的错误部分。
所以我的问题是 - 如何让 Powershell 报告来自远程机器的异常,就好像它是在本地引发的一样,具有相同的堆栈跟踪信息和错误流?
【问题讨论】:
-
使用
Invoke-Command -ErrorVariable remoteerror之类的东西,那么错误流的结果应该在$remoteerror中? -
我收回
-ErrorVariable不应该包含您需要的信息。我想我有一个想法,使用throw -
this article 上的内容有帮助吗? “为了调试,在 Invoke-Command 上,使用 Enter-PSSession 可能会更好,这样你就可以在远程机器上有一个 shell 来尝试一下”
-
你不能在脚本中使用
Enter-PSSession