Powershell via VB.NET. Which method and why?

12,454

Lets start understanding one by one:

PowerShell Object: Provides methods that are used to create a pipeline of commands and invoke those commands either synchronously or asynchronously within a runspace. This class also provides access to the output streams that contain data that is generated when the commands are invoked. This class is primarily intended for host applications that programmatically use Windows PowerShell to perform tasks. The pipeline here is exclusive to host application and you can make specific to PowerShell Objects. This also guarantee that you will have access to powershell results data even when the commands are sent sync and async.

RunspaceInvoke: Allows the execution of commands from a CLR language. It can not be use if host application needs to explicitly define a pipeline. This is going to use an existing object pipeline and add Powershell commands for you. You might have other commands in the pipeline and powershell commands will be included as well. Here you are using a CLR Pipeline object and adding more commands to it and the pipeline is not exclusive to your application.

Finally I would say using Powershell object is the best choice to use in any application which is going to host Powershell objects.

Share:
12,454
Jimmy D
Author by

Jimmy D

Updated on June 04, 2022

Comments

  • Jimmy D
    Jimmy D almost 2 years

    I need to call Powershell commands via my code and I find at least 2 different examples of doing this. I'm wondering what the differences between the methods are and why I would use one as opposed to the other.

    The first (simpler?) method goes something like this:

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

    results now contains a collection of Powershell objects that can be converted to strings, for example:

    MsgBox(results.Item(0).ToString())
    

    The second method looks like this:

    Dim invoker As New RunspaceInvoke
    Dim command As String = "<Powershell command here>"
    Dim outputObjects As Collection(Of PSObject) = invoker.Invoke(command)
    

    And then I can iterate through the collection of returned objects and convert to string in the same way:

    For Each result As PSObject In outputObjects
        Console.WriteLine(result.ToString)
    Next
    

    I also know that with either method I can pipe the command to out-string to make Powershell return strings instead of objects.

    My question is, which method should I use and why? They both seem the same to me.