Powershell远程没有标准输出

Powershell remote no standard output

我在 C# 中使用 PowerShell 对象来执行远程命令。我想要获取值的示例命令是 Get-ExecutionPolicy,但没有返回标准输出。

最终目标是在远程实例上获取剩余磁盘 space。

这是我用来远程执行脚本的代码。它工作正常,按预期安静地执行所有测试,输出错误和异常,但是......没有标准输出。有人可以帮忙吗?

PowerShell ps = PowerShell.Create();
logger.LogAndDisplay(Logger.MessageType.Note, "Connecting to '" + instance0 + "'");
logger.LogAndDisplay(Logger.MessageType.Note, "Executing script on remote: '" + path0 + "'.");
ps.AddScript("$password = convertto-securestring -asplaintext -force -string " + pass);
ps.AddScript("$credential = new-object -typename system.management.automation.pscredential -argumentlist " + user + ", $password");
ps.AddScript("$session = new-pssession " + instance0 + " -credential $credential");
ps.AddScript("Invoke-Command -Session $session -FilePath " + path0);
ps.AddScript("Remove-PSSession $session");
Execute(ps);

private bool Execute(PowerShell ps0)
{
    bool success = true;

    PSOutput.Clear();
    PSOutput = ps0.Invoke();

    if (ps0.HadErrors)
    {
        success = false;
        PSDataCollection<ErrorRecord> PSErrors = ps0.Streams.Error;
        foreach (ErrorRecord e in PSErrors)
        {
            logger.LogAndDisplay(Logger.MessageType.Note, e.ToString());
        }
    }

    if (PSOutput.Count() > 0)
    {
        logger.LogAndDisplay(Logger.MessageType.Subheader, "Command output:");
    }

    foreach (PSObject outputItem in PSOutput)
    {
        if (outputItem != null)
        {
            logger.LogAndDisplay(Logger.MessageType.Note, outputItem.BaseObject.GetType().FullName);
            logger.LogAndDisplay(Logger.MessageType.Note, outputItem.BaseObject.ToString() + "\n");
        }
    }

    logger.LogAndDisplay(Logger.MessageType.Note, "Command complete. Disconnecting.");
    ps0.Dispose();
    return success;
}

问题出在这一行:

ps.AddScript("Remove-PSSession $session");

The Remove-PSSession cmdlet closes Windows PowerShell sessions (PSSessions) in the current session. It stops any commands that are running in the PSSessions, ends the PSSession, and releases the resources that the PSSession was using. If the PSSession is connected to a remote computer, Remove-PSSession also closes the connection between the local and remote computers.

(强调我的)

显然,这包括流。

我在搜索过程中偶然发现 ths interesting post PowerShell 输出,它也可以回答一些未来的问题。