How to Run a Powershell Inside Visual Basic Programming

PowerShell lets programmers manipulate the Windows operating system from the command line. With PowerShell, you can access objects from the .NET framework as well as the Window’s file system. A reusable PowerShell script is called a “cmdlet.” You can combine cmdlets to create powerful scripts that you can share with other users. Visual BASIC (VB) is a programming language used in the .NET framework that lets you call PowerShell scripts from within its managed code. This in turn allows you to create an attractive user interface that beginning users can use to run cmdlets in lieu of the command line.

Things You’ll Need
Visual Studio
Start Visual Studio. Open the VB project you want to use to run a PowerShell cmdlet.

Right-click on the name of your project from the file directory on the upper right corner of your screen. Click on “Add Reference,” then click on the “Browse” button. Click on “System.Management.Automation.dll” and the “OK” button.

Double click on the VB file you want to use to run the PowerShell cmdlet, then place the following code at the top of the file:

Imports System.Text

Imports System.IO

Imports System.Management.Automation

Imports System.Collections.ObjectModel

Imports System.Management.Automation.Runspaces

Create a method to run the PowerShell script:

Private Function ExecuteMyPowerShellScript(ByVal scriptText As String) As String

End Function

Instantiate a PowerShell Runspace object and open it. Create a PowerShell pipeline object and run its “AddScript()” method, using the script text as an argument.

Dim RunspaceSample As Runspace = RunspaceFactory.CreateRunspace()
RunspaceSample.Open()

Dim PipelineSample As Pipeline = MyRunSpace.CreatePipeline()

PipelineSample.Commands.AddScript(scriptText)

Execute the PowerShell script and close it:

Dim results As Collection(Of PSObject) = PipelineSample.Invoke()

RunSpaceSample.Close()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s