I want to pull a list of users from a table, lookup their email using Get-ADUser and write the result back to a SQL table. So far I can save the resultset to a csv. file, but how to write to a table instead.
$connString = "Server = 'sql1'; Database = 'test'; Integrated Security = True"
$QueryText = 'SELECT [ADUser] FROM [test].[dbo].[Users]'
$SqlConnection = new-object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $connString
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = $QueryText
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
$DataAdapter.Fill($dataset)
$dataset.Tables[0] | ForEach {
Get-ADUser -identity $_.ADUser -Properties Name, SamAccountName,mail |
Select Name, SamAccountName, mail |
Export-CSV C:\Users\export3.csv -Append -Encoding UTF8
}
I would use the awesome PowerShell community DBATools module for this. It's written by some long-time PowerShell and SQL MVPs and makes this an easy job.
First, install the module with
Install-Module DBATools
The module has two commands we'll need to make this work. First, you convert regular PowerShell objects into a SQL DataTable by using ConvertTo-DBADataTable
, then you write it to a SQL DB using Write-DBADataTable
.
So here's what that looks like. I start by creating a new SQL DB called DBATools
on my SQL instance named SCCM
. Next, I get a list of users I want to insert into a table.
Next, I pipe this into | ConvertTo-DbaDataTable
| ConvertTo-DbaDataTable
and store it in a variable.
$DataTable = get-aduser -Filter * | select Name,DistinguishedName,SurName | ConvertTo-DbaDataTable
And finally, I run Write-DBADataTable
to write these rows to a new table (creating the new table by adding -AutoCreateTable
)
Write-DbaDataTable -SqlInstance SCCM -Database DBATools `
-InputObject $DataTable -Table UserTable -AutoCreateTable
Now, I go over to SSMS and refresh to see my new table has been created, with appropriate columns! Awesome, and easey-peasey!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.