You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用已执行PowerShell脚本中的Trial2函数失败问题求助

问题根因

默认情况下PowerShell执行外部.ps1脚本时,脚本内部定义的函数、变量仅在脚本自身的作用域内生效,脚本执行完成后对应内容会被回收,因此后续通过AddCommand添加的函数调用无法识别到Trial2函数。

解决方案

推荐使用点源加载的方式运行脚本,点源运算符(.)会将脚本的所有内容导入到当前PowerShell会话的作用域,脚本中定义的函数执行完后依然可以被调用。

修改C#代码中脚本加载的语句,在脚本路径前加.加空格即可:

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());

如果你的脚本路径包含空格,需要用引号将路径包裹,写法如下:

psExec.AddScript(@". ""C:\Users\路径包含空格\sc.ps1""");

替代方案

你也可以将脚本执行和函数调用合并为同一段脚本传入,无需分开调用:

PowerShell psExec = PowerShell.Create();
psExec.AddScript(@"C:\Users...\sc.ps1; Trial2 -a 'Ram'");
// 直接执行即可,无需单独调用AddCommand

内容的提问来源于stack exchange,提问作者Amrit Ohri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 23:36:04