Running powershell scripts from within a .NET windows app

 ̄綄美尐妖づ 提交于 2019-12-02 08:50:50

问题


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??


回答1:


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.



来源:https://stackoverflow.com/questions/3352933/running-powershell-scripts-from-within-a-net-windows-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!