From PowerShell to VB NET to DataGridView

Konstantin 41 Reputation points
2022-02-15T22:42:48.803+00:00

Hi! Need help in transferring the result from PowerShell to VB NET to DataGridView.

Windows for business | Windows Server | User experience | PowerShell
Developer technologies | VB
{count} votes

1 answer

Sort by: Most helpful
  1. Xingyu Zhao-MSFT 5,381 Reputation points
    2022-02-16T07:01:10.723+00:00

    Hi @Konstantin ,
    You can add | out-file yourFilePath -append to the end of the PowerShell command, and it will save the output string to a text file.
    Then the following code can read the file and convert the string to DataTable.

            Dim dt As DataTable = New DataTable()  
            Dim lines As String() = File.ReadAllLines(filePath).Where(Function(x) Not String.IsNullOrWhiteSpace(x)).ToArray()  
            Dim str As String = ""  
      
            For i As Integer = 0 To lines.Length - 1  
                If i = 1 Then  
                    Continue For  
                Else  
                    Dim items As String() = lines(i).Split(" "c).Where(Function(x) Not String.IsNullOrWhiteSpace(x)).ToArray()  
                    Dim dr As DataRow = dt.NewRow()  
      
                    For j As Integer = 0 To items.Length - 1  
                        If i = 0 Then  
                            dt.Columns.Add(items(j))  
                        Else  
                            If Not items(j).Contains(":") Then  
                                dr(j) = items(j)  
                                str = items(j)  
                            Else  
                                dr(j - 1) = str & items(j)  
                            End If  
                        End If  
                    Next  
                    dt.Rows.Add(dr)  
                End If  
            Next  
            DataGridView1.DataSource = dt.Rows.Cast(Of DataRow)().Where(Function(row) Not row.ItemArray.All(Function(field)   
                                                            String.IsNullOrWhiteSpace(TryCast(field, String)))).CopyToDataTable()  
    

    Hope it could be helpful.
    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.