简体   繁体   English

从C#执行powershell命令

[英]Execute powershell command from C#

I trying to execute this powershell command from C# 我试图从C#执行这个powershell命令

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. 关于whatif没有被识别的命令我一直有例外。 Can I use whatif from C# 我可以使用C#的whatif吗?

WhatIf is a parameter not a command, so it should be added to the Parameters collection of the command object for Unblock-File . WhatIf是一个参数而不是一个命令,所以它应该被添加到Unblock-File的命令对象的Parameters集合中。 However, this is made awkward by the API which returns void from Commands.Add . 但是,从Commands.Add返回void的API使这变得很尴尬。 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. Whatif是一个参数,而不是命令。 Try the AddParameter method instead: 请尝试使用AddParameter方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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