使用自动化DLL在c#中调用ps脚本文件

时间:2018-01-10 14:07:38

标签: c# powershell

我正在尝试使用System.Management.Automation使用C#中的参数调用Powershell脚本文件,如下所示:

using (var ps = PowerShell.Create())
{
    try
    {
        var script = System.IO.File.ReadAllText("MyPsFile.ps1");
        ps.Commands.AddScript(script);
         ps.AddScript(script);
        ps.AddParameter("MyKey1", value1);
        ps.AddParameter("MyKey2", value2);
        var results = ps.Invoke();
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

Powershell文件如下所示:

function MyFunction {
    Param (
        [Parameter(Mandatory=$true)][string] $MyKey1,
        [Parameter(Mandatory=$true)][string] $MyKey1,
    )
    Process {        
      ..do some stuff
    }
}
MyFunction $args[0] $args[1]

如果我在Powershell中运行脚本文件,如下所示:

powershell -file MyPsFile.ps1 "Value1" "Value2"

工作正常。但是从C#中调用该文件是行不通的。知道为什么吗?

所以我已经像这样更新了代码

var runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();

                    var runSpaceInvoker = new RunspaceInvoke(runspace);
                    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

                    // create a pipeline and feed it the script text
                    var pipeline = runspace.CreatePipeline();
                    var command = new Command(@". .\MyScript.ps1");
                    command.Parameters.Add("MyParam1", value1);
                    command.Parameters.Add("MyParam2", value2);
                    pipeline.Commands.Add(command);

                    pipeline.Invoke();
                    runspace.Close();

但我收到错误Powershell ps1文件“无法识别为cmdlet,函数,可操作程序或脚本文件。”

我发现了Powershell ps1 file "is not recognized as a cmdlet, function, operable program, or script file."

但它没有解决问题。知道还有什么可能导致这个错误吗?

1 个答案:

答案 0 :(得分:0)

最后我找到了解决方案。两件事情: 此代码解决了“未被识别为cmdlet,函数,可操作程序或脚本文件错误。感谢Problem with calling a powershell function from c#

using (var runspace = RunspaceFactory.CreateRunspace())
{
    try
    {
        var script = File.ReadAllText("MyScript.ps1");
        runspace.Open();
        var ps = PowerShell.Create();
        ps.Runspace = runspace;
        ps.AddScript(script);
        ps.Invoke();
        ps.AddCommand("MyFunction").AddParameters(new Dictionary<string, string>
        {
            { "Param1" , value1},
            { "Param2", value2},
            { "Param3", value3},            
        });

        foreach (var result in ps.Invoke())
        {
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

重要的是,我还必须从脚本文件中删除进程包装器属性

****MyScripts.ps1

    function MyFunction 
    {
        Param (
            [Parameter(Mandatory=$true)][string] myParam1,        
            [Parameter(Mandatory=$true)][string] myParam2,        
            [Parameter(Mandatory=$true)][string] myParam3,  
        )
        //  Removing the Process wrapper solved the problem, the code didn't run with it 
        Process {     
            //DOSTUFF
        }
    }
相关问题