Solved

Powershell script that can pull correct group members from filer or remote server

Posted on 2013-11-04
25
795 Views
Last Modified: 2013-11-07
Hi

I am trying modify script that would pull group members from filer and export to cvs file.
My script is  adding already found it members and adding them to next row "multiplays". It looks like is copy members from above  row and adds to new row
Also, is it possible to remove SID during output file creation , there is a lot of them and i would like to have them remove automatically before output file is created.



$Groups = Get-Content C:\LocalGroupsList.txt
$MemberNames = @()
$MasterArray = @()

$Server=bos-ref
       
        foreach ( $LocalGroup in $Groups ) {
        Write-Host $LocalGroup
            $TempArray = @()
            $TempArray = "" | Select ServerName, GroupName, MemberNames
           
            [string]$TempArray.ServerName = $Server
            [string]$TempArray.GroupName = $LocalGroup
            $Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
            $Members = @($Group.psbase.Invoke("Members"))

            $Members | ForEach-Object {
                $MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) + ','
            }
       
           
            [string]$TempArray.MemberNames = $MemberNames
      #Copy the contents of the TempArray into the masterArray. The TempArray is renewed for the next server.
         $MasterArray += $TempArray
         
        }
       
$MasterArray | Export-CSV C:\ListOfMembers.csv -NoType
Output-file.xlsx
0
Comment
Question by:michalek19
  • 13
  • 12
25 Comments
 
LVL 40

Expert Comment

by:Subsun
ID: 39623723
Try..
$Groups = Get-Content C:\LocalGroupsList.txt
$MemberNames = @()
$MasterArray = @()

$Server = "bos-ref"
       
        foreach ( $LocalGroup in $Groups ) {
        Write-Host $LocalGroup
            $TempArray = @()
            $TempArray = "" | Select ServerName, GroupName, MemberNames
           
            [string]$TempArray.ServerName = $Server
            [string]$TempArray.GroupName = $LocalGroup
            $Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
            $Members = @($Group.psbase.Invoke("Members"))
						$MemberNames = @()
						$Members | ForEach-Object {
									$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) + ',' | ?{$_ -notmatch "^S-1-5-21-"}
            }
       			
           
            [string]$TempArray.MemberNames = $MemberNames
      #Copy the contents of the TempArray into the masterArray. The TempArray is renewed for the next server.
 $MasterArray += $TempArray
         
        }
       
$MasterArray | Export-CSV C:\ListOfMembers.csv -NoType 

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
ID: 39623742
A bit shortened code..
$Groups = Get-Content C:\LocalGroupsList.txt

$Server = "bos-ref"
       
$Groups | % {

Write-Host $_
											
	New-Object PSObject -Property @{
	ServerName = $Server
	GroupName = $_
	MemberNames = (@($([ADSI]"WinNT://$Server/$_,group").psbase.Invoke("Members")) | % {
	              $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) | ?{$_ -notmatch "^S-1-5-21-"}
	              }) -join ","
	              }  
} | Select ServerName,GroupName,MemberNames | Export-CSV C:\ListOfMembers.csv -NoType

Open in new window

0
 

Author Comment

by:michalek19
ID: 39628429
Hi Subsun

Thank you so much for you help. Finally i got correct output.
I have one more question is it possible to add to this scrip antother script to run against AD and to check if the provided list of local groups already exists in AD. I would like to get CSV file generate with groups that already exists.

Or compare "LocalGroupsList.txt" to AD groups and generate output CSV file.

I will increase points if you can help me to create that script
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 40

Expert Comment

by:Subsun
ID: 39628515
Are you trying to get members of AD group?.. If yes and if you have win 2008 R2 DC's, then you can try..

Import-Module Activedirectory
Get-Content C:\LocalGroupsList.txt | %{
	$Group = $_
	Get-ADGroupMember $Group | Select @{N="GroupName";E={$Group}},SamAccountName
} | Select GroupName,SamAccountName | Export-CSV C:\ListOfMembers.csv -NoType

Open in new window

0
 

Author Comment

by:michalek19
ID: 39629172
Let me see if this script works and i will let you know if this is what i need.
But, thx for all your help
0
 

Author Comment

by:michalek19
ID: 39630224
I am getting errors please check attachment

The term 'Get-ADGroupMember' is not recognized as the name of a cmdlet, functio
n, script file, or operable program. Check the spelling of the name, or if a pa
th was included, verify that the path is correct and try again.
memberofAD.txt
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39630253
Do you have win 2008 R2 or later domain controller? If yes, Did you import Activedirectory module?
Import-Module Activedirectory
0
 

Author Comment

by:michalek19
ID: 39630533
We have Win 2008 R2
Where Active Directory module should be imported from
I have tried searching for what I am missing here, but am coming up blank.  Any insight will be appreciated.



I tried this and i got that message

PS C:\> import-module ActiveDirectory
Import-Module : The specified module 'ActiveDirectory' was not loaded because n
o valid module file was found in any module directory.
At line:1 char:14
+ import-module <<<<  ActiveDirectory
    + CategoryInfo          : ResourceUnavailable: (ActiveDirectory:String) [I
   mport-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Comm
   ands.ImportModuleCommand
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39630632
I hope you are running this code in Windows Server 2008 R2 Domain Controller. With Windows Server 2008 R2 Domain Controller, when you install the AD DS role. The AD PowerShell module will also be installed during this process. So it should be available to import..
0
 

Author Comment

by:michalek19
ID: 39630652
ohh, i am not running this on DC, i am running this on Jumphost "jump server" that has powershell installed
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39630663
In that case you need to install remote admin tools on jump server.. Refer the article for details..
http://technet.microsoft.com/en-us/magazine/gg413289.aspx
0
 

Author Comment

by:michalek19
ID: 39630784
ok, i did import-module ActiveDirectory

But, I am getting error

PS C:\Users\adm-rejman> import-module ActiveDirectory
PS C:\Users\adm-rejman> ./admember.ps1
The term './admember.ps1' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:15
+ ./admember.ps1 <<<<
    + CategoryInfo          : ObjectNotFound: (./admember.ps1:String) [], Comm
   andNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39631020
Do you have the scrip in same folder C:\Users\adm-rejman? if not give the complete path to run the script..
PS C:\> C:\temp\Test.ps1

Open in new window

0
 

Author Comment

by:michalek19
ID: 39631091
that seems to be working.  great

is it possible to  combine these two script in  one script.

----------------------------------------------------------------------------------------------

$Groups = Get-Content C:\LocalGroupsList.txt

$Server = "bos-ref"
       
$Groups | % {

Write-Host $_
                                                                  
      New-Object PSObject -Property @{
      ServerName = $Server
      GroupName = $_
      MemberNames = (@($([ADSI]"WinNT://$Server/$_,group").psbase.Invoke("Members")) | % {
                    $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) | ?{$_ -notmatch "^S-1-5-21-"}
                    }) -join ","
                    }  
} | Select ServerName,GroupName,MemberNames | Export-CSV C:\ListOfMembers.csv -NoType
                                           


 -------------------------------------------------------------------------------------

Import-Module Activedirectory
Get-Content C:\LocalGroupsList.txt | %{
      $Group = $_
      Get-ADGroupMember $Group | Select @{N="GroupName";E={$Group}},SamAccountName
} | Select GroupName,SamAccountName | Export-CSV C:\ListOfMembers.csv -NoType
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39631114
Local groups and Ad groups are different? why you want to combine the codes?And what is the output format
as of now first code gives you

ServerName,GroupName,MemberNames

and second one

 GroupName,SamAccountName
0
 

Author Comment

by:michalek19
ID: 39631161
Why you want to combine the codes? It would safe me some time.

Is it possible to get for second output the same format as first output has it

First Output has different format :

ServerName          GroupName      MemberNames
sn-n      2012                 Co                      pcolexary,hbxalxd,dgxbitz,pcoxry,hbaxd,doxmay,jruxls
sn-n      2012                 Comp              tekxta,pexenbe,joaxop,xrim,xeam


Second output the format is different:

GroupName      SamAccountName
AMG_x      djason
Blux      bely
Blux      garn
DBxAXX      wint
DBAXX      ba
DBAXX      har
DBAXX      rad
DBAXX      jyo
DBAXX      kish
DBAXX      kki
DBAXX      amah
DBxAXX      kpop
DBAXX      shou
DBAXX      awa
dcicoxnxxxx      han
dcicoxnxxxx      smul
dcicoxnxxxx      lyt
dcicoxnxxxx      arez
dcicoxnxxxx      ttrev
dcicoxnxxxx      otani
dcicoxnxxxx      kin
0
 
LVL 40

Accepted Solution

by:
Subsun earned 255 total points
ID: 39631175
There wont be any ServerName for AD groups..

If you just want to combine scripts, then you can copy paste both the codes in to notepad and save it in to .ps1 file.. You might need to change the input /output file names.. for example..

$Groups = Get-Content C:\LocalGroupsList.txt

$Server = "bos-ref"
       
$Groups | % {

Write-Host $_
                                                                  
      New-Object PSObject -Property @{
      ServerName = $Server
      GroupName = $_
      MemberNames = (@($([ADSI]"WinNT://$Server/$_,group").psbase.Invoke("Members")) | % {
                    $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) | ?{$_ -notmatch "^S-1-5-21-"}
                    }) -join ","
                    }  
} | Select ServerName,GroupName,MemberNames | Export-CSV C:\ListOfLocalMembers.csv -NoType

Import-Module Activedirectory
Get-Content C:\ADGroupsList.txt | %{
      $Group = $_
      Get-ADGroupMember $Group | Select @{N="GroupName";E={$Group}},SamAccountName
} | Select GroupName,SamAccountName | Export-CSV C:\ListOfADMembers.csv -NoType 

Open in new window

0
 
LVL 40

Expert Comment

by:Subsun
ID: 39631196
BTB are checking the same list of groups against the server and AD?
0
 

Author Comment

by:michalek19
ID: 39631236
That's correct
0
 

Author Comment

by:michalek19
ID: 39631254
Perhaps you can simply checking the same list of groups against the server and AD
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39631547
Try this and see if it works for you..
$ErrorActionPreference = "STOP"
Import-Module Activedirectory
$Groups = Get-Content C:\LocalGroupsList.txt

$Server = "bos-ref"
       
$Groups | % {
Write-Host $_
$Lmembers = $null
$ADmembers = $null
Try {

$Lmembers = (@($([ADSI]"WinNT://$Server/$_,group").psbase.Invoke("Members")) | % {
           $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) | ?{$_ -notmatch "^S-1-5-21-"}
           }) -join ","

If ($Lmembers -ne $null){
	New-Object PSObject -Property @{
	ServerName = $Server
	GroupType = "Local"
	GroupName = $_
	MemberNames = $Lmembers
	}
 }
}Catch{}

Try {

$ADmembers = (Get-ADGroupMember $_ | Select -ExpandProperty SamAccountName) -join ","

If ($ADmembers -ne $null){
	New-Object PSObject -Property @{
	ServerName = $Server
	GroupType = "AD"
	GroupName = $_
	MemberNames = $ADmembers
	}
 }
}Catch{}

} | Select ServerName,GroupType,GroupName,MemberNames | Export-CSV C:\ListOfADMembers.csv -NoType 

Open in new window

0
 

Author Comment

by:michalek19
ID: 39631586
You are very good sir. It works like charm. thank you
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39631632
Good.. BTB you didn't increase the points.. :-P
0
 

Author Comment

by:michalek19
ID: 39631811
Can i still increase these points?

I am sorry
0
 
LVL 40

Expert Comment

by:Subsun
ID: 39632591
I am not sure.. Probably Mod’s  can change it.. But no worries it’s ok.. :-)
0

Featured Post

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Utilizing an array to gracefully append to a list of EmailAddresses
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
This tutorial will show how to configure a single USB drive with a separate folder for each day of the week. This will allow each of the backups to be kept separate preventing the previous day’s backup from being overwritten. The USB drive must be s…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

831 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