I want insert some AD attributes with PowerShell into a SQL table. So far so good:
$insert = @'
INSERT INTO [mdb].[dbo].[import](id,userid)
VALUES ('{0}','{1}')
'@
Try {
$connectionString = 'Data Source=serverdb;Initial Catalog=mdb;Integrated Security=SSPI'
$conn = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$conn.Open()
$cmd = $conn.CreateCommand()
$counter = 0
Get-ADUser -Filter * -SearchBase "OU=company,DC=company,DC=state,DC=de" | Select @{Name="ID";Expression={ $global:counter; $global:counter++ }},SamAccountName |`
ForEach-Object {
$cmd.CommandText = $insert -f $counter,$_.SamAccountName
$cmd.ExecuteNonQuery()
}
$conn.Close()
}
Catch {
Throw $_
}
The output from get-ADUser is right, but the insert throws an error, that the primary key has duplicates. The incrementing must be wrong.
Can anybody help? THANKS!