0

多くのPowerShellコマンドレットを含む.ps1ファイルからPowerShellコマンドレットを実行するコードがあります...実行すると、次の例外が発生します。

「New-BuildCVFromSql」という用語は、コマンドレット、関数、スクリプトファイル、または操作可能なプログラムの名前として認識されません。名前のスペルを確認するか、パスが含まれている場合は、パスが正しいことを確認して、再試行してください。

private void RunPowerShellCommandToBuildCV()
{
    string BigWindow = "";
    string FileNamePopup = "";

    TestPopup(ref BigWindow, ref FileNamePopup);

    string psScriptPath = @"D:\Project Files\CIS3G\Webapp\_Powershell\JcdcCv.psm1";
    string psScript = string.Empty;

    if(File.Exists(psScriptPath))
        psScript = File.ReadAllText(psScriptPath);
    else
        throw new FileNotFoundException("Wrong path for the script file");

    // Init the PowerShell runspace and pipeline - EWB
    Runspace runSpace = RunspaceFactory.CreateRunspace();
    runSpace.Open();

    // Set execution policy - EWB
    RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace);
    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

    Pipeline pipeline = runSpace.CreatePipeline();

    // I tried loading it both of the ways below and had no joy load the script from the string - EWB
    //pipeline.Commands.AddScript(psScript);

    // Load as file - EWB
    pipeline.Commands.AddScript(psScriptPath, false);

    // Add the outstring command to the pipeline.
    pipeline.Commands.Add("Out-String");

    Command myCommand = new System.Management.Automation.Runspaces.Command("New-BuildCVFromSql");

    CommandParameter SqlOrExcelFile                          = new CommandParameter("SqlOrExcelFile", @"C:\Documents and Settings\Brown.Ericw\My Documents\tempeval.sql");
    CommandParameter Js                                      = new CommandParameter("Js", "JCDC");
    CommandParameter FileName                                = new CommandParameter("FileName", @"Evaluation\EvaluationFormPartialListVM");

    myCommand.Parameters.Add(SqlOrExcelFile);
    myCommand.Parameters.Add(Js);
    myCommand.Parameters.Add(FileName);

    pipeline.Commands.Add(myCommand);

    Collection<PSObject> output = pipeline.Invoke();
    //foreach (PSObject psObject in output)
    //{

    //System.Diagnostics.Debug.WriteLine ("Object name: " + psObject.);
    //}
}

したがって、このスクリプトファイルを正しくロードしていないようです。PowerShell ISE / IDEでは、コマンドを実行する前にスクリプトを実行する必要があります。それは私が間違っていることですか?

他の人が書いた一連のPowerShellスクリプトの上にインターフェイスを配置しようとしているだけなので、他の人が他の場所で使用しているため、そのスクリプトファイルを実際に変更することはできません...

.ps1ファイル内で、私が呼び出そうとしているコマンドレットは次のように定義されています。

# Create CV Method #

function New-BuildCVFromSql {
  param([Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]$SqlFile,
        [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]$js,
        [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]$FileName)

 ...

補遺:この投稿では、パイプラインの代わりにPowerShellを使用してみました。

C#からPowerShell関数を呼び出す際の問題

このように、しかし私は同じ例外を得ました:

private void RunPowerShellCommandToBuildCV()
{
    string BigWindow = "";
    string FileNamePopup = "";

    TestPopup(ref BigWindow, ref FileNamePopup);

    string psScriptPath = @"D:\Project Files\CIS3G\Webapp\_Powershell\JcdcCv.psm1";
    string psScript = string.Empty;

    if (File.Exists(psScriptPath))
        psScript = File.ReadAllText(psScriptPath);
    else
        throw new FileNotFoundException("Wrong path for the script file");

    // Init the PowerShell runspace and pipeline - EWB
    using (Runspace runSpace = RunspaceFactory.CreateRunspace())
    {
        runSpace.Open();

        // Set execution policy - EWB
        RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace);
        runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

        //Pipeline pipeline = runSpace.CreatePipeline();

        PowerShell ps = PowerShell.Create();
        ps.Runspace = runSpace;

        // Load as file - EWB
        ps.AddScript(psScriptPath);

        ps.AddCommand("New-BuildCVFromSql").AddParameters(new Dictionary<string, string>()
         {
             {"SqlOrExcelFile", @"C:\tempeval.sql"},
             {"Js", "JCDC"},
             {"FileName", @"Evaluation\EvaluationFormPartialListCV"}
         });

        foreach (PSObject result in ps.Invoke())
        {
            Debug.WriteLine ("Object : " + result);
        }
    }

補遺2:

すべてのコマンドを削除し(ユーザー定義関数ではなく、組み込みのCmdLetsでのみ機能するため)、実行時に依存関係が読み込まれなくても、代わりにコードを呼び出しているようです...私はまだ調査中です。

ps.AddScript( @"New-BuildCVFromSql 'C:\Documents and Settings\Brown.Ericw\My Documents\tempeval.sql' JCDC 'Evaluation\EvaluationFormPartialListCV'" );

実行中に依存関係はロードされませんが、コードを呼び出しているようです...私はまだそれを調べています。しかし、それがISEから実行される場合、それは機能します...

4

2 に答える 2

2

の2番目のバージョンでRunPowerShellCommandToBuildCV()は、ps.invoke()アフタースクリプトが追加されていません。

    //load as file - EWB
    ps.AddScript( psScriptPath );
    ps.Invoke(); //<--------- !!!!
    ps.AddCommand( "New-BuildCVFromSql" ).AddParameters(new Dictionary<string, string>()
     {
         { "SqlOrExcelFile", @"C:\tempeval.sql" },
         { "Js", "JCDC" },
         { "FileName", @"Evaluation\EvaluationFormPartialListCV" }
     });

と呼ばれる関数があることを知っInvoke()た後runspaceNew-BuildCVFromSql

于 2012-06-06T19:16:01.153 に答える
0

これは私がそれを行う方法であり、それは御馳走を機能させます:

private static void Test()
{
    dynamic parameters = new ExpandoObject();
    parameters.test= "myImage";
    parameters.arg2= 2;

    var results = RunPowerShellFunction("My-Function", parameters);
    var obj = results[0];
    var str = results[1];
}

private static dynamic RunPowerShellFunction(string functionName, dynamic parameters)
{
    dynamic rv = null;

    try
    {
        InitialSessionState iss = InitialSessionState.CreateDefault();

        using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
        {
            runspace.Name = typeof(DockerManager).Name;
            runspace.Open();

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

            using (var mainPowerShell = System.Management.Automation.PowerShell.Create())
            {
                mainPowerShell.Runspace = runspace;

                mainPowerShell.AddScript(LoadedScriptText, false);
                mainPowerShell.Invoke();

                var cmd = mainPowerShell.AddCommand(functionName);

                if (parameters != null)
                {
                    foreach (var parameter in parameters)
                    {
                        cmd.AddParameter(parameter.Key, parameter.Value);
                    }
                }

                rv = cmd.Invoke();
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }

    return rv;
}
于 2017-04-22T10:09:15.187 に答える