使用System.Management.Automation调用Powershell时,如何从远程命令传递警告流和详细流?

时间:2019-01-09 10:19:36

标签: c# powershell virtual-machine

我正在尝试使用C#中的PowerShell远程(在本地虚拟机上或使用网络)调用命令。我正在使用https://www.nuget.org/packages/Microsoft.PowerShell.5.ReferenceAssemblies/

中的System.Management.Automation库

由于我未知的原因,警告和详细消息不会重新登录。

在C#中本地调用commnd时,效果很好。

Program output

我尝试了各种与流相关的设置($ verbosepreference,$ warningpreference),但我不认为它们是相关的-从控制台调用PowerShell时不存在此问题。

我已经检查了到虚拟机的远程连接(Invoke-Command的-VmName参数)和网络中的计算机(Invoke-Command的-ComputerName参数)-都遇到了这个问题。

我尝试在PowerShell Invoke()中找到一些魔术开关来使这些流通过-我发现了一个名为RemoteStreamOptions(https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.remotestreamoptions?view=powershellsdk-1.1.0)的东西,但设置它并没有帮助。

有什么我可以做的事吗?

namespace ConsoleApp2
{
using System;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security;

class Program
{
    static void Main(string[] args)
    {
        var script = @"
        $VerbosePreference='Continue' #nope, it's not about these settings
        $WarningPreference = 'Continue'
        Write-Host "" ------- $env:computername  ------- ""
        Write-Warning ""Write warning directly in warn script""
        Write-Error ""Write error directly in warn script""
        Write-Verbose ""Write verbose directly in warn script"" -verbose
        Write-Host ""Write host directly in warn script""   
        Write-Information ""Write Information in warn script""
        ";


        Call(script, command =>
            {
                SecureString password = new SecureString();
                "admin".ToCharArray().ToList().ForEach(c => password.AppendChar(c));
                command.Parameters.Add("Credential", new PSCredential("admin", password));
                command.Parameters.Add("VmName", new[] { "190104075839" });
            }
    );
        Call(script);
    }

    private static void Call(string script, Action<Command> addtionalCommandSetup = null)
    {
        using (var shell = PowerShell.Create())
        {
            shell.Streams.Information.DataAdded += LogProgress<InformationRecord>;
            shell.Streams.Warning.DataAdded += LogProgress<WarningRecord>;
            shell.Streams.Error.DataAdded += LogProgress<ErrorRecord>;
            shell.Streams.Verbose.DataAdded += LogProgress<VerboseRecord>;
            shell.Streams.Debug.DataAdded += LogProgress<DebugRecord>;



            var command = new Command("Invoke-Command");
            command.Parameters.Add("ScriptBlock", ScriptBlock.Create(script));
            addtionalCommandSetup?.Invoke(command);
            shell.Commands.AddCommand(command);
            shell.Invoke();
            Console.ReadKey();
        }
    }

    private static void LogProgress<T>(object sender, DataAddedEventArgs e)
    {
        var data = (sender as PSDataCollection<T>)[e.Index];
        Console.WriteLine($"[{typeof(T).Name}] {Convert.ToString(data)}");
    }
}
}

1 个答案:

答案 0 :(得分:1)

我认为问题可能是您正在使用var shell = PowerShell.Create()创建本地PowerShell会话,然后使用Invoke-Command创建了一个单独的远程会话,并且流没有正确传递。如果您直接创建一个远程会话,它可以正常工作。这是使用远程运行空间的代码的简化版本:

namespace ConsoleApp2
{
    using System;
    using System.Linq;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    using System.Security;

    class Program
    {
        static void Main(string[] args)
        {
            var script = @"
            Write-Host ""-------$env:computername-------""
            Write-Warning ""Write warning directly in warn script""
            Write-Error ""Write error directly in warn script""
            Write-Verbose ""Write verbose directly in warn script"" -verbose
            Write-Host ""Write host directly in warn script""
            Write-Information ""Write Information in warn script""
            ";

            SecureString password = new SecureString();
            "Password".ToCharArray().ToList().ForEach(c => password.AppendChar(c));
            PSCredential credentials = new PSCredential("UserName", password);

            WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
            connectionInfo.ComputerName = "TargetServer";
            connectionInfo.Credential = credentials;

            using (var shell = PowerShell.Create())
            {
                using (var runspace = RunspaceFactory.CreateRunspace(connectionInfo))
                {
                    runspace.Open();

                    shell.Runspace = runspace;

                    shell.Streams.Information.DataAdded += LogProgress<InformationRecord>;
                    shell.Streams.Warning.DataAdded += LogProgress<WarningRecord>;
                    shell.Streams.Error.DataAdded += LogProgress<ErrorRecord>;
                    shell.Streams.Verbose.DataAdded += LogProgress<VerboseRecord>;
                    shell.Streams.Debug.DataAdded += LogProgress<DebugRecord>;

                    shell.AddScript(script);
                    shell.Invoke();
                }
            }

            Console.ReadKey();
        }

        private static void LogProgress<T>(object sender, DataAddedEventArgs e)
        {
            var data = (sender as PSDataCollection<T>)[e.Index];
            Console.WriteLine($"[{typeof(T).Name}] {Convert.ToString(data)}");
        }
    }
}