VS2013 VB - 尝试向ListBox添加Powershell输出

时间:2014-04-11 12:51:03

标签: vb.net winforms powershell listbox cmdlets

我在这里遇到了一些麻烦。在Visual Basic中使用Visual Studio 2013 Express。我有一个有ListBox的表单。还有一个调用PowerShell cmd-let'Get-Process'的函数。我试图让这个输出显示在所述列表框中。

我到目前为止的代码如下:

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

这一切都是显示PowerShell输出的第一行而不是其他内容。我错过了什么?我想也许需要被告知循环收集,但到目前为止我在搜索中找不到类似的内容......

任何帮助将不胜感激。

菲尔

1 个答案:

答案 0 :(得分:1)

你的问题在这一行:

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

删除它。

这会导致您的输出格式化为字符串。之后的意思是你需要将它解析回字符串列表,然后可能做更多的解析。你并不需要所有这些,因为使用PSObject列表要容易得多,因为每个PSObject实际上都是PSObject,而不是字符串包装器。

另外,关于流程格式,您可以考虑使用此格式而不仅仅是Id

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

这将使用进程名称列表填充您的核对表控件。另外,请考虑更改您的变量名称,即IdpsProcess,以反映它的真实含义。