Solved

AD Group Members to SQL Table

Posted on 2014-02-27
14
651 Views
Last Modified: 2014-03-08
Here is my powershell statement with associated error.  Can't figure out what I am doing wrong.


PS H:\> Get-Content C:\temp\groups.txt | ForEach-Object {
$Group = $_
$Results = Get-ADGroupMember $Group |
      Select-Object @{Name="Group Name";Expression={$Group}},name
} | out-host
$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=LSI-1; Initial Catalog=databasename; Integrated Security=SSPI")
$conn.Open()
$insert_stmt = "INSERT INTO ADGroupMembers('$Results')"
$cmd = $conn.CreateCommand()
$cmd.CommandText = $insert_stmt
$cmd.ExecuteNonQuery()
$conn.Close()


Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near ')'."
At line:11 char:1
+ $cmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException

Any assistance would be greatly appreciated.  Also I am planning on running this script once a day and would probably like to drop and re-add the table with the new data.  Insight into this would also be beneficial
0
Comment
Question by:geohixon
  • 8
  • 5
14 Comments
 
LVL 34

Expert Comment

by:Paul MacDonald
ID: 39892558
It may be expecting a VALUES statement:
     INSERT INTO ADGroupMembers VALUES ('$Results')

http://technet.microsoft.com/en-us/library/dd776381(v=sql.105).aspx
0
 
LVL 14

Expert Comment

by:Justin Yeung
ID: 39892564
I am not sure about the SQL part but | out-host after } of each object will only result in the last searched result

you should include | out-host within the } after ,name
0
 

Author Comment

by:geohixon
ID: 39892592
Getting closer but now get this (see screenshot).
Also the table names in the table are exactly the same in the output  "Group Name" and "Name" set to nvarchar(50)

screenshot of results
0
 
LVL 34

Expert Comment

by:Paul MacDonald
ID: 39892634
Okay, so the error is self-explanatory - "the number of supplied values does not match the table definition" so you either need to tell it what column the values go into or you need to supply values for all the columns.
0
 

Author Comment

by:geohixon
ID: 39892663
This is what I am trying to figure out.  what should be there.  I tried this

Get-Content C:\temp\groups.txt | ForEach-Object {
$Group = $_
$Results = Get-ADGroupMember $Group |
      Select-Object @{Name="GroupName";Expression={$Group}},name
} | out-host
$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=LSI-1; Initial Catalog=database; Integrated Security=SSPI")
$conn.Open()
$insert_stmt = "INSERT INTO ADGroupMembers VALUES($Results.GroupName,$Results.Name)"
$cmd = $conn.CreateCommand()
$cmd.CommandText = $insert_stmt
$cmd.ExecuteNonQuery()
$conn.Close()

Exception calling "ExecuteNonQuery" with "0" argument(s): "The name ".GroupName" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not
permitted."
At line:11 char:1
+ $cmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException
0
 
LVL 34

Expert Comment

by:Paul MacDonald
ID: 39892699
"This is what I am trying to figure out.  what should be there."
What's your table's structure?  Generally the command takes the form of:
    INSERT INTO table (columnname1, columnname2, columnname3) VALUES (value1, value2, value3)
0
 

Author Comment

by:geohixon
ID: 39892712
results provides two columns, "GroupName" and "name" as seen in the screenshot above, the table contains the exact two column names.  Essentially I need the results from
Get-Content C:\temp\groups.txt | ForEach-Object {
$Group = $_
$Results = Get-ADGroupMember $Group |
      Select-Object @{Name="GroupName";Expression={$Group}},name | out-host
}
 entered into a SQL Table called ADGroupMembers that has two columns as well (GroupName, Name)
0
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 

Author Comment

by:geohixon
ID: 39892785
maybe my approach is all wrong to start with and there is a better way.  I need to take groups from a text file, query AD and find all the users that are in those said groups then take the results and insert the group name and the member into a sql table.  Is there another approach I should be taking for this?  Thanks again as I am new to powershell (as you can tell) and trying to piece together stuff from google to get what I need.
0
 
LVL 34

Expert Comment

by:Paul MacDonald
ID: 39893027
Try...
     $insert_stmt = "INSERT INTO ADGroupMembers (GroupName, Name) VALUES ($Results.GroupName, $Results.Name)"
0
 

Author Comment

by:geohixon
ID: 39893182
Get this error.


INSERT INTO ADGroupMembers (GroupName, Name) VALUES(.groupname, .name)
-1
Exception calling "ExecuteNonQuery" with "0" argument(s): "The name ".groupname" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not
permitted."
At line:16 char:1
+ $cmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException
0
 
LVL 34

Expert Comment

by:Paul MacDonald
ID: 39893209
Try...
    $cmd.ExecuteScalar()
0
 

Author Comment

by:geohixon
ID: 39893246
Still no go...

INSERT INTO ADGroupMembers (GroupName, Name) VALUES(.groupname, .name)
-1
Exception calling "ExecuteScalar" with "0" argument(s): "The name ".groupname" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not
permitted."
At line:16 char:1
+ $cmd.ExecuteScalar()
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException
 
when I try this I see all the user info under 1 row.  

Get-Content C:\temp\groups.txt | ForEach-Object {
$Group = $_
$Results = Get-ADGroupMember $Group  
     # Select-Object @{Name="GroupName";Expression={$Group}},name, samaccountname | Out-Host
}
$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=LSI-1; Initial Catalog=db; Integrated Security=SSPI")
$conn.Open()
$insert_stmt = "INSERT INTO ADGroupMembers VALUES('"+ $group +"','"+ $Results +"')"
write $insert_stmt
$cmd = $conn.CreateCommand()
#delete existing contents of this table (enter SysTrack DB Name below)
$cmd.CommandText = "truncate table " + $db + ".ADGroupMembers"
$cmd.ExecuteNonQuery()
#import new/current data
$cmd.CommandText = $insert_stmt
$cmd.ExecuteNonQuery()
$conn.Close()

INSERT INTO ADGroupMembers VALUES('ACL_Builds','CN=Linux Build,OU=Engineering,OU= Hills,DC=domain,DC=org CN=BUILD1,OU=Engineering Computers,OU=Engineering,OU=HQ,DC=domain,DC=org CN=Support Group,OU=Su
pport Users,OU=Support,OU=HQ,DC=domain,DC=org CN=Domain Admins,CN=Users,DC=domain,DC=org CN=Engineering Group,OU=Engineering Users,OU=Engineering,OU=HQ,DC=domain,DC=org')
-1
Exception calling "ExecuteNonQuery" with "0" argument(s): "String or binary data would be truncated.
The statement has been terminated."
At line:16 char:1
+ $cmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException
0
 

Accepted Solution

by:
geohixon earned 0 total points
ID: 39900725
Figured it out.

$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=sqlserver; Initial Catalog=databasename; Integrated Security=SSPI")
$conn.Open()

$cmd = $conn.CreateCommand()
#delete existing contents of this table (enter sqlDB Name below)
$cmd.CommandText = "truncate table " + $dbname+ ".ADGroupMembers"
$cmd.ExecuteNonQuery()
#import new/current data

$content = Get-Content c:\temp\groups.txt
foreach ($Group in $content)
{
     
     $Results = Get-ADGroupMember $Group  
           Select-Object @{Name="GroupName";Expression={$Group}},name

     foreach ($name in $Results)
     {
          $insert_stmt = "INSERT INTO ADGroupMembers VALUES('"+ $group +"', '"+ $name.name +"')"
          write $insert_stmt
          $cmd.CommandText = $insert_stmt
          $cmd.ExecuteNonQuery()
          }
          }
          $conn.Close()
0
 

Author Closing Comment

by:geohixon
ID: 39914440
was able to figure it out by doing some other google searches
0

Featured Post

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now