简体   繁体   中英

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#

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

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

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

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