Run powershell command from C #

I am trying to execute powershell command from c #

gci C:\Ditectory -Recurse | unblock-file -whatif

using this code

        Runspace space = RunspaceFactory.CreateRunspace();
        space.Open();
        space.SessionStateProxy.Path.SetLocation(directoryPath);
        Pipeline pipeline = space.CreatePipeline();
        pipeline.Commands.Add("get-childitem");

        pipeline.Commands.Add("Unblock-File");
        pipeline.Commands.Add("-whatif");
        var cresult = pipeline.Invoke();
        space.Close();

I continue to receive an exception from the whatif command which is not recognized. Can i use whatif from c #

+4
source share
2 answers

WhatIfis a parameter, not a command, so it should be added to the collection of parameters of the command object for Unblock-File. However, the API API that returns void from Commands.Addbecomes inconvenient. I suggest using a small set of helper extension methods that allow you to use a syntax similar to a builder:

internal static class CommandExtensions
{
    public static Command AddCommand(this Pipeline pipeline, string command)
    {
        var com = new Command(command);
        pipeline.Commands.Add(com);
        return com;
    }

    public static Command AddParameter(this Command command, string parameter)
    {
        command.Parameters.Add(new CommandParameter(parameter));
        return command;
    }

    public static Command AddParameter(this Command command, string parameter, object value)
    {
        command.Parameters.Add(new CommandParameter(parameter, value));
        return command;
    }
}

Then your code is simple:

pipeline.AddCommand("Get-ChildItem").AddParameter("Recurse");
pipeline.AddCommand("Unblock-File").AddParameter("WhatIf");
var results = pipeline.Invoke();
space.Close();
+3
source

Source: https://habr.com/ru/post/1538663/


All Articles