PowerShell Script – List Certain ADGroups as Column Headings & their Users as Row Headings showing who is in which groups

huangapple go评论70阅读模式
英文:

PowerShell Script - List Certain ADGroups as Column Headings & their Users as Row Headings showing who is in which groups

问题

以下是您要翻译的内容:

# Set the filename for the output Excel file
$dateTimeStr = (get-date).tostring('yyyyMMdd_HHmmss')
[String]$ExcelPath  = "C:\Temp\DeptSsrsAdGroups_$dateTimeStr.xlsx"

# Set the list of AD Groups to export results for
[String[]]$AdGroups = ("Group1", "Group3", "Group10")

# Loop through each AD Group in the list
# Export certain properties/fields for each user/member in the AD Group to a worksheet with the same name as the AD Group
# Each excel worksheet will have a table with the AD Group name, auto sized and the top row frozen for formatting/layout purposes.
ForEach($AdGroup in $AdGroups)
{
     Get-AdGroupMember -Identity $AdGroup -Recursive | `
     Get-ADUser -Properties SamAccountName,Surname,GivenName,DisplayName,EmailAddress,Enabled,Title,Department,Office,Company,Manager | `
     #Select SamAccountName,Surname,GivenName,DisplayName,EmailAddress,Enabled,Title,Department,Office,Company,Manager | `
     Select SamAccountName,Surname,GivenName,DisplayName,EmailAddress,Enabled,@{n="ManagerName";e={(Get-AdUser $_.manager -Properties DisplayName).DisplayName}},Title,Department,Office,Company | `
     Sort-Object Surname,GivenName | `
     Export-Excel -Path $ExcelPath -AutoSize -WorksheetName $AdGroup -TableName $AdGroup -FreezeTopRow
} 
英文:

How do I do this in PowerShell please?

I can only find a way to list Users in groups or list groups for a user, not list both in this way.

List AdUsers (in certain groups) as row headings and a subset of AdGroups as Column headings (eg: Group1, Group3 & Group10 only) with the column values having 1's or Y's to show which of those groups the users are in.

eg:

Group1 members are:
UserA
UserC

Group3 members are:
UserA
UserB

Group10 members are:
UserB
UserC

What I'm expecting:
User       Group1    Group3    Group10
UserA      1         1
UserB                1         1
UserC      1                   1

I have this so far, but want to add the matrix shown above as a summary worksheet in the Excel file.

# The ActiveDirectory (AD) App generally only lists Staff Ids which is painful when trying to find out each staff members name to determine who needs to be removed from what groups.
# This script will:
# * Export certain properties of AD Group Members (eg: StaffIds, Names, Depts, etc) for each SSRS AD Group that <Dept> uses for <Dept> RAP Report Security.
# * Exports the data to an Excel Spreadsheet with 1 worksheet per AD Group, listing it's members.
#
# PRE-REQUISITES: 
# * Export-Excel module must be installed
# * ActiveDirectory module must be installed
# ** Remote Server Administration Tools (RSAT) must be installed
# --------------------------------------------------------------------------

# Shows what Properties are available that can be added to lines 30-35 below
#Get-ADUser 12345678 -Properties *

Clear-Host

# Set the filename for the output Excel file
$dateTimeStr = (get-date).tostring('yyyyMMdd_HHmmss')
[String]$ExcelPath  = "C:\Temp\DeptSsrsAdGroups_$dateTimeStr.xlsx"

# Set the list of AD Groups to export results for
[String[]]$AdGroups = ("Group1", "Group3", "Group10")

# Loop through each AD Group in the list
# Export certain properties/fields for each user/member in the AD Group to a worksheet with the same name as the AD Group
# Each excel worksheet will have a table with the AD Group name, auto sized and the top row frozen for formatting/layout purposes.
ForEach($AdGroup in $AdGroups)
{
     Get-AdGroupMember -Identity $AdGroup -Recursive | `
     Get-ADUser -Properties SamAccountName,Surname,GivenName,DisplayName,EmailAddress,Enabled,Title,Department,Office,Company,Manager | `
     #Select SamAccountName,Surname,GivenName,DisplayName,EmailAddress,Enabled,Title,Department,Office,Company,Manager | `
     Select SamAccountName,Surname,GivenName,DisplayName,EmailAddress,Enabled,@{n="ManagerName";e={(Get-AdUser $_.manager -Properties DisplayName).DisplayName}},Title,Department,Office,Company | `
     Sort-Object Surname,GivenName | `
     Export-Excel -Path $ExcelPath -AutoSize -WorksheetName $AdGroup -TableName $AdGroup -FreezeTopRow
} 

# --------------------------------------------------------------------------

答案1

得分: 0

你正在尝试构建一个数据透视表。您需要按用户进行分组,以便将一行用户添加到表中,然后枚举属性。使用类似以下的代码:

$table = [System.Collections.ArrayList]::new()
ForEach($user in $users)
{
   $newRow = New-Object -TypeName psobject
   ForEach($property in $properties)
   {
      $newRow | Add-Member -NotePropertyName propertyName -NotePropertyValue value
   }
   $table.Add($newRow) | Out-Null
}
英文:

You are trying to build a Pivot Table. You need to group by users so you can add one row of users to a table. Then enumerate through the properties. Use code like below

<!-- begin snippet: js hide: false console: true babel: false -->

$table = [System.Collections.ArrayList]::new()
ForEach($user in $users)
{
   $newRow = New-Object -TypeName psobject
   ForEach($property in $properties)
   {
      $newRow | Add-Member -NotePropertyName  propertyName -NotePropertyValue value
   }
   $table.Add($newRow) | Out-Null
}

<!-- end snippet -->

答案2

得分: 0

这是我正在使用的解决方案。
我添加了一个名为“摘要”的工作表,其中包含2列:用户和组。
然后添加了一个名为“PivotData”的工作表,它对“摘要”工作表的数据进行了数据透视。

活动目录(AD)应用程序通常仅列出员工ID,当试图找出每个员工的姓名以确定谁需要从哪些组中删除时,这很痛苦。

此脚本将执行以下操作:

* 导出AD组成员的某些属性(例如:StaffIds、Names、Depts等)供用于 RAP报告安全性的每个SSRS AD组。

* 将数据导出到Excel电子表格

** 每个AD组一个工作表,列出其成员

** 摘要工作表

** PivotData工作表(基于摘要工作表)

先决条件:

* 必须安装Export-Excel模块

* 必须安装ActiveDirectory模块

** 必须安装远程服务器管理工具(RSAT)

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

第一个显示默认属性(-Properties不需要)可用于下面的选择。

第二个显示扩展属性,必须使用-Properties然后选择。

Get-ADUser 12345678

Get-ADUser 12345678 -Properties *

Clear-Host

设置输出Excel文件的文件名

$dateTimeStr = (get-date).tostring('yyyyMMdd_HHmmss')
[String]$ExcelPath = "C:\Temp\SsrsAdGroups_$dateTimeStr.xlsx"

设置要导出结果的AD组列表

[String[]]$AdGroups = ("Group1", "Group3", "Group10")

循环遍历列表中的每个AD组

为AD组中的每个用户/成员导出某些属性/字段到与AD组同名的工作表

每个Excel工作表都将具有一个自动调整大小的包含AD组名称的表,顶部行用于格式/布局目的而冻结。

$UserGroupSummary = @()
ForEach($AdGroup in $AdGroups)
{
# 准备摘要Excel工作表的数据
$Users = Get-AdGroupMember -Identity $AdGroup -Recursive | Get-ADUser -Properties DisplayName |
ForEach { "{0} ({1})" -f $.DisplayName, $.SamAccountName }
ForEach( $User in $Users ) {
$UserGroupSummary += [PSCustomObject]@{
User = $User
Group = $AdGroup
}
}

# AD组Excel工作表
Get-AdGroupMember -Identity $AdGroup -Recursive | `
Get-ADUser -Properties DisplayName,EmailAddress,Enabled,Title,Department,Office,Company,Manager | `
Select SamAccountName,Surname,GivenName,DisplayName,EmailAddress,Enabled,@{n="ManagerName";e={(Get-AdUser $_.manager -Properties DisplayName).DisplayName}},Title,Department,Office,Company | `
Sort-Object Surname,GivenName | `
Export-Excel -Path $ExcelPath -AutoSize -WorksheetName $AdGroup -TableName $AdGroup -FreezeTopRow

}

摘要Excel工作表 - 用户及其匹配的组 - Excel数据透视表的数据源

$UserGroupSummary | Sort-Object User,Group | Export-Excel -Path $ExcelPath -AutoSize -WorksheetName Summary -TableName Summary -FreezeTopRow

向Excel文件(如果存在)添加数据透视表,数据源为摘要工作表

If (Test-Path $ExcelPath)
{
Try {

    # 打开Excel文件
    $excel = Open-ExcelPackage -Path $ExcelPath

    # 在开头创建新的工作表
    Add-Worksheet -ExcelPackage $excel -Activate -MoveToStart -WorksheetName PivotData | Out-Null

    # 向新的Excel工作表添加数据透视表
    Add-PivotTable -ExcelPackage $excel -SourceWorkSheet "Summary" -PivotTableName "PivotData" -PivotTableStyle Medium9 -PivotRows User -PivotColumns Group -PivotData Group #-Activate

    # 保存并关闭Excel文件
    Close-ExcelPackage $excel
}
Catch {
    # 发生错误
    $message = $_
    write-output "ERROR - $message"
    write-warning "ERROR updating existing Excel file $ExcelPath. ABORTING. $message"
}

# 打开Excel文件
$excelObj = New-Object -ComObject Excel.Application
$excelObj.DisplayAlerts = $false;

# 将数据透视表更改为表格格式 - 似乎只有在某种原因下使其可见时才有效
$excelObj.Visible = $true
$excelWb = $excelObj.Workbooks.Open($ExcelPath)
$excelWsh = $excelWb.Sheets("PivotData")
$pivot = $excelWsh.PivotTables(1)
$pivot.RowAxisLayout(1)   # 表格布局
$pivot.EnableFieldList = $false
$excelObj.Visible = $false

# 在PivotData工作表中冻结窗格B3
[void]$excelObj.Cells.Item(3,2).Select()
$excelObj.ActiveWindow.FreezePanes = $True

# 保存并关闭
$excelObj.ActiveWorkbook.SaveAs($ExcelPath, 51)   # xlsx
$excelObj.Workbooks.Close()
$excelObj.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelObj) | Out-Null

}

write-output "已将数据导出到$ExcelPath"

英文:

Here's the solution I'm using.
I added a 'Summary' worksheet which has 2 columns: User & Group.
Then added a 'PivotData' worksheet which pivots the 'Summary' worksheet data.

# The ActiveDirectory (AD) App generally only lists Staff Ids which is painful when trying to find out each staff members name to determine who needs to be removed from what groups.
# This script will:
# * Export certain properties of AD Group Members (eg: StaffIds, Names, Depts, etc) for each SSRS AD Group that &lt;Dept&gt; uses for &lt;Dept&gt; RAP Report Security.
# * Exports the data to an Excel Spreadsheet
# ** 1 worksheet per AD Group, listing it&#39;s members
# ** Summary worksheet
# ** PivotData worksheet (based on Summary worksheet)
#
# PRE-REQUISITES: 
# * Export-Excel module must be installed
# * ActiveDirectory module must be installed
# ** Remote Server Administration Tools (RSAT) must be installed
# --------------------------------------------------------------------------

# 1st shows default properties (-Properties not reqd) that can be used in the Select below.
# 2nd shows extended properties, must use -Properties then Select.
#Get-ADUser 12345678 
#Get-ADUser 12345678 -Properties *

Clear-Host

# Set the filename for the output Excel file
$dateTimeStr = (get-date).tostring(&#39;yyyyMMdd_HHmmss&#39;)
[String]$ExcelPath  = &quot;C:\Temp\SsrsAdGroups_$dateTimeStr.xlsx&quot;

# Set the list of AD Groups to export results for
[String[]]$AdGroups = (&quot;Group1&quot;, &quot;Group3&quot;, &quot;Group10&quot;)

# Loop through each AD Group in the list
# Export certain properties/fields for each user/member in the AD Group to a worksheet with the same name as the AD Group
# Each excel worksheet will have a table with the AD Group name, auto sized and the top row frozen for formatting/layout purposes.
$UserGroupSummary = @()
ForEach($AdGroup in $AdGroups)
{
    # Prepare data for Summary Excel Worksheet
    $Users = Get-AdGroupMember -Identity $AdGroup -Recursive | `
             Get-ADUser -Properties DisplayName | `
             ForEach { &quot;{0}  ({1})&quot; -f $_.DisplayName, $_.SamAccountName } 
    ForEach( $User in $Users ) {
        $UserGroupSummary += [PSCustomObject]@{
                            User  = $User
                            Group = $AdGroup
                        }
    }

    # AdGroup Excel Worksheets
    Get-AdGroupMember -Identity $AdGroup -Recursive | `
    Get-ADUser -Properties DisplayName,EmailAddress,Enabled,Title,Department,Office,Company,Manager | `
    Select SamAccountName,Surname,GivenName,DisplayName,EmailAddress,Enabled,@{n=&quot;ManagerName&quot;;e={(Get-AdUser $_.manager -Properties DisplayName).DisplayName}},Title,Department,Office,Company | `
    Sort-Object Surname,GivenName | `
    Export-Excel -Path $ExcelPath -AutoSize -WorksheetName $AdGroup -TableName $AdGroup -FreezeTopRow
} 
# Summary Excel Worksheet - Users &amp; their matching Groups - data source for an Excel pivot table
$UserGroupSummary | Sort-Object User,Group | Export-Excel -Path $ExcelPath -AutoSize -WorksheetName Summary -TableName Summary -FreezeTopRow

# Add a Pivot Table to the Excel file (if it exists) based on the Summary worksheet
If (Test-Path $ExcelPath) 
{
	Try {

		# Open the Excel file
		$excel = Open-ExcelPackage -Path $ExcelPath

        # Create new worksheet at the start
        Add-Worksheet -ExcelPackage $excel -Activate -MoveToStart -WorksheetName PivotData | Out-Null

		# Add a pivot table to the new Excel worksheet
		Add-PivotTable -ExcelPackage $excel -SourceWorkSheet &quot;Summary&quot; -PivotTableName &quot;PivotData&quot; -PivotTableStyle Medium9 -PivotRows User -PivotColumns Group -PivotData Group #-Activate

		# Save &amp; close the Excel file
		Close-ExcelPackage $excel
	}
	Catch {
		# An error occurred
		$message = $_
		write-output &quot;ERROR - $message&quot;
		write-warning &quot;ERROR updating existing Excel file $ExcelPath. ABORTING. $message&quot;
	}

    # Open the excel file
    $excelObj = New-Object -ComObject Excel.Application
    $excelObj.DisplayAlerts = $false;

    # Change pivot table to tabular format - only seems to work if make Visible true for some reason
    $excelObj.Visible = $true
    $excelWb = $excelObj.Workbooks.Open($ExcelPath)
    $excelWsh = $excelWb.Sheets(&quot;PivotData&quot;)
    $pivot = $excelWsh.PivotTables(1)
    $pivot.RowAxisLayout(1)   # Tabular layout
    $pivot.EnableFieldList = $false
    $excelObj.Visible = $false

    # Freeze panes at B3 in PivotData Worksheet
    [void]$excelObj.Cells.Item(3,2).Select()
    $excelObj.ActiveWindow.FreezePanes = $True

    # Save and close
    $excelObj.ActiveWorkbook.SaveAs($ExcelPath, 51)   # xlsx
    $excelObj.Workbooks.Close()
    $excelObj.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelObj) | Out-Null

}

write-output &quot;Finished exporting data to $ExcelPath&quot;

# --------------------------------------------------------------------------

huangapple
  • 本文由 发表于 2023年2月24日 07:57:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定