2012-05-18 49 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和调用函数,这并不是我正在寻找的。 –