Solved

AD Group Members to SQL Table

Posted on 2014-02-27
14
643 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 33

Expert Comment

by:paulmacd
Comment Utility
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
Comment Utility
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
Comment Utility
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 33

Expert Comment

by:paulmacd
Comment Utility
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
Comment Utility
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 33

Expert Comment

by:paulmacd
Comment Utility
"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
Comment Utility
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:geohixon
Comment Utility
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 33

Expert Comment

by:paulmacd
Comment Utility
Try...
     $insert_stmt = "INSERT INTO ADGroupMembers (GroupName, Name) VALUES ($Results.GroupName, $Results.Name)"
0
 

Author Comment

by:geohixon
Comment Utility
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 33

Expert Comment

by:paulmacd
Comment Utility
Try...
    $cmd.ExecuteScalar()
0
 

Author Comment

by:geohixon
Comment Utility
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
Comment Utility
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
Comment Utility
was able to figure it out by doing some other google searches
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Performance is the key factor for any successful data integration project, knowing the type of transformation that you’re using is the first step on optimizing the SSIS flow performance, by utilizing the correct transformation or the design alternat…
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.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

772 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

11 Experts available now in Live!

Get 1:1 Help Now