【问题标题】:Running powershell scripts from within a .NET windows app从 .NET Windows 应用程序中运行 powershell 脚本
【发布时间】:2010-07-28 12:43:24
【问题描述】:

我需要在 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

但是一定有更好的方法吗??

【问题讨论】:

    标签: vb.net powershell powershell-2.0 windows


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 2023-03-31
      • 2019-05-08
      • 2011-07-15
      • 1970-01-01
      • 2011-12-22
      • 2013-08-22
      相关资源
      最近更新 更多