【问题标题】:Powershell does not display remoted executed outputs of .NET commands in Local Powershell sessionPowershell 在本地 Powershell 会话中不显示 .NET 命令的远程执行输出
【发布时间】:2015-02-03 02:24:55
【问题描述】:

我想将远程 PowerShell 会话生成的错误传递回本地会话: (这工作)

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

问题:我想使用稍微调整的代码以易于阅读的格式获得它。我得到了标准结果,但 $error 显示为空白。 代码在这里:

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

或者更好的是:

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

有没有人知道如何让它工作?

【问题讨论】:

    标签: powershell powershell-remoting


    【解决方案1】:

    您没有从脚本块内的$Error[0].tostring() 得到任何返回,因为Invoke-Command 正在将远程会话的错误流重定向到本地会话中的错误流。您需要在那里查找错误文本:

    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()
    

    编辑:根据 cmets:

    $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)
    

    应该给你一个来自 $devErrors 调用的错误的反转数组。

    【讨论】:

    • 你是对的,谢谢,它帮助我意识到错误文本实际上被重定向到本地会话,但文本的顺序相反。所以我正在寻找的输出结果是 $Error[10].ToString() + $Error[9].ToString() 而不是 $error[0].ToString()
    • 我想现在我将有乐趣研究如何解析可能出现在数组中任何位置的错误消息字符串:(
    • 在回答中留下了建议。
    【解决方案2】:

    如果您想向scriptDEVerror 添加其他信息,则需要确保该信息是错误,如果您希望它们包含在您的 ErrorVariable 中。 $error.ToString()$error[0].ToString() 不是错误,它们是字符串。尝试使用Write-Error 将您想要的内容写入错误流,例如

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

    【讨论】:

    • 感谢您的回复以及我可以探索的另一种故障排除途径。写入错误失败并出现异常:+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
    猜你喜欢
    • 2012-01-16
    • 2021-05-10
    • 1970-01-01
    • 2014-02-23
    • 2018-05-16
    • 2014-11-03
    • 2011-01-12
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多