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

标签 vb.net powershell powershell-2.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

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

最佳答案

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

关于vb.net - 从 .NET Windows 应用程序中运行 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3352933/

相关文章:

c# to vb 转换对象初始化

email - 打开 outlook 的新电子邮件对话框,其中包含来自 powershell 的预填充信息

regex - Powershell:无法让正则表达式在多行上工作

powershell - 删除未锁定(正在使用)的文件

powershell - 如何使函数成为 cmdlet 的别名

powershell - 如何使用 PowerShell 将 UTC 转换为 EST

vb.net - 如何在vb.net中迭代字典?

vb.net - 检查FTP是否在线/离线

.net - 无法在Win64位上创建64位的activex组件?

powershell - 在 Powershell 中设置像 yyyy-mm-dd 这样的默认日期格式?