从c#运行仅签名的powershell脚本

Dan*_*ghe 5 c# powershell executionpolicy

我有一个Windows服务,下载脚本,然后运行它.

我一直在努力使我的Windows服务更安全,使它只接受签名的power-shell脚本.

我在服务器上运行了Set-ExecutionPolicy AllSigned命令,这可以在windows power shell命令提示符下运行.

但是,即使set-executionpolicy设置为restricted,我的代码仍会运行有符号和无符号脚本.

我尝试了两种方法:

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();

        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        Pipeline pipeline = runspace.CreatePipeline();         
        pipeline.Commands.AddScript(@"Set-ExecutionPolicy AllSigned");
        pipeline.Commands.AddScript(@"Get-ExecutionPolicy");
        pipeline.Commands.AddScript(script);
        Collection<PSObject> results = pipeline.Invoke();
Run Code Online (Sandbox Code Playgroud)

另一种方法:

using (PowerShell ps = PowerShell.Create())
                {
                    ps.AddCommand("Set-ExecutionPolicy").AddArgument("Restricted");
                    ps.AddScript("Set-ExecutionPolicy Restricted");
                    ps.AddScript(script);
                    Collection<PSObject> results = ps.Invoke();
                  }
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,代码也会运行未签名的脚本.

我错过了什么吗?

Dan*_*ghe 1

我找到了解决方案。限制代码运行未签名脚本的唯一方法是使用 Get-AuthenticodSignature 自行检查脚本:

 public bool checkSignature(string path)
    {

        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(String.Format("Get-AuthenticodeSignature \"{0}\"", path));
        Collection<PSObject> results = pipeline.Invoke();
        Signature check = (Signature)results[0].BaseObject;
        runspace.Close();
        if (check.Status == SignatureStatus.Valid)
        {
            return true;
        }
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

谢谢,