运行PowerShell cmdlet(函数?)的代码,该cmdlet位于cmpsts的.ps1文件中(函数?)

时间:2012-06-06 17:24:14

标签: c# .net powershell

我有代码从包含大量PowerShell cmdlet的.ps1文件运行PowerShell cmdlet ...当我执行它时,我得到了这个异常:

  

术语'New-BuildCVFromSql'未被识别为a的名称   cmdlet,函数,脚本文件或可操作程序。检查拼写   如果包含名称,或者包含路径,请验证路径是否正确   纠正,然后再试一次。

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文件中,我试图调用的cmdlet是这样定义的:

# 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而不是管道:

Problem with calling a powershell function from c#

像这样,但我得到了同样的例外:

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运行它可以工作......

2 个答案:

答案 0 :(得分: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()runspace知道有一个名为New-BuildCVFromSql的函数

答案 1 :(得分:0)

这就是我这样做的方式,它有效:

from matplotlib import pyplot as plt
from matplotlib import gridspec
from matplotlib.widgets import Slider, RadioButtons

# Set the grid
grid = gridspec.GridSpec(2, 1, height_ratios=[1, 2])

# Plot the sliders
axes_slider = plt.subplot(grid[0, 0])
slider = Slider(axes_slider, 'Channel', valmin=0, valmax=255, valinit=128)

# Plot the radio buttons
axes_button = plt.subplot(grid[1, 0])
button = RadioButtons(axes_button, ('Gradient', 'Channel'), active=1)

plt.tight_layout(h_pad=0)
plt.subplots_adjust(left=.2, right=.9)

def buttonupdate(val):
    if val == "Gradient":
        axes_slider.clear()
        slider.__init__(axes_slider, 'Gradient', valmin=-1, valmax=1, valinit=0)        
    else:
        axes_slider.clear()
        slider.__init__(axes_slider, 'Channel', valmin=0, valmax=255, valinit=128) 
    plt.gcf().canvas.draw_idle()

def sliderupdate(val):
    if slider.label.get_text() == 'Gradient':
        #do something depending on gradient value
        pass
    else:
        #do something depending on channel value
        pass

# Register call-backs with widgets
slider.on_changed(sliderupdate)
button.on_clicked(buttonupdate)

plt.show()