2012-05-18 52 views
1

我必須從VB.NET程序調用PS命令。這工作正常,如果我打電話標準的PS命令,但如果我不得不打電話生活在第三方模塊的命令,我似乎無法使其工作。在PS控制檯上,我可以輸入Import-Module MyModule,然後我可以調用該模塊中的命令。我嘗試以下,但它不工作,我仍然無法從模塊中訪問我的命令:通過.NET代碼加載Powershell模塊

Dim PowerShell As Management.Automation.PowerShell = PowerShell.Create() 
Dim PowerShellCommand As New PSCommand() 
Dim PowerShellCommandResults As Object 

PowerShellCommand.AddScript("Import-Module MyModule") 
PowerShellCommand.AddScript("Get-MyCommand | Out-String") 
PowerShell.Commands = PowerShellCommand 
PowerShellCommandResults = PowerShell.Invoke() 

我怎樣才能做到這一點與上面的代碼例子嗎?除非必須,否則我不想將所有內容都更改爲Runspace

+0

貌似答案:http://stackoverflow.com/questions/6266108/powershell-how-to-import-module-in-a-runspace –

+0

那ANS wer使用Runspace類。我已經知道我可以用這個班級來完成,我的目標是在沒有班級的情況下完成。 –

+0

你有錯誤嗎? 「PowerShellCommandResults」中是否有任何結果? – Richard

回答

-1

簡單的代碼看起來像下面和它的工作:

Dim command As New PSCommand() 
command.AddScript("<Powershell command here>") 
Dim powershell As Management.Automation.PowerShell = powershell.Create() 
powershell.Commands = command 
Dim results = powershell.Invoke() 

我已經解釋了在其他線程下你可以選擇其中之一: Powershell via VB.NET. Which method and why?

如果您提供更多關於錯誤我可能會提供幫助。

增加了更多的信息有完整的例子:

我剛剛創建了一個非常簡單的C#DLL並把它稱爲從VB.NET如下:

C#DLL代碼:(認爲這是一個第三方模塊)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Xml.Linq; 

namespace CSVtoXML 
{ 
    public class Actions 
    { 
    public Actions() 
    { 

    } 

    public static string writeHello(string name) 
    { 
     return "Hello " + name; 

    } 
} 
} 

如果你想測試在PS命令窗口這個第三方DLL只使用以下命令:

PS C:\2012> [Reflection.Assembly]::LoadFile("C:\2012\CSVtoXML.dll") 

GAC Version  Location 
--- -------  -------- 
False v2.0.50727  C:\2012\CSVtoXML.dll 


PS C:\2012> [CSVtoXML.Actions]::writeHello("Avkash") 
Hello Avkash 
PS C:\2012> 

現在我使用加載第三方模塊相同的步驟如下VB.NET應用

Module Module1 
Sub Main() 
    Dim PowerShell As Management.Automation.PowerShell = PowerShell.Create() 
    Dim PowerShellCommand As New PSCommand 
    PowerShellCommand.AddScript("[Reflection.Assembly]::LoadFile('C:\2012\CSVtoXML.dll')") 
    PowerShellCommand.AddScript("[CSVtoXML.Actions]::writeHello('Avkash')") 
    PowerShell.Commands = PowerShellCommand 
    Dim results = PowerShell.Invoke() 
    MsgBox(results.Item(0).ToString()) 
End Sub 
End Module 

下面是在調試窗口輸出證明代碼不會作爲工作預計:

enter image description here

+0

你有沒有看過我的問題? –

+0

我確定閱讀你的問題,並建議上述代碼將工作。除非你告訴我什麼都行不通,我不能幫忙。你需要告訴我解釋錯誤消息的問題進一步挖掘,只是說它「沒有工作」沒有幫助..謝謝你的 - 雖然。 Next – AvkashChauhan

+0

我的問題清楚地解釋了我需要通過FIRST調用'import-module'來調用第三方模塊中的函數。我給出的例子不起作用,看起來是因爲調用import-module不起作用。向我展示如何通過命名空間和類名來加載dll和調用函數,這並不是我正在尋找的。 –