[英]Invoking powershell script within c# that calls another powershell script is throwing an UnauthorizedAccessException
下面的功能適用於我的測試
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對象而不是腳本文件的內容?
試驗后,確定我可以簡單地多次調用我的函數。 一次設置策略,下次調用任何腳本。 該政策似乎是在一次通話后設置的。
RunScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy ByPass");
RunScript(File.ReadAllText("test.ps1"));
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();
}
您還可以排隊命令,即
private static void RunScript(string scriptText)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy ByPass");
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.