简体   繁体   中英

How to Pipe Powershell Commands together in C#

I have a set of commands in Powershell 2 where the output of one function is the input to the next function, but in the output of the first function I can select a value from the result, which is to be the input to the next function.

For example with

Get-RDUserSession | ? {$_.username -eq "myuser"} | Disconnect-User

My example, I am selecting a user called "myuser", and passing this user into a function called Disconnect-User to do something. All works in Powershell, but I would like to be able to replicate this in C# without having to write multiple lines of code.

Is it possible to reproduce this in C# in one line like in Powershell?

Sure, you'd end up with something like (multiline to make it more readable on SO; though I also prefer to format my code like that 'in real life'):

GetRDUserSessionMethod().Where(u => u.username == "myuser")
                        .ToList()
                        .ForEach(DisconnectUser);

GetRDUserSessionMethod() would simply have to return an IEnumerable<SomeUserClass> .

ToList() is required because MS never decided to have such an extension method on IEnumerable<T> , which for various reasons (type safety!) would be a nice addition to the language. It's pretty trivial to write one yourself if you want to avoid doing a ToList() each time, quick and dirty example:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach (T element in source)
    { 
        action(element);
    }
}

There can be some discussion on whether this is more readable than a regular foreach { } statement - probably as many opinions as devs out there. Personally, I don't have an issue with writing code like that.

command1 && command2

Say to restart a service named "XYZ" using c#

net stop "XYZ" && net start "XYZ"

Code Example is,

using (Process command = new Process())
{        
    command.StartInfo = new ProcessStartInfo
    {
        CreateNoWindow = true,
        FileName = CommonStrings.RestartProccesCommand,
        Arguments = COMMAND1 && COMMAND2,
        LoadUserProfile = false,
        UseShellExecute = false,
        WindowStyle = ProcessWindowStyle.Hidden,
    };
    command.Start();
    command.WaitForExit(3000);
    exitCode = command.ExitCode;
}

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