Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2013-11-04
25
Medium Priority
?
885 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
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 1020 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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
In the absence of a fully-fledged GPO Management product like AGPM, the script in this article will provide you with a simple way to watch the domain (or a select OU) for GPOs changes and automatically take backups when policies are added, removed o…
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…

721 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