【发布时间】:2020-09-11 08:12:18
【问题描述】:
下面的函数很适合我的测试
private static void RunScript(string scriptText)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
}
我这样称呼这个函数
RunScript(File.ReadAllText("test.ps1"));
一切都很好。现在我已经修改了 test.ps1 以调用其他 powershell 脚本。
但是现在我运行它时遇到异常。
UnauthorizedAccessException: 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.
我猜我需要将执行策略设置为“绕过”。我该如何设置?
还有没有办法将 powershell 脚本文件名提供给 Pipeline 对象而不是脚本文件的内容?
【问题讨论】:
-
Set-ExecutionPolicy -ExecutionPolicy ByPass -
为什么要从 C# 调用 PowerShell 脚本而不是本机函数?
-
它与运行外部 powershell 脚本以供其他人扩展功能的解决方案有关。
-
我知道调用 powershell 的命令,但我想知道如何通过 c# powershell API 指定它?
标签: c# powershell runspace