Need to get these results from powershell into a sql table.

Walter Cantin 1 Reputation point
2020-11-24T00:32:10.32+00:00

$adgroups = Get-ADGroup -Filter "name -like 'DL'" | sort name

$data = foreach ($adgroup in $adgroups) {
$members = $adgroup | get-adgroupmember | sort name
foreach ($member in $members) {
[PSCustomObject]@{
Group = $adgroup.name
Members = $member.SamAccountName
}
}
}

$data

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,574 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 47,306 Reputation points
    2020-11-24T03:02:37.26+00:00

    The easiest way may be to create a CSV and import the CSV into the SQL table.

    Get-ADGroup -Filter "name -like 'DL'" | #Is the filter correct? Or should it be "DL*"?
        Sort-Object name |
            ForEach-Object
                $groupname = $_.name
                Get-ADGroupMember $_ | 
                    Sort-Object name |
                        ForEach-Object{
                            [PSCustomObject]@{
                                Group = $groupname
                                Members = $_.SamAccountName
                            }
                        } | Export-Csv SomeFileName.csv -NoTypeInformation
    

    If you want to use PowerShell to import the CSV there are examples of how to do this if you search for "powershell import csv into sql".

    0 comments No comments

  2. Ian Xue 38,301 Reputation points Microsoft Vendor
    2020-11-24T05:58:23.647+00:00

    Hi,

    You can use Invoke-Sqlcmd to execute Transact-SQL statements if you need to insert data into a sql table with a powershell script.
    For more details you can refer to this link
    https://learn.microsoft.com/en-us/powershell/module/sqlserver/invoke-sqlcmd?view=sqlserver-ps

    Best Regards,
    Ian

    ============================================

    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 Answers by the question author, which helps users to know the answer solved the author's problem.