首页 > 解决方案 > 从 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");

标签: c#wpfpowershell

解决方案


推荐阅读