Как извлечь результаты PowerShell в DataTable в vb.net - PullRequest
0 голосов
/ 12 апреля 2020

Я хотел бы извлечь вывод PowerShell, извлечь данные и сохранить их в DataTable в VB. NET, я хочу отобразить вывод в GridView. Мне нужно извлечь столбец и значение из вывода PowerShell в VB. NET

Вот PowerShell:

Get-ADComputer -Filter { OperatingSystem -NotLike '*Windows Server*'} -Property * | 
select Name, operatingSystem, LastLogonDate, Description, whenChanged | 
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-90)) -and ($_.LastLogonDate -ne $NULL)}

Вот результат PowerShell:

Name            : PCO37
operatingSystem : Windows 7 Professional
LastLogonDate   : 1/13/2020 10:04:23 AM
Description     :
whenChanged     : 1/17/2020 1:22:08 PM

Name            : PCO41
operatingSystem : Windows 7 Professional
LastLogonDate   : 2/10/2019 4:43:31 PM
Description     :
whenChanged     : 2/10/2019 4:47:05 PM

Name            : PCO40
operatingSystem : Windows 7 Professional
LastLogonDate   : 4/8/2019 10:03:38 PM
Description     :
whenChanged     : 4/11/2019 6:29:25 AM

Name            : PCO09
operatingSystem : Windows 7 Professional
LastLogonDate   : 3/6/2019 8:04:59 AM
Description     :
whenChanged     : 3/6/2019 8:09:39 AM

Вот мой код в VB. NET:

Function PSObjectToDataTable(ByVal command As String) As DataTable

    ' Initialize PowerShell engine
    Dim Ps As PowerShell = PowerShell.Create()

    ' add the script the PowerShell command
    Ps.Commands.AddScript(command)

    ' Execute the script
    Dim results = Ps.Invoke()

    Dim dt As DataTable = New DataTable()
    dt.Columns.Add("Detail")
    Dim Name As String
    Dim CanonicalName As String
    For Each psObject As PSObject In results
        dt.Rows.Add(psObject.ToString)
    Next

    Return dt

End Function

Здесь является результатом VB. NET:

Detail
@{Name=PC037; operatingSystem=Windows 7 Professional; LastLogonDate=1/13/2020 10:04:23 AM; Description=; whenChanged=1/17/2020 1:22:08 PM}   
@{Name=PC041;  operatingSystem=Windows 7 Professional; LastLogonDate=2/10/2019 4:43:31 PM; Description=; whenChanged=2/10/2019 4:47:05 PM}   
@{Name=PC040; operatingSystem=Windows 7 Professional; LastLogonDate=4/8/2019 10:03:38 PM; Description=; whenChanged=4/11/2019 6:29:25 AM}    
@{Name=PC009;  operatingSystem=Windows 7 Professional; LastLogonDate=3/6/2019 8:04:59 AM; Description=; whenChanged=3/6/2019 8:09:39 AM}

1 Ответ

0 голосов
/ 13 апреля 2020

Наконец я нашел ответ самостоятельно.

Чтобы извлечь свойства из объекта PowerShell, мне нужно указать c имя элемента, не может использовать индекс свойства объекта PowerShell.

## Правильный синтаксис ##

psObject.Properties("Name").Value.ToString
psObject.Properties("CanonicalName").Value.ToString
psObject.Properties("operatingSystem").Value.ToString
psObject.Properties("LastLogonDate").Value.ToString
psObject.Properties("whenChanged").Value.ToString
psObject.Properties("Description").Value.ToString

## Неверный синтаксис ##

psObject.Properties(0).Value.ToString
psObject.Properties(1).Value.ToString
psObject.Properties(2).Value.ToString
psObject.Properties(3).Value.ToString
psObject.Properties(4).Value.ToString
psObject.Properties(5).Value.ToString

Вот код (Dynami c создать столбец в функции: PSObjectToDataTable):

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim func As New clsFunction
    Dim command As String = "Get-ADComputer -Filter { OperatingSystem -NotLike '*Windows Server*'} -Property * | select Name, CanonicalName, operatingSystem, LastLogonDate, Description, whenChanged | Where {($_.LastLogonDate -lt (Get-Date).AddDays(-90)) -and ($_.LastLogonDate -ne $NULL)}"

    Dim arr As New ArrayList
    arr.Add("Name")
    arr.Add("CanonicalName")
    arr.Add("operatingSystem")
    arr.Add("LastLogonDate")
    arr.Add("whenChanged")
    arr.Add("Description")

    Me.GridView1.DataSource = func.PSObjectToDataTable(command, arr)
    Me.GridView1.DataBind()

End Sub

Function PSObjectToDataTable(ByVal command As String, ByVal arr As ArrayList) As DataTable

    ' Initialize PowerShell engine
    Dim Ps As PowerShell = PowerShell.Create()

    ' add the script the PowerShell command
    Ps.Commands.AddScript(command)

    ' Execute the script
    Dim results = Ps.Invoke()

    Dim dt As DataTable = New DataTable()
    Dim dr As DataRow = Nothing

    'Dynamic create cloumn
    For i = 0 To arr.Count - 1
        dt.Columns.Add(arr(i))
    Next

    For Each psObject As PSObject In results

        'Assign value to dynamic column
        dr = dt.NewRow()
        For i = 0 To arr.Count - 1

            'Check if object is null
            If psObject.Properties(arr(i)).Value Is Nothing Then
                dr(i) = ""
            Else
                dr(i) = psObject.Properties(arr(i)).Value.ToString
            End If

        Next
        dt.Rows.Add(dr)
    Next

    Return dt

End Function
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...