尝试从WinForms App启动Powershell脚本时出错

时间:2019-06-28 18:16:48

标签: vb.net winforms powershell

因此,我一直遵循在线制作的指南,该指南演示了如何使用VB.Net从Windows窗体应用程序运行Powershell脚本。但是,我一直遇到这个问题,我一生无法找到答案或任何接近它的答案。

Password

这是我的代码,它紧跟示例的内容。但是,我不断收到此错误:

    Dim myRunSpace As Runspace = RunspaceFactory.CreateRunspace
    myRunSpace.Open()
    Dim mypipeline As Pipeline = myRunSpace.CreatePipeline()
    Dim command As String = " .'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; get-mailbox -recipienttypedetails UserMailbox | select-object DisplayName,RecipientTypeDetails,PrimarySmtpAddress"
    mypipeline.Commands.AddScript(command)
    mypipeline.Commands.Add("Out-String")
    Dim outputs As Collection(Of PSObject) = mypipeline.Invoke()
    'myRunSpace.Close()
    Dim MyStringBuiler As New StringBuilder()
    For Each result As PSObject In outputs
        MyStringBuiler.AppendLine(result.ToString())
    Next
    MessageBox.Show(MyStringBuiler.ToString)
    '        ReadExchangeCSVFile()

到目前为止,根据我收集的研究结果,可能是我要导入的库版本与计算机上安装的powershell版本不匹配。

出错的行是上面代码片段中的第一行。因此,在创建运行空间时,它会在调试时向我显示错误。

1 个答案:

答案 0 :(得分:0)

完全正确。如果它在没有大量引用的空Windows窗体项目中工作,则意味着您发生冲突(然后进行进程间的通信愉快!)。

如果这两种方法都不起作用,则表示您很幸运,只需找到缺少的DLL(您可以使用Fusion Log Viewer进行查看,或在相应的事件处理程序中显示一个消息框):

Imports System
Imports System.Linq
Imports System.Reflection
Imports Microsoft.VisualBasic

Module StartUp

    Public Sub Main(args As String())
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, AddressOf CustomResolver
        'Load powershell here

    End Sub

    Private Function CustomResolver(sender As Object, args As ResolveEventArgs) As Assembly
        MsgBox($"Assembly {args.Name} not found!{vbCrLf}{vbCrLf}(referred by {args.RequestingAssembly?.Modules?.FirstOrDefault()?.FullyQualifiedName})")
        Return Nothing
    End Function

End Module