Solved

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

Posted on 2013-11-04
25
753 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 40

Expert Comment

by:Subsun
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 40

Expert Comment

by:Subsun
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
BTB are checking the same list of groups against the server and AD?
0
 

Author Comment

by:michalek19
Comment Utility
That's correct
0
 

Author Comment

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

Expert Comment

by:Subsun
Comment Utility
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
Comment Utility
You are very good sir. It works like charm. thank you
0
 
LVL 40

Expert Comment

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

Author Comment

by:michalek19
Comment Utility
Can i still increase these points?

I am sorry
0
 
LVL 40

Expert Comment

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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

New Windows 7 Installations take days for Windows-Updates to show up and install. This can easily be fixed. I have finally decided to write an article because this seems to get asked several times a day lately. This Article and the Links apply to…
A safe way to clean winsxs folder from your windows server 2008 R2 editions
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

762 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

6 Experts available now in Live!

Get 1:1 Help Now