无法从 C# 调用 Powershell 函数 [英] Unable to call a Powershell function from C#
问题描述
C# 代码:C# 代码无法调用存在于 powershell 脚本中的函数 Trial2,尽管它之前已被执行.
C# Code: The C# code is unable to call the function Trial2 which is present in the powershell script although it is being executed before.
StringBuilder sb = new StringBuilder();
PowerShell psExec = PowerShell.Create();
psExec.AddScript(@ "C:\Users...\sc.ps1");
psExec.AddCommand("Trial2").AddParameter("a", "Ram");
Collection < PSObject > results;
Collection < ErrorRecord > errors;
results = psExec.Invoke();
errors = psExec.Streams.Error.ReadAll();
if (errors.Count > 0) {
foreach(ErrorRecord error in errors) {
sb.AppendLine(error.ToString());
}
} else {
foreach(PSObject result in results) {
sb.AppendLine(result.ToString());
}
}
Console.WriteLine(sb.ToString());
Powershell 脚本:
Powershell Script:
function Trial2($a){
"Yes! $a";
}
我得到的错误:
我在 Powershell 中也将 Set-ExecutionPolicy 设置为 Unrestricted.
I have Set-ExecutionPolicy to Unrestricted in the Powershell as well.
提前致谢!
推荐答案
Mathias R. Jessen 有在他的评论中提供了所有必要的提示,但让我把它们放在一起:
Mathias R. Jessen has provided all the necessary pointers in his comments, but let me put it all together:
PowerShell psExec = PowerShell.Create();
// Add a script block that dot-sources (.) your .ps1 file,
// which in turn defines the Trial2 function.
psExec.AddScript(@". C:\Users...\sc.ps1");
// Start a new statement to ensure that the dot-sourcing is performed
// before additional commands are executed.
psExec.AddStatement();
// Now you can add a command that calls your Trial2 function.
psExec.AddCommand("Trial2").AddParameter("a", "Ram");
// ...
请注意,API 是流畅的,因此您可以使用单个语句;下面演示了这一点,并且还展示了如何直接通过 API 设置执行策略,而不是通过提交 Set-ExecutionPolicy
命令,如您最初尝试:
Note that the API is fluent, so you could use a single statement; the following demonstrates this, and also shows how to set the execution policy directly via the API rather than by submitting a Set-ExecutionPolicy
command, as you originally attempted:
// Create an initial default session state.
var iss = System.Management.Automation.Runspaces.InitialSessionState.CreateDefault2();
// Set its script-file execution policy.
iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
// Create a PowerShell instance with a runspace based on the
// initial session state.
PowerShell psExec = PowerShell.Create(iss);
psExec
.AddScript(@". C:\Users...\sc.ps1")
.AddStatement()
.AddCommand("Trial2").AddParameter("a", "Ram");
// ...
请注意,以这种方式设置执行策略相当于使用Set-ExecutionPolicy
-范围过程
.这意味着它将对从当前进程启动的所有 PowerShell 会话保持有效.
Note that setting the execution policy this way is the equivalent of setting it with
Set-ExecutionPolicy
-Scope Process
. This means that it'll stay in effect for all PowerShell sessions started from the current process.
这篇关于无法从 C# 调用 Powershell 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!