在C#中使用自定义PowerShell模块

时间:2013-09-18 10:33:45

标签: c# powershell

我写了这样的函数PowerShell模块:

    Function docConvert2{
         param ([string]$sourceFile, [string]$sourceFilePath)
         ....
         ....
    }

我已成功导入模块

enter image description here

我可以在powershell cmdlet中使用模块

enter image description here

当我在c#中尝试调用函数时,我得到了类似的异常

  

术语“docConvert2”未被识别为cmdlet,函数,脚本文件或可操作程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。

C#代码

        PowerShell pShell = PowerShell.Create();
        pShell.Commands.AddCommand("import-module").AddParameter("Name", "DocConverter2");
        pShell.Invoke();//works correctly
        pShell.AddCommand("docConvert2");
        pShell.AddParameter("sourceFile", "'addendum no-3_PREP.doc'");
        pShell.AddParameter("sourceFilePath", @"'D:\New\wordler'");
        pShell.Invoke();//throw exception

我的错误是什么?

2 个答案:

答案 0 :(得分:1)

尝试:

PowerShell pShell = PowerShell.Create();
pShell.Commands.AddCommand("import-module").AddParameter("Name","DocConverter2");
pShell.Invoke();
...
rest of you code here
...

您还可以使用InitialSessionState预加载模块:read here

答案 1 :(得分:0)

在实例化pShell对象后,您需要导入模块,就像在命令行中一样。

尝试在第1行和第1行之间执行以下操作2。

        ps.AddScript(@"import-module DocConverter2");
        ps.Invoke();

确保您的C#应用​​程序可以访问PSM所在的路径。