在我的 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,我认为这是不好的行为,所以我将用它来包装我的函数,并将 Users 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");
}
现在我们的功能可以运行并且我们不会篡改用户的系统设置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)