Search code examples
powershellpowershell-remoting

Powershell does not display remoted executed outputs of .NET commands in Local Powershell session


I would like to pass an Error generated from a Remote PowerShell Session back to the Local Session: (This Works)

Invoke-Command -Session $DevSession -ScriptBlock {sqlps -command E:\admin\DBA\Refresh_SQL_Config_Scripts.ps1 $args[0] $args[1]; $error} -args $SQLServer, $dbName -ErrorVariable +scriptDEVerror

Problem: I would like to get it in a friendly readable format using the slightly ajusted code. I get my standard results but the $error shows as blank. Code here:

Invoke-Command -Session $DevSession -ScriptBlock {sqlps -command E:\admin\DBA\Refresh_SQL_Config_Scripts.ps1 $args[0] $args[1]; $error.tostring() } -args $SQLServer, $dbName -ErrorVariable +scriptDEVerror

Or even better would be:

Invoke-Command -Session $DevSession -ScriptBlock {sqlps -command E:\admin\DBA\Refresh_SQL_Config_Scripts.ps1 $args[0] $args[1]; $error[0].tostring() } -args $SQLServer, $dbName -ErrorVariable +scriptDEVerror

Does anyone know of a way to get this working?


Solution

  • You aren't getting anything back from $Error[0].tostring() inside the script block because Invoke-Command is redirecting the remote session's error stream to the error stream in your local session. You need to look for your error text there:

    Invoke-Command -Session $DevSession -ScriptBlock {sqlps -command E:\admin\DBA\Refresh_SQL_Config_Scripts.ps1 $args[0] $args[1] } -args $SQLServer, $dbName -ErrorVariable +scriptDEVerror
    $Error[0].tostring()
    

    Edit: Per the comments:

    $Error.clear()
    
    Invoke-Command -Session $DevSession -ScriptBlock {sqlps -command E:\admin\DBA\Refresh_SQL_Config_Scripts.ps1 $args[0] $args[1] } -args $SQLServer, $dbName -ErrorVariable +scriptDEVerror
    
    $devErrors = [array]$error
    [array]::reverse($devErrors)
    

    Should give you a reversed array of the errors from the invocation in $devErrors.