解决C#操作PowerShell时有时需要确认的操作不能执行问题,附操作VisualSvn权限的方法

因为需要在web端管理SVN文件夹权限,参考网上资料写了如下方法调用PowerShell,

public static List<PSObject> RunPowershell(string filePath, params string[]

parameters)

{

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

runspace.Open();

runspace.SessionStateProxy.SetVariable("ConfirmPreference", "None");

RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

Pipeline pipeline = runspace.CreatePipeline();

Command scriptCommand = new Command(filePath);

List<CommandParameter> commandParameters = new List<CommandParameter>();

foreach (var parameter in parameters)

{

if (parameter.IndexOf("=") != -1)

{

string[] namevalue = parameter.Split('=');

CommandParameter commandParm = new CommandParameter(namevalue[0], namevalue[1]);

commandParameters.Add(commandParm);

scriptCommand.Parameters.Add(commandParm);

}

else

{

CommandParameter commandParm = new CommandParameter(null, parameter);

commandParameters.Add(commandParm);

scriptCommand.Parameters.Add(commandParm);

}

}

//pipeline.Input.Write("$ConfirmPreference='None'");

pipeline.Commands.Add(scriptCommand);

List<PSObject> psObjects = new List<PSObject>();

psObjects.AddRange(pipeline.Invoke());

if (pipeline.Error.Count > 0)

{

pipeline.Error.ReadToEnd();

throw new Exception("Something is wrong in PowerShell script.");

}

runspace.Close();

return psObjects;

}

但在删除SVN权限是Powershell需要确认的动作,查了很多资料如:http://www.pstips.net/powershell-skip-confirm-prompt.html,知道了要设置环境变量才能解决.但怎么设置摸了很久,MSDN,Stack Overflow,都没有介绍.最后在codeproject看到一篇文章后尝试才解决关键代码如下:

runspace.SessionStateProxy.SetVariable("ConfirmPreference", "None");

希望帮到同样问题的人.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值