尝试从Winforms应用启动PowerShell脚本时出错



所以我一直在遵循在线制作的指南,该指南演示了如何使用vb.net从Windows form应用程序运行PowerShell脚本。但是,我一直遇到这个问题,我一生都无法找到答案或几乎任何东西引起我的答案。

    Dim myRunSpace As Runspace = RunspaceFactory.CreateRunspace
    myRunSpace.Open()
    Dim mypipeline As Pipeline = myRunSpace.CreatePipeline()
    Dim command As String = " .'C:Program FilesMicrosoftExchange ServerV14binRemoteExchange.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()

那是我的代码,它遵循了示例的作用。但是,我一直遇到此错误:

{"Cannot load Windows PowerShell snap-in Microsoft.PowerShell.Diagnostics  because of the following error: Could not load file or assembly 'Microsoft.PowerShell.Commands' or one of its dependencies.The system cannot find the file specified."}Source : System.Management.Automation

从我到目前为止我收集的研究中,我正在导入的库和安装在机器上的PowerShell版本的库可能不匹配。

错误的行是上面代码段中的第一个。因此,创建Runspace时会向我显示调试时的错误。

准确。如果它在一个空的Windows表单项目中起作用,而没有很多参考,则意味着您有冲突(然后是Happy Cranscess Communication!(。

如果它都不起作用,则意味着您很幸运,只需要找到哪个DLL(您可以使用Fusion Log Viguter的外观,或者在符合事件处理程序中显示消息框(:

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

最新更新