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

从C#执行含自定义Commandlet的PowerShell脚本遇执行次数异常问题

问题分析与解决方案

你遇到的核心问题是错误地混合使用了AddCommand和AddScript方法,导致你的PowerShell脚本并没有被完整执行——只有你通过AddCommand添加的那一次Get-MyParameter被调用了,脚本里的其他命令都被当成了第一个命令的参数,根本没运行。

为什么会这样?

当你调用powerShellInstance.AddCommand(new Command("Get-MyParameter"))之后,再调用AddScript(psScript),PowerShell会把脚本内容作为前一个命令的参数来处理,而不是把脚本作为独立的命令序列执行。换句话说,你的代码实际执行的是:

Get-MyParameter @"
Get-MyParameter myTasks
Start-Process notepad.exe
Get-MyParameter myTasks
Get-MyParameter myTasks
Get-MyParameter myTasks
"@

这就解释了为什么只有一次Get-MyParameter调用——剩下的脚本内容都被当成了第一个命令的输入参数,而非独立执行的命令。

修正后的C#代码

你只需要直接使用AddScript来加载并执行整个脚本即可,不需要提前用AddCommand添加Get-MyParameter。修正后的代码如下:

var powerShellInstance = PowerShell.Create();
powerShellInstance.Runspace = runSpace;

// 先导入自定义Commandlet所在的程序集
var importCommand = new Command("Import-Module");
importCommand.Parameters.Add("Assembly", Assembly.LoadFrom(@"..\CommandLets\bin\Debug\Commandlets.dll"));
powerShellInstance.Commands.AddCommand(importCommand);
powerShellInstance.Invoke();
powerShellInstance.Commands.Clear();

// 直接添加整个脚本并执行,不需要提前AddCommand
powerShellInstance.AddScript(psScript);
var result = powerShellInstance.Invoke();

// 别忘了检查执行过程中的错误
if (powerShellInstance.HadErrors)
{
    foreach (var error in powerShellInstance.Streams.Error)
    {
        Console.WriteLine($"执行错误: {error.ToString()}");
    }
}

额外注意事项

  • 确保你的自定义Commandlet已经正确标记了[Cmdlet(VerbsCommon.Get, "MyParameter")]特性,并且继承了Cmdlet基类。
  • 如果你的脚本需要传递参数,不要用AddCommand+AddScript的组合,而是可以在AddScript里直接写带参数的命令,或者用AddParameter方法配合脚本执行。
  • 每次执行完命令后清空命令集合,避免后续执行出现命令残留的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:49:53