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

时间:2010-07-28 12:43:24

标签: vb.net powershell powershell-v2.0 windows

我需要在vb.net windows应用程序中运行脚本。

我已经在后台运行脚本了;

 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

但是,我现在需要能够运行powershell(不在后台),例如。出现提示时;

Set-ExecutionPolicy unrestricted

我目前正在查看Microsoft.PowerShell.ConsoleHost命名空间,看看我是否可以使用类似的内容;

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

任何人都可以告诉我吗???

编辑:我用它捏了一下这个;

  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

但是还有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

PowerShell引擎与其主机之间存在差异。您想要的是在您的应用程序中运行引擎,然后启动一个单独的主机(也托管PowerShell引擎)来处理提示。您可能希望修改应用程序以充当主机本身。然后,您可以对提示(读取主机)和弹出对话框等做出反应。看一下这个relevant PowerShell namespace。另请查看此blog post on creating a simple PSHost