2010-07-28 77 views
1

我需要從vb.net窗口應用程序內運行腳本。在.NET窗口應用程序中運行powershell腳本

我已經在後臺運行的腳本很好;

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 

但是有一個更好的方法?

回答

4

PowerShell引擎與其主機之間存在區別。你想要的是在應用程序中運行引擎,然後啓動一個單獨的主機(它也託管PowerShell引擎)來處理提示。您可能需要考慮修改您的應用程序以充當主機本身。然後,您可以對提示(讀取主機)和彈出對話框等進行響應。看看relevant PowerShell namespace。還請看看這blog post on creating a simple PSHost

相關問題