Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 912
  • Last Modified:

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

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
michalek19
Asked:
michalek19
  • 13
  • 12
1 Solution
 
SubsunCommented:
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
 
SubsunCommented:
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
 
michalek19Author Commented:
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
 The Evil-ution of Network Security Threats

What are the hacks that forever changed the security industry? To answer that question, we created an exciting new eBook that takes you on a trip through hacking history. It explores the top hacks from the 80s to 2010s, why they mattered, and how the security industry responded.

 
SubsunCommented:
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
 
michalek19Author Commented:
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
 
michalek19Author Commented:
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
 
SubsunCommented:
Do you have win 2008 R2 or later domain controller? If yes, Did you import Activedirectory module?
Import-Module Activedirectory
0
 
michalek19Author Commented:
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
 
SubsunCommented:
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
 
michalek19Author Commented:
ohh, i am not running this on DC, i am running this on Jumphost "jump server" that has powershell installed
0
 
SubsunCommented:
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
 
michalek19Author Commented:
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
 
SubsunCommented:
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
 
michalek19Author Commented:
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
 
SubsunCommented:
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
 
michalek19Author Commented:
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
 
SubsunCommented:
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
 
SubsunCommented:
BTB are checking the same list of groups against the server and AD?
0
 
michalek19Author Commented:
That's correct
0
 
michalek19Author Commented:
Perhaps you can simply checking the same list of groups against the server and AD
0
 
SubsunCommented:
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
 
michalek19Author Commented:
You are very good sir. It works like charm. thank you
0
 
SubsunCommented:
Good.. BTB you didn't increase the points.. :-P
0
 
michalek19Author Commented:
Can i still increase these points?

I am sorry
0
 
SubsunCommented:
I am not sure.. Probably Mod’s  can change it.. But no worries it’s ok.. :-)
0

Featured Post

New Tabletop Appliances Blow Competitors Away!

WatchGuard’s new T15, T35 and T55 tabletop UTMs provide the highest-performing security inspection in their class, allowing users at small offices, home offices and distributed enterprises to experience blazing-fast Internet speeds without sacrificing enterprise-grade security.

  • 13
  • 12
Tackle projects and never again get stuck behind a technical roadblock.
Join Now