Вывести результат работы скрипта PowerShell в ListView - Visual Basic .NET
Формулировка задачи:
Есть скрипт на powershell, который выводит список принтеров с домена:
результат его работы такой
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, и выводит результат в текстовое поле. вот весь код:
ставил библиотеку вот отсюда:https://www.nuget.org/packages/System.Management.Automation/
результат выполнения всего кода такой(см. вложение). Выводиться в TextBox
все работает шикарно, но есть одно но. как можно (и возможно ли вообще) перепилить код так что бы информация выводилась по столбцам в ListView.
Пожалуйста, помогите! буду рад вашей помощи! Заранее большое спасибо!!!
Листинг программы
- $terminals = ("domen")
- $terminals | ForEach-Object { Get-WmiObject -class Win32_Printer -computer $terminals `
- | Where-Object {$_.ShareName -ne $null} `
- | select Name, ShareName, PortName } `
Листинг программы
- Imports System.Collections.ObjectModel
- Imports System.Management.Automation
- Imports System.Management.Automation.Runspaces
- Imports System.Text
- Imports System.IO
- Public Class Form2
- Private Function RunScript(ByVal scriptText As String) As String
- ' create Powershell runspace
- Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
- ' open it
- MyRunSpace.Open()
- ' create a pipeline and feed it the script text
- Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
- MyPipeline.Commands.AddScript(scriptText)
- ' add an extra command to transform the script output objects into nicely formatted strings
- ' remove this line to get the actual objects that the script returns. For example, the script
- ' "Get-Process" returns a collection of System.Diagnostics.Process instances.
- MyPipeline.Commands.Add("Out-String")
- ' execute the script
- Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
- ' close the runspace
- MyRunSpace.Close()
- ' convert the script result into a single string
- Dim MyStringBuilder As New StringBuilder()
- For Each obj As PSObject In results
- MyStringBuilder.AppendLine(obj.ToString())
- Next
- ' return the results of the script that has
- ' now been converted to text
- Return MyStringBuilder.ToString()
- End Function
- Private Function LoadScript(ByVal filename As String) As String
- Try
- ' Create an instance of StreamReader to read from our file.
- ' The using statement also closes the StreamReader.
- Dim sr As New StreamReader(filename)
- ' use a string builder to get all our lines from the file
- Dim fileContents As New StringBuilder()
- ' string to hold the current line
- Dim curLine As String = ""
- ' loop through our file and read each line into our
- ' stringbuilder as we go along
- Do
- ' read each line and MAKE SURE YOU ADD BACK THE
- ' LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF
- curLine = sr.ReadLine()
- fileContents.Append(curLine + vbCrLf)
- Loop Until curLine Is Nothing
- ' close our reader now that we are done
- sr.Close()
- ' call RunScript and pass in our file contents
- ' converted to a string
- Return fileContents.ToString()
- Catch e As Exception
- ' Let the user know what went wrong.
- Dim errorText As String = "The file could not be read:"
- errorText += e.Message + "\n"
- Return errorText
- End Try
- End Function
- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
- 'run our script and put the result into our textbox
- 'NOTE: make sure to change the path to the correct location of your script
- TextBox1.Text = RunScript(LoadScript("d:\скрипты\print_list.ps1"))
- End Sub
Решение задачи: «Вывести результат работы скрипта PowerShell в ListView»
textual
Листинг программы
- Public Class Form1
- Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
- FillListView(TextBox1.Text, ListView1)
- Label1.Text = "Всего принтеров: " & ListView1.Items.Count
- End Sub
- Public Sub FillListView(SourceText As String, LV As ListView)
- LV.Clear()
- Dim LINES() As String = SourceText.Split(New Char() {vbCrLf}, System.StringSplitOptions.RemoveEmptyEntries)
- Dim Columns() As String = LINES(0).Split(New Char() {Space(1)}, System.StringSplitOptions.RemoveEmptyEntries)
- For Each item In Columns : LV.Columns.Add(item).Width = 130 : Next
- For i = 2 To LINES.Length - 1
- If LINES(i).Trim.Length > 0 Then
- Dim name As String = Strings.Left(LINES(i), 37).Trim
- Dim sharename As String = Strings.Mid(LINES(i), 38, 40).Trim
- Dim portname As String = Strings.Mid(LINES(i), 77, 36).Trim
- LV.Items.Add(name).SubItems.AddRange({sharename, portname})
- LV.Items(LV.Items.Count - 1).ImageKey = "printer.png"
- End If
- Next
- End Sub
- End Class
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д