C# 仅从c运行已签名的powershell脚本#
我有一个windows服务,可以下载一个脚本,然后运行它 我一直在努力使我的windows服务更加安全,使它只接受已签名的power shell脚本 我已经在服务器上运行了Set-ExecutionPolicy-AllSigned命令,这可以在windows power shell命令提示符下运行 但是,即使set executionpolicy设置为restricted,我的代码仍然同时运行有符号和无符号脚本 我尝试了两种方法: RunspaceConfiguration RunspaceConfiguration=RunspaceConfiguration.Create()C# 仅从c运行已签名的powershell脚本#,c#,powershell,executionpolicy,C#,Powershell,Executionpolicy,我有一个windows服务,可以下载一个脚本,然后运行它 我一直在努力使我的windows服务更加安全,使它只接受已签名的power shell脚本 我已经在服务器上运行了Set-ExecutionPolicy-AllSigned命令,这可以在windows power shell命令提示符下运行 但是,即使set executionpolicy设置为restricted,我的代码仍然同时运行有符号和无符号脚本 我尝试了两种方法: RunspaceConfiguration RunspaceCo
Runspace Runspace=RunspaceFactory.CreateRunspace(runspaceConfiguration);
Open();
RunspaceInvoke scriptInvoker=新的RunspaceInvoke(运行空间);
Pipeline Pipeline=runspace.CreatePipeline();
pipeline.Commands.AddScript(@“Set ExecutionPolicy AllSigned”);
pipeline.Commands.AddScript(@“Get ExecutionPolicy”);
pipeline.Commands.AddScript(脚本);
收集结果=pipeline.Invoke();
另一种方法是:
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Set-ExecutionPolicy").AddArgument("Restricted");
ps.AddScript("Set-ExecutionPolicy Restricted");
ps.AddScript(script);
Collection<PSObject> results = ps.Invoke();
}
使用(PowerShell ps=PowerShell.Create())
{
ps.AddCommand(“设置执行策略”).AddArgument(“受限”);
ps.AddScript(“设置执行策略受限”);
ps.AddScript(脚本);
收集结果=ps.Invoke();
}
在这两种情况下,代码也运行未签名脚本
我错过了什么吗?我找到了解决办法。限制代码运行未签名脚本的唯一方法是亲自使用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;
}
public bool checkSignature(字符串路径)
{
Runspace Runspace=RunspaceFactory.CreateRunspace();
Open();
RunspaceInvoke scriptInvoker=新的RunspaceInvoke(运行空间);
Pipeline Pipeline=runspace.CreatePipeline();
pipeline.Commands.AddScript(String.Format(“Get-Authenticode签名\“{0}\”,path));
收集结果=pipeline.Invoke();
签名检查=(签名)结果[0]。BaseObject;
runspace.Close();
if(check.Status==SignatureStatus.Valid)
{
返回true;
}
返回false;
}
谢谢
Dan服务器是64位o.s.?是的,@C.B.它是64位Windows server 2008R2
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;
}