Вывести результат работы скрипта PowerShell в ListView - Visual Basic .NET

Узнай цену своей работы

Формулировка задачи:

Есть скрипт на powershell, который выводит список принтеров с домена:
Листинг программы
  1. $terminals = ("domen")
  2. $terminals | ForEach-Object { Get-WmiObject -class Win32_Printer -computer $terminals `
  3. | Where-Object {$_.ShareName -ne $null} `
  4. | select Name, ShareName, PortName } `
результат его работы такой Name ShareName PortName ---- --------- -------- Xerox-3250 Xerox-3250 10.57.1.162 Xerox-3250 Xerox-3250 10.57.1.161 Xerox-3250 Xerox-3250 10.57.1.165 нашел в интернете библиотеку System.Management.Automation, которая интегрирует powershell в vb.net, и выводит результат в текстовое поле. вот весь код:
Листинг программы
  1. Imports System.Collections.ObjectModel
  2. Imports System.Management.Automation
  3. Imports System.Management.Automation.Runspaces
  4. Imports System.Text
  5. Imports System.IO
  6. Public Class Form2
  7. Private Function RunScript(ByVal scriptText As String) As String
  8. ' create Powershell runspace
  9. Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
  10. ' open it
  11. MyRunSpace.Open()
  12. ' create a pipeline and feed it the script text
  13. Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
  14. MyPipeline.Commands.AddScript(scriptText)
  15. ' add an extra command to transform the script output objects into nicely formatted strings
  16. ' remove this line to get the actual objects that the script returns. For example, the script
  17. ' "Get-Process" returns a collection of System.Diagnostics.Process instances.
  18. MyPipeline.Commands.Add("Out-String")
  19. ' execute the script
  20. Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
  21. ' close the runspace
  22. MyRunSpace.Close()
  23. ' convert the script result into a single string
  24. Dim MyStringBuilder As New StringBuilder()
  25. For Each obj As PSObject In results
  26. MyStringBuilder.AppendLine(obj.ToString())
  27. Next
  28. ' return the results of the script that has
  29. ' now been converted to text
  30. Return MyStringBuilder.ToString()
  31. End Function
  32. Private Function LoadScript(ByVal filename As String) As String
  33. Try
  34. ' Create an instance of StreamReader to read from our file.
  35. ' The using statement also closes the StreamReader.
  36. Dim sr As New StreamReader(filename)
  37. ' use a string builder to get all our lines from the file
  38. Dim fileContents As New StringBuilder()
  39. ' string to hold the current line
  40. Dim curLine As String = ""
  41. ' loop through our file and read each line into our
  42. ' stringbuilder as we go along
  43. Do
  44. ' read each line and MAKE SURE YOU ADD BACK THE
  45. ' LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF
  46. curLine = sr.ReadLine()
  47. fileContents.Append(curLine + vbCrLf)
  48. Loop Until curLine Is Nothing
  49. ' close our reader now that we are done
  50. sr.Close()
  51. ' call RunScript and pass in our file contents
  52. ' converted to a string
  53. Return fileContents.ToString()
  54. Catch e As Exception
  55. ' Let the user know what went wrong.
  56. Dim errorText As String = "The file could not be read:"
  57. errorText += e.Message + "\n"
  58. Return errorText
  59. End Try
  60. End Function
  61. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  62. 'run our script and put the result into our textbox
  63. 'NOTE: make sure to change the path to the correct location of your script
  64. TextBox1.Text = RunScript(LoadScript("d:\скрипты\print_list.ps1"))
  65. End Sub
ставил библиотеку вот отсюда:https://www.nuget.org/packages/System.Management.Automation/ результат выполнения всего кода такой(см. вложение). Выводиться в TextBox все работает шикарно, но есть одно но. как можно (и возможно ли вообще) перепилить код так что бы информация выводилась по столбцам в ListView. Пожалуйста, помогите! буду рад вашей помощи! Заранее большое спасибо!!!

Решение задачи: «Вывести результат работы скрипта PowerShell в ListView»

textual
Листинг программы
  1. Public Class Form1
  2.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  3.         FillListView(TextBox1.Text, ListView1)
  4.         Label1.Text = "Всего принтеров: " & ListView1.Items.Count
  5.     End Sub
  6.  
  7.     Public Sub FillListView(SourceText As String, LV As ListView)
  8.         LV.Clear()
  9.         Dim LINES() As String = SourceText.Split(New Char() {vbCrLf}, System.StringSplitOptions.RemoveEmptyEntries)
  10.         Dim Columns() As String = LINES(0).Split(New Char() {Space(1)}, System.StringSplitOptions.RemoveEmptyEntries)
  11.         For Each item In Columns : LV.Columns.Add(item).Width = 130 : Next
  12.  
  13.         For i = 2 To LINES.Length - 1
  14.             If LINES(i).Trim.Length > 0 Then
  15.                 Dim name As String = Strings.Left(LINES(i), 37).Trim
  16.                 Dim sharename As String = Strings.Mid(LINES(i), 38, 40).Trim
  17.                 Dim portname As String = Strings.Mid(LINES(i), 77, 36).Trim
  18.                 LV.Items.Add(name).SubItems.AddRange({sharename, portname})
  19.                 LV.Items(LV.Items.Count - 1).ImageKey = "printer.png"
  20.             End If
  21.         Next
  22.     End Sub
  23. End Class

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

7   голосов , оценка 3.857 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут