[英]Execute powershell command from C#
我试图从C#执行这个powershell命令
gci C:\Ditectory -Recurse | unblock-file -whatif
使用此代码
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();
关于whatif没有被识别的命令我一直有例外。 我可以使用C#的whatif吗?
WhatIf
是一个参数而不是一个命令,所以它应该被添加到Unblock-File
的命令对象的Parameters集合中。 但是,从Commands.Add
返回void的API使这变得很尴尬。 我建议使用一小组辅助扩展方法,这将允许您使用类似构建器的语法:
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;
}
}
那你的代码很简单:
pipeline.AddCommand("Get-ChildItem").AddParameter("Recurse");
pipeline.AddCommand("Unblock-File").AddParameter("WhatIf");
var results = pipeline.Invoke();
space.Close();
Whatif是一个参数,而不是命令。 请尝试使用AddParameter
方法:
http://msdn.microsoft.com/en-us/library/dd182433(v=vs.85).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.