[英]Running Powershell from C# gives error: `running scripts is disabled on this system`
在我的 C# 应用程序中,我尝试创建一个RunSpace
来调用一些 Powershell 脚本。 但是,当它到达实际创建它的代码时,它失败并出现以下错误:
var implementedHost = new implementedPSHost();
using (var rs = RunspaceFactory.CreateRunspace(customPSHost))
{
cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.At line:1 char:3+ . .\\Scripts\\loadFunctions.ps1+
正如其他地方所建议的,我运行了一个 Powershell 窗口并执行了Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
但这没有帮助。 错误仍然发生。 有没有人有任何想法如何解决这个问题?
尝试在运行空间中运行Set-ExecutionPolicy -Scope CurrentUser
步骤,如下所示。
首先,将此用户的 ExecutionPolicy 设为受限,当我运行此代码时,我看到以下错误:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
//scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser ");
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command("C:\\temp\\test.ps1");
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
}
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted");
给我
System.Management.Automation.PSSecurityException: '文件 C:\\temp\\test.ps1 无法加载,因为在此系统上禁用了运行脚本。 有关详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkID=135170 上的 about_Execution_Policies。
接下来,我重新运行它,取消注释这一行:
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser ");
而且,没有错误! 但是,这会改变用户 ExecutionPolicy ,我认为这是不好的行为,所以我打算用它来包装我的函数,并将用户 ExecutionPolicy 设置回我发现它的方式。
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("$ExecutionPolicy = Get-ExecutionPolicy -Scope CurrentUser");
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser ");
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command("C:\\temp\\test.ps1");
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser $ExecutionPolicy -Force");
}
现在我们的功能可以工作了,我们不会篡改用户的系统设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.