我需要从 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/