从 .NET Windows 应用程序中运行 powershell 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3352933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running powershell scripts from within a .NET windows app
提问by GordonB
I'm needing to run scripts from within a vb.net windows app.
我需要从 vb.net Windows 应用程序中运行脚本。
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;
但是,我现在需要能够让 powershell 运行(不在后台运行),例如。出现提示时;
Set-ExecutionPolicy unrestricted
Set-ExecutionPolicy unrestricted
I'm currently looking into the Microsoft.PowerShell.ConsoleHost namespace to see if i can use something like;
我目前正在查看 Microsoft.PowerShell.ConsoleHost 命名空间,看看我是否可以使用类似的东西;
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??
但必须有更好的方法?
回答by Keith Hill
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.
PowerShell 引擎与其主机之间存在区别。您想要的是在您的应用程序中运行引擎,然后启动一个单独的主机(它也托管 PowerShell 引擎)来处理提示。您可能需要考虑修改您的应用程序以充当主机本身。然后,您可以对提示(读取主机)和弹出对话框或其他任何内容做出反应。看看这个相关的 PowerShell 命名空间。另请查看有关创建简单 PSHost 的博客文章。