Home > Blockchain >  Is there a way in powershell to select what info needs to be the header so i can construct it to a t
Is there a way in powershell to select what info needs to be the header so i can construct it to a t

Time:01-29

I want to have a script that i can start and it gives me all the groups starting with APS- and its members

I want to get a HTML where it says in the Header : the group and in the table the Users

this is the code i got so far :

$properties = 'GivenName', 'Surname', 'UserPrincipalName'
Get-ADGroup -Filter {name -like "APS-*"} | ForEach {
$groupName = $_.Name
    Get-ADGroupMember -Identity $_.SamAccountName |Get-ADUser -Property $properties |Select 
@{N='GroupName';E={$groupName}},'GivenName', 'Surname', 'UserPrincipalName'}

But this give me a list of group,givenname,Surename,userprincipal

i want to get : Organized like this

Is there a way of getting this ?

CodePudding user response:

please consider the following points in order to accomplish the needed result

  1. the variable $properties contains common values, you do not need to pass it to `Get-ADUser to get its values
  2. You need to specify the parameter recursive to the command Get-ADGroupMember in order to get all child users within child groups.
  3. If you need to output the result in HTML format you can use the command ConvertTo-Html

I modified your code to output the needed format, please check it

$groups = Get-ADGroup -Filter {name -like "APS-*"}
$list = foreach ($group in $groups) {
        $groupName = $group.Name
        Get-ADGroupMember -Identity $group.SamAccountName -Recursive | Get-ADUser | select @{N='GroupName';E={$groupName}},'GivenName', 'Surname', 'UserPrincipalName'
        }
$out = $list | Group-Object GroupName 
[string]$out_html = foreach ($item in $out){
$item.group | Select-Object 'GivenName', 'Surname', 'UserPrincipalName' | ConvertTo-Html -PreContent "<br>$($item.Name)<br><br>"
}
$out_html| Out-File .\groups.html

if you need to exclude specific users from the report, you can filter the output of Get-ADGroupMember using the Where clause as follow

# i.e. to exclude specific samaccountnames
$execlusionList = @("SamAccountName1","SamAccountName2") 
Get-ADGroupMember -Identity $group.SamAccountName -Recursive | where {$_.samaccountname -notin $execlusionList} | Get-ADUser | select @{N='GroupName';E={$groupName}},'GivenName', 'Surname', 'UserPrincipalName'
  •  Tags:  
  • Related