user3373870
user3373870

Reputation: 1466

Execute powershell command from C#

I trying to execute this 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 keep getting an exception about the whatif not being recognized command. Can I use whatif from C#

Upvotes: 3

Views: 3396

Answers (2)

Mike Zboray
Mike Zboray

Reputation: 40788

WhatIf is a parameter not a command, so it should be added to the Parameters collection of the command object for Unblock-File. However, this is made awkward by the API which returns void from Commands.Add. I suggest a using a small set of helper extension methods which will allow you to use a builder-like syntax:

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();

Upvotes: 3

Andy Arismendi
Andy Arismendi

Reputation: 52567

Whatif is a parameter, not a command. Try the AddParameter method instead:

http://msdn.microsoft.com/en-us/library/dd182433(v=vs.85).aspx

Upvotes: 1

Related Questions