且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 .NET Windows 应用程序中运行 powershell 脚本

更新时间:2022-10-15 08:40:32

PowerShell 引擎与其主机之间存在区别.您想要的是在您的应用程序中运行引擎,然后启动一个单独的主机(它也托管 PowerShell 引擎)来处理提示.您可能需要考虑修改您的应用程序以充当主机本身.然后,您可以对提示(读取主机)和弹出对话框或其他任何内容做出反应.看看这个相关的PowerShell命名空间.另请查看此 有关创建简单 PSHost 的博文.

I'm needing to run scripts from within a vb.net windows app.

I've got the scripts running in the background fine;

 Using MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
      MyRunSpace.Open()
      Using MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
        MyPipeline.Commands.AddScript("import-module -name " & moduleName &
                              vbCrLf &
                              "(get-module -name " & moduleName & ").version")


        Dim results = MyPipeline.Invoke()
        'Do something with the results
      End Using

      MyRunSpace.Close()
    End Using

However, i now need to be able to have the powershell run (not in the background) eg. When prompts occur;

Set-ExecutionPolicy unrestricted

I'm currently looking into the Microsoft.PowerShell.ConsoleHost namespace to see if i can use something like;

Dim config = RunspaceConfiguration.Create
ConsoleShell.Start(config, "Windows PowerShell", "", New String() {""})

Can anyone advise me please???

EDIT: I've fudged it a bit with this;

  Public Function RunPowershellViaShell(ByVal scriptText As String) As Integer
    Dim execProcess As New System.Diagnostics.Process
    Dim psScriptTextArg = "-NoExit -Command ""& get-module -list"""
    'Dim psScriptTextArg = "-NoExit -Command ""& set-executionPolicy unrestricted"""
    'Dim psScriptTextArg = ""-NoExit -Command """ & scriptText & """"

    execProcess.StartInfo.WorkingDirectory = Environment.SystemDirectory & "\WindowsPowershell\v1.0\"
    execProcess.StartInfo.FileName = "powershell.exe"
    execProcess.StartInfo.Arguments = psScriptTextArg
    execProcess.StartInfo.UseShellExecute = True
    Return execProcess.Start
  End Function

But there's gotta be a better way??

There is a distinction between the PowerShell engine and its host. What you're wanting is to run the engine within your application but then fire up a separate host (which also is hosting the PowerShell engine) to handle prompts. You might want to look into modifying your application to act as a host itself. You could then react to prompts (read-host) and pop dialog boxes or whatever. Take a look at this relevant PowerShell namespace. Also check out this blog post on creating a simple PSHost.