简体   繁体   中英

How to pass Warning and Verbose streams from a remote command when calling powershell using System.Management.Automation?

I am trying to invoke a command remotely (either on a local virtual machine or using the network) using PowerShell in C#. I am using the System.Management.Automation library from https://www.nuget.org/packages/Microsoft.PowerShell.5.ReferenceAssemblies/

For reasons unknown to me, the warnings and verbose messages are not logged back.

When invoking the commnd locally in C#, it works fine.

程序输出

I've tried various stream related settings ($verbosepreference, $warningpreference) but I do not think that they are related - this problem does not exist when calling PowerShell from the console.

I've checked both a remote connection to a virtual machine (-VmName parameter of Invoke-Command) and a computer in the network (-ComputerName parameter of Invoke-Command) - both suffer from that problem.

I've tried finding some magic switch in PowerShell Invoke() that would make those streams be passed - I found a thing called RemoteStreamOptions ( https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.remotestreamoptions?view=powershellsdk-1.1.0 ) but setting it did not help.

Is there any thing I can do to make it work?

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)}");
    }
}
}

I think the issue might be that you are creating a local PowerShell session with var shell = PowerShell.Create() , which then creates a separate remote session with Invoke-Command and the streams are not being passed through properly. If you create a remote session directly, it works fine. Here is a simplified version of your code that uses a remote runspace:

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)}");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM