从 C# 启用 PowerShell 的执行策略

编程入门 行业动态 更新时间:2024-10-19 00:27:07
本文介绍了从 C# 启用 PowerShell 的执行策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个调用 PowerShell 的 ASP.NET MVC 4 页面.但是,我遇到了一个问题,因为我使用的模块没有签名,所以我必须启用 Unrestricted 策略.如何强制 PowerShell 子级使用 Unrestricted 策略?

I have an ASP.NET MVC 4 page that calls a piece of PowerShell. However, I am running into a problem as a module I am using is not signed, so I have to enable the Unrestricted policy. How can I force the PowerShell child to use Unrestricted policy?

我在我的脚本中启用了它,但它被忽略了.此外,当我尝试在代码中设置策略时,会引发异常.

I have enabled this in my script, but it is ignored. Also when I try to set the policy in code, an exception is thrown.

using (Runspace myRunSpace = RunspaceFactory.CreateRunspace()) { myRunSpace.Open(); using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = myRunSpace; powerShell.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted"); powerShell.AddScript(script); objectRetVal = powerShell.Invoke(); } }

推荐答案

如果您只需要运行一个脚本而无需交互,您可以通过命令提示符设置执行策略,如下所示:

If you only need to run the one script with no interactions you can set the execution policy via the command prompt like so:

string command = "/c powershell -executionpolicy unrestricted C:\script1.ps1"; System.Diagnostics.Process.Start("cmd.exe",command);

更多推荐

从 C# 启用 PowerShell 的执行策略

本文发布于:2023-11-29 20:24:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647531.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:策略   PowerShell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!