0

I'm trying to run PowerShell script from my form. I've added a NuGet package named "System Management Automation" to my project that enables interaction with PowerShell from vb.net program. And added project reference to System.Management.Automation.dll found in the in package folder. Below is the code I'm using trying to run PowerShell script.

Imports System.Collections.ObjectModel
Imports System.Diagnostics
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.Text

Public Class FormMain

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        RichTextBoxConsole.AppendText(RunScript("cls"))
    End Sub

    Private Function RunScript(ByVal script As String) As String
        Dim runspace As Runspace = RunspaceFactory.CreateRunspace
        runspace.Open()
        Dim pipeline As Pipeline = runspace.CreatePipeline
        pipeline.Commands.Add("cls")
        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

End Class

But, when I click on Button1 I get the following exception:

An unhandled exception of type 'System.Management.Automation.SetValueInvocationException' occurred in System.Management.Automation.dll

Additional information: Exception setting "CursorPosition": "A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows."

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
Somanna
  • 284
  • 1
  • 13

1 Answers1

1

Clear-Host (alias cls) works by calling the host user interface of the hosting application - if you don't provide a UI implementation it won't have anything to work against, which is why you see the exception being thrown.

Either implement a host UI, or avoid calling functions that rely on one being available

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206