Question

I am having some real trouble here. Working in Visual Studio 2013 Express, in Visual Basic. I have a form which has a ListBox. And a function which calls a PowerShell cmd-let 'Get-Process'. I am trying to get this output to display in said Listbox.

The code I have so far is below:

Private Function RunScript(ByVal scriptText As String) As String
        ' create Powershell runspace 
        Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
        MyRunSpace.Open()
        ' create a pipeline and feed it the script text 
        Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()

        MyPipeline.Commands.AddScript(scriptText)
        MyPipeline.Commands.Add("Out-String")

        ' execute the script 
        Dim PSOut As Collection(Of PSObject) = MyPipeline.Invoke()

        ' close the runspace 
        MyRunSpace.Close()

        For Each Id In PSOut
            CheckList1.BeginUpdate()
            CheckList1.Items.Add(Id)
            CheckList1.EndUpdate()
        Next

    End Function

All this does is display the first line of the PowerShell output and nothing else. What am I missing? I thought maybe it needs to be told to loop through the collection, but I cant find anything like that in my searches thus far...

Any help will be appreciated.

Phill

Was it helpful?

Solution

Your problem is in this line:

MyPipeline.Commands.Add("Out-String")

Just remove it.

It's causing your output to be formatted as a string. Meaning after that you need to parse it back to a list of string, and then potentially do even more parsing. You don't need all that, because it's much easier to work with a list of PSObject, when each of them is actually a PSObject, and not a string wrapper.

Also regarding process format, you may consider using this instead of just Id:

Id.Properties("Name").Value.ToString()

This will populate your checklist control with a list of process names. Also consider changing your variable name, i.e. Id to psProcess, to reflect what it really is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top