c# - 从 WPF 应用程序启用 PS ExecutionPolicy
问题描述
我想将 powershell 执行设置为不受脚本本身的限制。
我在控制台应用程序中有工作版本。它看起来像这样:
public static void SetPowerShellExecuteUnrestricted()
{
try
{
RunspaceInvoke scriptInvoker = new RunspaceInvoke();
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
但现在我在 WPF 应用程序中需要相同的内容。上面的代码不起作用。所以我尝试了不同的版本,例如:通过 RunspaceFactory:
Runspace rs;
rs = RunspaceFactory.CreateRunspace();
rs.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Set-ExecutionPolicy Unrestricted");
ps.Runspace = rs;
ps.Invoke();
}
这将捕获异常:“Set-ExecutionPolicy”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。但是这个 cmdlet 通常在 powershell 控制台中工作。
我什至尝试像这样从 Windows cmd 执行此操作:
string strCmdText = "/C PowerShell.exe Set-ExecutionPolicy Unrestricted";
Process.Start("CMD.exe", strCmdText);
但是这种方式 cmd 窗口会闪一下然后 disseaper 但执行策略没有改变。
有没有人处理类似的问题并可以提供帮助?
谢谢
//EDIT 25.08.2019 21:10 又尝试了一件事,但没有成功:
void CreateScript()
{
string path = @"C:\Windows\Temp\ExecPolicy.ps1";
if (!File.Exists(path))
{
using (StreamWriter sw = new StreamWriter(File.Open(path, FileMode.CreateNew), Encoding.Unicode))
{
sw.WriteLine("Set-ExecutionPolicy Unrestricted");
}
}
}
void RunPowershellScript(string PathToScript)
{
string strCmdText;
strCmdText = PathToScript;
Process.Start("C:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe ", strCmdText);
}
CreateScript();
System.Threading.Thread.Sleep(2000);
RunPowershellScript(@"C:\Windows\Temp\ExecPolicy.ps1");
使用脚本创建文件,然后使用 powershell 运行它。但没有成功。你不能运行它导致它被那个 ExecutionPolicy 禁用......
//编辑 25.08.2019 21:55
好的,伙计们,我想通了。
这是解决方案:您需要像这样制定命令:
ps.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted").AddParameter("Scope", "CurrentUser");
解决方案
推荐阅读
- ionic-framework - 在 ION-SELECT 上应用 PICKER FORMAT
- amazon-web-services - Amazon RDS:备份和还原到现有数据库实例上的新数据库
- typescript - 模板文字中的 Array.map 为多个媒体查询呈现 css 规则?
- reactjs - 本机基础选择器图标不可点击
- performance - Unity - 提高网格生成和渲染性能
- dns - 通过一个提供商提供域名,通过另一个提供商托管,通过另一个提供商发送电子邮件
- selenium - 在本地浏览器中单击 selenium 中的元素,在浏览器堆栈中的其他位置显示“陈旧元素错误”?
- jenkins - Jenkins 在 devops 管道中的位置如何?
- java - 杰克逊 ObjectMapper 休眠问题
- android - BroadcastReceiver 如何工作属于应用状态?