Error when trying to launch powershell script from WinForms App

Viewed 660

So I've been following the guide made online that demonstrates how to run a powershell script from a windows form app using VB.Net. However I keep running into this problem that I cannot for the life of me find the answer to or anything close to lead me to an answer.

    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()

That is my code and it follows closely what the example does. However, I keep getting this error :

{"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

From research I've gathered so far it may be mismatching versions of libraries I'm importing and the powershell version installed on the machine.

The line that errors out is the first one in the code snippet above. So when creating the runspace it shows me the error when debugging.

1 Answers

Exactly. If it works in an empty windows form project without a lot of references that means you have a conflict (and then happy interprocess communication!).

If it does not work neither, it means you are lucky and just have to find which DLL is missing (you can have a look with fusion log viewer or show a message box in the according event handler):

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
Related