Sergey
Sergey

Reputation: 189

Get full stack trace from remote session

I'm using Invoke-Expression under remote session and when throws exception - it returns just RemoteException without any stack trace information. Example:

try
{
    Invoke-Expression "$command 2>&1"
}    
catch
{
    Write-Host $_    
}

If I exclude redirect error to output(2>&1) - I'm getting proper error but it call unwanted debug console(from $command), which is hidden using redirection.

Start-Process -NoNewWindow -FilePath $CmdExe -ArgumentList $Arguments

Using Start-Process I can see full stack trace but also have unwanted debug console.

How can I get a full stack trace and proper Exception from thrown exception under remote session? Thanks.

Upvotes: 7

Views: 910

Answers (2)

Dennis
Dennis

Reputation: 1790

This answer is for PowerShell 5.1 since the Windows Framework using PowerShell 3.0 is since long deprecated.

  • Firstly, you will never enter the catch section if the error is not terminating the execution (as I suspect you are already aware of), so make sure that the invoked command uses -ErrorAction Stop to force it to always terminate errors.

  • Secondly, Get-PSCallStack run directly on the console will only get a "flat" response. So you need to make it part of the function called.

function BreakThis {throw 'It broke'} #throw always teminates and has no level

function Test-MyFunction {
  try   { Invoke-Expression "BreakThis" }
  catch { Get-PSCallstack; $Write-Output $_ }
}

Test-MyFunction
  • Thirdly, Accessing sessions remotely will always have the risk of some information getting distorted or dropped due to PowerShell remoting serialization. And Get-PSCallstack seems to be among those commands that behaves differently when used in an interactive remote session.

  • Fourth, using Invoke-Expression is a bad practice and I recommend using Invoke-Command for remoting instead.

Invoke-Command -ComputerName MySrv {
  function BreakThis {throw 'It broke'}

  function Test-MyFunction {
    try   { BreakThis }
    catch { Get-PSCallstack; Write-Output $_ }
  }

  Test-MyFunction
}

But to address your concern, I would recommend you looking into the module PSFramework, from PS Gallery instead (which wasn't available when this question was asked), as it supports logging the PowerShell stack content when using Write-PSFMessage/Get-PSFMessage.

To get up and running quickly with logging legacy scripts, you might also be interested in the module PSFRedirect that redirects all PowerShell Write-* proxy command counter parts to PSFramework logs as well as performing the original command.

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201992

If you're doing a remote session, don't use write-host. Try this:

catch { 
    Write-Error ($_ | fl * -force | out-string)
}

The other option is not to catch the exception and the let error propagate back to the local session. But I suspect you want to attempt to recover?

Upvotes: 0

Related Questions