My goal is to accomplish running a PowerShell command within a vb.net application. I'm trying to run the command calc
inside powershell.
These following systems are imported:
Imports System.IO
Imports System.Collections.ObjectModel
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.Text
I created the function RunScript
to run any powershell commands:
Public Function RunScript(ByVal script As String) As String
Dim runspace As Runspace = RunspaceFactory.CreateRunspace()
runspace.Open()
Dim pipeline As Pipeline = Runspace.CreatePipeline()
pipeline.Commands.AddScript(script)
pipeline.Commands.Add("Out-String")
Dim results As Collection(Of PSObject) = pipeline.Invoke()
Runspace.Close()
Dim stringbuilder As StringBuilder = New StringBuilder()
For Each ps As PSObject In results
stringbuilder.AppendLine(ps.ToString())
Next
Return stringbuilder.ToString()
End Function
The NuGet Package I am using is this: System.Management.Automation.dll (not to be confused with System.Management.Automation
)
The way I use this function to run a PowerShell command (running calc
in this instance:)
txtOutput.Text = RunScript("calc")
(note: txtOutput
is a textbox containing the output of the command when it is run inside powershell)
No errors are shown before building the solution but when building the solution, the following errors were logged in the console:
error BC30002: Type 'Runspace' is not defined.
error BC30451: 'RunspaceFactory' is not declared. It may be inaccessible due to its protection level.
error BC30002: Type 'Pipeline' is not defined.
error BC30002: Type 'PSObject' is not defined.
error BC30002: Type 'PSObject' is not defined.