Execute a cmdlet or PS1 script from Visual Basic

The cmdlets in PowerShell can easily be executed from within Visual Basic. I have done this in a few Visual Basic 8 projects, and the code for doing this from Visual Basic 8 can be somewhat ugly, but in Visual Basic 9 (and .NET Framework 3.5) it is very straight forward. You will need a reference to System.Management.Automation. If you don’t have it, you will get it when you install the Windows SDK for Windows Server 2008 and .NET Framework 3.5 from here. System.Management.Automation.dll installs to C:\Program\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0.

The Runspace object will host the Pipeline object, and the Pipeline object is used to execute cmdlets or PS1 scripts.

Some preparations: I have activated script execution and I have created a script file (C:\script.ps1) that contains one simple line: Write-Output 10+2

'Create the runspace.
Using R As System.Management.Automation.Runspaces.Runspace = _
System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()

   'Create the pipeline
   Using P As System.Management.Automation.Runspaces.Pipeline = R.CreatePipeline()

      'Open the runspace.
      R.Open()

      'Create each command (in this case just one)...
      Dim Cmd As New System.Management.Automation.Runspaces.Command("C:\script.ps1", True)

      '...and add it to the pipeline.
      P.Commands.Add(Cmd)

      'Execute the commands and get the response.
      Dim Result As System.Collections.ObjectModel.Collection(Of _
      System.Management.Automation.PSObject) = P.Invoke()

      'Close the runspace.
      R.Close()

      'Display the result in the console window.
      For Each O As System.Management.Automation.PSObject In Result
         Console.WriteLine(O.ToString())
      Next

   End Using
End Using

Output: 12

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *