如何从C#创建交互式Powershell实例?

时间:2019-01-21 14:24:00

标签: c# powershell

我有一个Powershell脚本,需要用户交互。我可以使用System.Diagnostics.Process从C#调用powershell.exe,并将脚本路径作为参数传递,但是我希望脚本是项目的嵌入式资源。我尝试创建运行空间(请参见下文)并运行脚本,但是由于脚本需要用户交互,因此我收到了异常。

        var assembly = Assembly.GetExecutingAssembly();            
        var resourceName = "mynamespace.myscriptfile.ps1";
        string result = "";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        using (StreamReader reader = new StreamReader(stream))
        {
            result = reader.ReadToEnd();
            Console.WriteLine(result);
        }
        //Create Powershell Runspace
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        // Create pipeline and add commands
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(result);

        // Execute Script
        Collection<PSObject> results = new Collection<PSObject>();
        try
        {
            results = pipeline.Invoke();
        }
        catch (Exception ex)
        {
            results.Add(new PSObject((object)ex.Message));
        }

        runspace.Close();
        Console.ReadKey();

是否可以使用 System.Diagnostics.Process 将嵌入式资源传递到powershell.exe,或者是否可以从C#调用脚本,以便用户进行交互?

更新: 在我看来,我也许能够正​​确使用抽象类PSHost的实现以及正确使用PSHostUserInterface属性,我也许能够创建一个以PSHost实现为参数的运行空间,以使用本机Powershell控制台。我一直在尝试测试这个想法,但是我不确定如何实现抽象类。

下面是我从Microsoft获得的代码示例。我对两件事感到困惑。如果很重要,我将在控制台应用程序中创建运行空间,该控制台应用程序在 Program 类中的名称空间为: WebRequirements

  1. 私有Host01程序; (Host01可以编程吗?)
  2. PSHostUserInterface(这是我要使用本地Powershell主机的地方,如果要,我将如何使用它?)

    内部类MyHost:PSHost {     ///     ///对PSHost实现的引用。     ///     私人Host01程序;

    /// <summary>
    /// The culture information of the thread that created
    /// this object.
    /// </summary>
    private CultureInfo originalCultureInfo =
        System.Threading.Thread.CurrentThread.CurrentCulture;
    
    /// <summary>
    /// The UI culture information of the thread that created
    /// this object.
    /// </summary>
    private CultureInfo originalUICultureInfo =
        System.Threading.Thread.CurrentThread.CurrentUICulture;
    
    /// <summary>
    /// The identifier of this PSHost implementation.
    /// </summary>
    private Guid myId = Guid.NewGuid();
    
    /// <summary>
    /// Initializes a new instance of the MyHost class. Keep
    /// a reference to the host application object so that it
    /// can be informed of when to exit.
    /// </summary>
    /// <param name="program">
    /// A reference to the host application object.
    /// </param>
    public MyHost(Host01 program)
    {
        this.program = program;
    }
    
    /// <summary>
    /// Return the culture information to use. This implementation
    /// returns a snapshot of the culture information of the thread
    /// that created this object.
    /// </summary>
    public override System.Globalization.CultureInfo CurrentCulture
    {
        get { return this.originalCultureInfo; }
    }
    
    /// <summary>
    /// Return the UI culture information to use. This implementation
    /// returns a snapshot of the UI culture information of the thread
    /// that created this object.
    /// </summary>
    public override System.Globalization.CultureInfo CurrentUICulture
    {
        get { return this.originalUICultureInfo; }
    }
    
    /// <summary>
    /// This implementation always returns the GUID allocated at
    /// instantiation time.
    /// </summary>
    public override Guid InstanceId
    {
        get { return this.myId; }
    }
    
    /// <summary>
    /// Return a string that contains the name of the host implementation.
    /// Keep in mind that this string may be used by script writers to
    /// identify when your host is being used.
    /// </summary>
    public override string Name
    {
        get { return "MySampleConsoleHostImplementation"; }
    }
    
    /// <summary>
    /// This sample does not implement a PSHostUserInterface component so
    /// this property simply returns null.
    /// </summary>
    public override PSHostUserInterface UI
    {
        get { return null; }
    }
    
    /// <summary>
    /// Return the version object for this application. Typically this
    /// should match the version resource in the application.
    /// </summary>
    public override Version Version
    {
        get { return new Version(1, 0, 0, 0); }
    }
    
    /// <summary>
    /// Not implemented by this example class. The call fails with
    /// a NotImplementedException exception.
    /// </summary>
    public override void EnterNestedPrompt()
    {
        throw new NotImplementedException(
            "The method or operation is not implemented.");
    }
    
    /// <summary>
    /// Not implemented by this example class. The call fails
    /// with a NotImplementedException exception.
    /// </summary>
    public override void ExitNestedPrompt()
    {
        throw new NotImplementedException(
            "The method or operation is not implemented.");
    }
    
    /// <summary>
    /// This API is called before an external application process is
    /// started. Typically it is used to save state so the parent can
    /// restore state that has been modified by a child process (after
    /// the child exits). In this example, this functionality is not
    /// needed so the method returns nothing.
    /// </summary>
    public override void NotifyBeginApplication()
    {
        return;
    }
    
    /// <summary>
    /// This API is called after an external application process finishes.
    /// Typically it is used to restore state that a child process may
    /// have altered. In this example, this functionality is not
    /// needed so the method returns nothing.
    /// </summary>
    public override void NotifyEndApplication()
    {
       return;
    }
    
    /// <summary>
    /// Indicate to the host application that exit has
    /// been requested. Pass the exit code that the host
    /// application should use when exiting the process.
    /// </summary>
    /// <param name="exitCode">The exit code to use.</param>
    public override void SetShouldExit(int exitCode)
    {
        this.program.ShouldExit = true;
        this.program.ExitCode = exitCode;
    }
    

    }

0 个答案:

没有答案