ADGraph.psm1
$script:ModuleRoot = $PSScriptRoot $script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\ADGraph.psd1").ModuleVersion # Detect whether at some level dotsourcing was enforced $script:doDotSource = Get-PSFConfigValue -FullName ADGraph.Import.DoDotSource -Fallback $false if ($ADGraph_dotsourcemodule) { $script:doDotSource = $true } <# Note on Resolve-Path: All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator. This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS. Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist. This is important when testing for paths. #> # Detect whether at some level loading individual module files, rather than the compiled module was enforced $importIndividualFiles = Get-PSFConfigValue -FullName ADGraph.Import.IndividualFiles -Fallback $false if ($ADGraph_importIndividualFiles) { $importIndividualFiles = $true } if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true } if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true } function Import-ModuleFile { <# .SYNOPSIS Loads files into the module on module import. .DESCRIPTION This helper function is used during module initialization. It should always be dotsourced itself, in order to proper function. This provides a central location to react to files being imported, if later desired .PARAMETER Path The path to the file to load .EXAMPLE PS C:\> . Import-ModuleFile -File $function.FullName Imports the file stored in $function according to import policy #> [CmdletBinding()] Param ( [string] $Path ) $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath if ($doDotSource) { . $resolvedPath } else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) } } #region Load individual files if ($importIndividualFiles) { # Execute Preimport actions foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) { . Import-ModuleFile -Path $path } # Import all internal functions foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Import all public functions foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore)) { . Import-ModuleFile -Path $function.FullName } # Execute Postimport actions foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) { . Import-ModuleFile -Path $path } # End it here, do not load compiled code below return } #endregion Load individual files #region Load compiled code <# This file loads the strings documents from the respective language folders. This allows localizing messages and errors. Load psd1 language files for each language you wish to support. Partial translations are acceptable - when missing a current language message, it will fallback to English or another available language. #> Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'ADGraph' -Language 'en-US' Import-PSFLocalizedString -Path "$($script:ModuleRoot)\de-de\*.psd1" -Module 'ADGraph' -Language 'de-DE' class ADGraphCircleException:System.Exception { <# .SYNOPSIS Simple Class for Circle Exceptions #> [object[]]$ErrorEdges [object[]]$ExistingEdges ADGraphCircleException():base() { $this::new("Zirkelbezug") } ADGraphCircleException([string]$mesage):base($mesage) { $this.ErrorEdges = @() $this.ExistingEdges = @() } AddErrorEdge($newEdge) { $this.ErrorEdges += $newEdge $newEdge.attributes.color = "red" $newEdge.attributes.penwidth = "4" } AddExistingEdges($newEdges) { $this.ExistingEdges += $newEdges } } # class definition created by ConvertTo-ClassDefinition at 09/02/2021 12:07:02 for object type PSCustomObject class ADGraphEdge { <# .SYNOPSIS Simple Class for GraphViz Edges #> # properties [String]$From [String]$To [System.Collections.Hashtable]$Attributes [System.Object]$ToObject [System.Object]$FromObject [String[]]$SpecialMarkers # constructors ADGraphEdge () { } ADGraphEdge ([PSCustomObject]$InputObject) { $this.From = $InputObject.from $this.To = $InputObject.to $this.Attributes = $InputObject.attributes $this.ToObject = $InputObject.toObject $this.FromObject = $InputObject.fromObject $this.SpecialMarkers=@() } [String]GetAttrString() { return "$($this.From)>>$($this.To)($($this.SpecialMarkers -join "|"))" } } Class ADGraphNode { <# .SYNOPSIS Simple Class for GraphViz Nodes #> [string]$name [hashtable]$attributes [System.Object]$ADBaseObject [string]$nodeType [String[]]$SpecialMarkers ADGraphNode ([string]$DistinguishedName, [System.Object]$baseObj) { $this.name = $DistinguishedName $this.ADBaseObject = $baseObj $this.attributes = @{ } $label = ($DistinguishedName -replace '^CN=(.*?),OU.*$', '$1') $this.SpecialMarkers += "ObjectClass=$($baseObj.ObjectClass)" $this.attributes.label = $label } [String]GetAttrString() { return "$($this.name)($($this.SpecialMarkers -join "|"))" } } function Add-ADGraphEdge { <# .SYNOPSIS Helper function which determines all Edges (aka relations) of a given DistinguishedName. .DESCRIPTION Helper function which determines all Edges (aka relations) of a given DistinguishedName. It uses recursive calling patterns. .PARAMETER StartObjectDN The DistinguishedName of the object which should be inspected. .PARAMETER RecursionLevel FailSafe for detection of circle relationships. .PARAMETER linkAttribute Should be members/memberOf be followed? .EXAMPLE Add-ADGraphEdge -startObjectDN "CN=joe,OU=Users,DC=mydomain,DC=com" Queries all relationships of the given user. .NOTES General notes #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] param ( [Parameter(Mandatory=$true)] $StartObjectDN, $RecursionLevel = 0, [ValidateSet("memberOf", "members")] $LinkAttribute = "memberOf" ) Write-PSFMessage -String 'Add-ADGraphEdge.Start' -StringValues ($RecursionLevel), $StartObjectDN, $LinkAttribute if ($RecursionLevel -gt 20) { throw [ADGraphCircleException ]::new("Zirkelbezug, Level $RecursionLevel erreicht") } $newEdges = @() $startObject = $allExistingGroupsAndUsersHash[$StartObjectDN] Write-PSFMessage -Level Debug -String 'Add-ADGraphEdge.startObject' -StringValues $startObject try { $linkDNlist = $startObject | Select-Object -ExpandProperty $LinkAttribute -ErrorAction Stop } catch { Write-PSFMessage "Could not find attribute $LinkAttribute" } foreach ($linkDN in $linkDNlist) { $memberObject = $allExistingGroupsAndUsersHash[$linkDN] $attributes = @{ } # if (($startObject.ObjectClass -ne "user") -and ($memberObject.Epoche -ne $startObject.Epoche)) { # Write-PSFMessage -Level Debug -String 'Add-ADGraphEdge.differentTimeline' -StringValues $StartObjectDN, $linkDN # $attributes.add("color", "red") # } if ($LinkAttribute -eq "memberOf") { # MemberOf Beziehung von Links nach Rechts $currentEdge = [ADGraphEdge]::new([PSCustomObject]@{ from = $StartObjectDN to = $linkDN attributes = $attributes fromObject = $startObject toObject = $memberObject } ) $newEdges += $currentEdge } else { # Members Beziehung von Rechts nach Links $currentEdge = [ADGraphEdge]::new([PSCustomObject]@{ from = $linkDN to = $StartObjectDN attributes = $attributes fromObject = $memberObject toObject = $startObject } ) $newEdges += $currentEdge } try { $newEdges += Add-ADGraphEdge -startObjectDN $linkDN -recursionLevel ($RecursionLevel + 1) -linkAttribute $LinkAttribute } catch [ADGraphCircleException] { $circleError = $PSItem.Exception if ($RecursionLevel -gt 0) { $circleError.AddErrorEdge($currentEdge) $circleError.AddExistingEdges($newEdges) throw $circleError } else { $newEdges += $circleError.ExistingEdges return $newEdges } } } $newEdges } function Export-ADGraphExcelFile { <# .SYNOPSIS Short description .DESCRIPTION Long description .PARAMETER Graph A pregenerated graph .PARAMETER Path Parameter description .EXAMPLE An example .NOTES General notes #> param ( [parameter(Mandatory = $true, ValueFromPipeline = $true)] $Graph, [parameter(Mandatory = $true, ValueFromPipeline = $false)] $Path ) process { Write-PSFMessage "Erstelle $Path Objekten" $Graph |Set-Clipboard try { $excelContent=@() $pattern = 'CN=([^,]*).*>"CN=([^,]*)' $results = $Graph | Select-String $pattern -AllMatches foreach ($match in $results.Matches) { $member = $match.Groups[1] $memberOf = $match.Groups[2] $excelContent+=[PSCustomObject]@{ member = $member memberOf = $memberOf } } } catch { Write-PSFMessage "Error while extracting Excel-Data" } $excelContent | Export-XLSX $Path -WorksheetName "Hierarchy $((Get-Date).toString('yyyy-MM-dd HH-mm'))" -AutoFit -Table # # Zuordnung aller Node-Objekte zu den Edges # $nodeHashTable = @{ } # foreach ($node in $nodeObjects) { # $nodeHashTable.add($node.name, $node) # } # foreach ($edge in $edgeObjects) { # add-member -InputObject $edge -membertype noteproperty -name fromNode -value $nodeHashTable[$edge.from] -Force # add-member -InputObject $edge -membertype noteproperty -name toNode -value $nodeHashTable[$edge.to] -Force # } # # Es werden nur Objekte als Delegation (daher im AD) angelegt, welche mit einem 't' beginnen # $newAdNodes = $nodeObjects | where-object { $_.attributes.label -imatch '^t' } # Remove-Item $Path # $xlsItems = @() # foreach ($entry in $newAdNodes) { # $xlsItems += [PSCustomObject]@{ # Name = $entry.attributes.label # Beschreibung = $entry.ADBaseObject.Description # Insel = (Get-ADGraphInselFromDN -dn $entry.name) # } # } # $xlsItems | Export-XLSX $Path -WorksheetName "Delegationen" -AutoFit -Table # # Alle Verknüpfungen werden als Delegations-Hierarchie gespeichert # $xlsItems = @() # foreach ($entry in $edgeObjects) { # $xlsItems += [PSCustomObject]@{ # Insel = (Get-ADGraphInselFromDN -dn $entry.from) # Delegation = ($entry.fromNode.attributes.label) # memberOf = ($entry.toNode.attributes.label) # } # } # $xlsItems | Export-XLSX $Path -WorksheetName "Delegations-Hierarchie" -AutoFit -Table } } function Format-ADADGraphNodeObject { <# .SYNOPSIS Performs formatting templates on Edges and Nodes .DESCRIPTION Performs formatting templates on Edges and Nodes .PARAMETER Node The ADGraphNode Object to be formatted .PARAMETER Edge The ADGraphEdge Object to be formatted .EXAMPLE Format-ADADGraphNodeObject $node Formats the $node Object .NOTES General notes #> param ( [ADGraphNode]$Node, [ADGraphEdge]$Edge ) Write-PSFMessage "Formatting $attrString" if ($Node) { $attrString = $node.GetAttrString() if ($attrString -match 'ObjectClass=user') { $node.attributes.Add("shape", "record") $node.nodeType = "User" $node.attributes.label = "$($node.attributes.label)|$($node.ADBaseObject.DisplayName)" } if ($attrString -match '((CN=R-)|(CN=ROL-)).*group') { $node.attributes.shape = "cds" } if ($attrString -match '((CN=ROL)|(CN=DEL))-T[012].*group') { $node.attributes.color = "red" $node.attributes.penwidth = "4" } if ($attrString -match 'arrayIndex=0') { $node.attributes.fillcolor = "cyan" $node.attributes.style = "filled" } if ($attrString -match 'arrayIndex=1') { $node.attributes.fillcolor = "yellow" $node.attributes.style = "filled" } if ($attrString -match 'arrayIndex=2') { $node.attributes.fillcolor = "green" $node.attributes.style = "filled" } } if ($Edge) { $attrString = $Edge.GetAttrString() # if ($attrString -match 'ObjectClass=user') { # $node.attributes.Add("shape", "record") # $label = "$($node.attributes.label)|$($node.baseObj.DisplayName)" # $node.nodeType = "User" # $node.attributes.label = "$($node.attributes.label)|$($node.ADBaseObject.DisplayName)" # } if ($attrString -match '((CN=((ROL)|(DEL))-T[012]).*>>(CN=[DR]-))|((CN=[DR]-).*>>(CN=((ROL)|(DEL))-T[012]))') { # Different time epoches $Edge.attributes.color = "red" } # if ($attrString -match '((CN=ROL)|(CN=DEL))-T[012].*group') { # $node.attributes.color = "red" # $node.attributes.penwidth="4" # } } } function Get-ADGraphCache { <# .SYNOPSIS Queries information from the Active Directory and caches them. .DESCRIPTION Queries information from the Active Directory and caches them. This includes all users and groups of the named domain. .PARAMETER Domain The Domain which should be queried. This is used to connect to the server. .PARAMETER ReturnType Should the array of all users and groups be returned or the Indexed HashTable? .EXAMPLE Get-ADGraphCache -Domain "myDomain" -ReturnType HashTable Queries all Users/Groups as a HashTable .NOTES General notes #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')] param ( [Parameter(Mandatory = $true)] [string[]]$Domain, [ValidateSet("Array", "HashTable")] [Parameter(Mandatory = $true)] $ReturnType ) if (!$global:ADGraphCacheTable) { $global:ADGraphCacheTable = @{} } $domainKey = $Domain -join ";" Write-PSFMessage "Query AD-Cache-Data, domainKey=$domainKey and ReturnType=$ReturnType" if ($global:ADGraphCacheTable.Contains($domainKey)) { Write-PSFMessage "Information cached" $cacheData = $global:ADGraphCacheTable[$domainKey] } else { Write-PSFMessage "Initial query" $allExistingGroupsAndUsers = @() foreach ($targetDomain in $Domain) { $allExistingGroupsAndUsers += Get-ADUser -filter { ( (ObjectClass -eq "user") -and (objectCategory -eq "Person")) } -properties CanonicalName, SamAccountName, Displayname, Description, memberOf, ObjectClass -server $targetDomain $allExistingGroupsAndUsers += Get-ADGroup -filter { (ObjectClass -eq "group") } -properties CanonicalName, SamAccountName, Displayname, Description, memberOf, members, ObjectClass -server $targetDomain } # Save all groups/users in one HashTable $allExistingGroupsAndUsersHash = @{ } $allExistingGroupsAndUsers | ForEach-Object { $allExistingGroupsAndUsersHash.Add($_.DistinguishedName, $_) } $cacheData = @{ "Array" = $allExistingGroupsAndUsers "HashTable" = $allExistingGroupsAndUsersHash } # $cacheData.add("Array",$allExistingGroupsAndUsers ) # $cacheData.add("HashTable",$allExistingGroupsAndUsersHash) $global:ADGraphCacheTable[$domainKey] = $cacheData } $cacheData[$ReturnType] } function Get-ADGraphElapsedTime { <# .SYNOPSIS Time Measurement helper for developing. DEPRECATED. .DESCRIPTION Queries information from the Active Directory and caches them. .PARAMETER Message The Message which should be logged .EXAMPLE Get-ADGraphElapsedTime -Message "Query AD" Logs "Query AD" with a timestamp .NOTES General notes #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')] param ( $Message ) if ($false) { if (-not ($global:stopwatch)) { Write-PSFMessage -Level Host -Message "Starte Stoppuhr" $global:stopwatch = [system.diagnostics.stopwatch]::startNew() } Write-PSFMessage -Level Host -Message "[$($global:stopwatch.Elapsed.TotalSeconds)] $Message" } } function Get-ADGraphNodeObject { <# .SYNOPSIS Determines the unique ADGraphNode objects from given ADGraphEdges. .DESCRIPTION Determines the unique ADGraphNode objects from given ADGraphEdges. .PARAMETER StartObjectDN The DistinguishedName of the starting point .PARAMETER Edges Array of all Edges .EXAMPLE An example .NOTES General notes #> param ( [string]$StartObjectDN, [ADGraphEdge[]]$Edges ) Write-PSFMessage "Ermittele Nodes von startObjectDN=$StartObjectDN und edges=$($Edges.count)" $nodeDNs = @() $nodeObjects = @() $nodeDNs += ($Edges | Select-Object -ExpandProperty from) $nodeDNs += ($Edges | Select-Object -ExpandProperty to) $nodeDNs = $nodeDNs | Select-Object -Unique foreach ($DistinguishedName in $nodeDNs) { $currentNodeObject = $allExistingGroupsAndUsersHash[$DistinguishedName] # Aktuelle Node als Objekt initiieren, Formatierung passiert im Constructor $node = [ADGraphNode]::new($DistinguishedName, $currentNodeObject) $nodeObjects += $node # Das Start-Objekt erhält eine getrennte Formatierung if ($currentNodeObject.DistinguishedName -eq $StartObjectDN) { $node.attributes.fillcolor = "cyan" $node.attributes.style = "filled" } } # Falls keine Beziehungen vorhanden sind, wäre die Liste der Nodes leer. Hier wird ein Startobjekt angelegt. if ($nodeObjects.count -eq 0) { $nodeObjects += [ADGraphNode]::new($StartObjectDN, $allExistingGroupsAndUsersHash[$StartObjectDN] ) } $nodeObjects } Function Get-ADGraphSaveAsFileName { <# .SYNOPSIS Asks the user for a SaveAs Filename. .DESCRIPTION Asks the user for a SaveAs Filename. .PARAMETER InitialDirectory In which directory should the dialog be started? .PARAMETER Filter File filter, example: "Excel Files (*.xlsx)| *.*" .EXAMPLE An example .NOTES General notes #> param( [Parameter(Mandatory=$true)] $InitialDirectory, $Filter="Excel Files (*.xlsx)|*.*" ) [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null $OpenFileDialog = New-Object System.Windows.Forms.SaveFileDialog $OpenFileDialog.initialDirectory = $InitialDirectory $OpenFileDialog.filter = $Filter $OpenFileDialog.ShowDialog() | Out-Null $OpenFileDialog.filename } function New-ADGraphGroupGraph { <# .SYNOPSIS Creates a GraphViz dot graph. .DESCRIPTION Creates a GraphViz dot graph. .PARAMETER StartObjectDN The DistinguishedName of the object which should be inspected. .PARAMETER LinkAttribute Should be members/memberOf be followed? .PARAMETER RemoveUsers Should User objects be removed from the graph? .EXAMPLE New-ADGraphGroupGraph -LinkAttribute @("memberOf", "members") -StartObjectDN "CN=joe,OU=Users,DC=mydomain,DC=com" Gets a grpah from Joe .NOTES General notes #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')] param ( [Parameter(Mandatory)] [String[]]$StartObjectDN, [Parameter(Mandatory = $false)] [ValidateSet("memberOf", "members")] [String[]]$LinkAttribute = "memberOf", [switch]$RemoveUsers ) Write-PSFMessage "Erstelle neuen Graphen, Start-Objekte: $($StartObjectDN -join ';'), LinkAttribute $($LinkAttribute -join ';'), RemoveUsers=$RemoveUsers" # Zählen, wie viele Start-Objekte verwendet werden sollen $measurement = $startObjectDN | Measure-Object if ($measurement.Count -eq 2) { Write-PSFMessage "Vergleich von zwei Objekten" } $compareMode = ($measurement.Count -eq 2) # Verknüpfungen ermitteln und als GraphViz Edges hinterlegen $edgeObjectArrays = 1..($measurement.Count) $arrayIndex = 0 $allEdgeObjects = @() foreach ($startObject in $startObjectDN) { Write-PSFMessage "Suche Edges für $startObject" $edgeObjects = @() foreach ($linkAttr in $LinkAttribute) { try { $edgeObjects += Add-ADGraphEdge -startObjectDN $startObject -linkAttribute $linkAttr } catch [ADGraphCircleException] { $circleError = $PSItem.Exception $edgeObjects += $circleError.ExistingEdges Write-Error "Fehler, Zirkelbezug!" } } if ($RemoveUsers) { $edgeObjects = $edgeObjects | Where-Object { $_.from -notmatch 'OU=Users' } } $edgeObjectArrays[$arrayIndex] = $edgeObjects $allEdgeObjects += $edgeObjects Write-PSFMessage "edgeObjects.count=$($edgeObjects.count), arrayIndex=$arrayIndex" $arrayIndex += 1 } Write-PSFMessage "edgeObjectArrays.count=$($edgeObjectArrays.count) Array mit Edges erstellt" $nodeObjectArrays = 1..($measurement.Count) $allNodeObjects = @() $arrayIndex = 0 foreach ($startObject in $startObjectDN) { $nodeObjects = Get-ADGraphNodeObject -edges $edgeObjectArrays[$arrayIndex] -startObjectDN $startObject if ($compareMode) { foreach ($node in $nodeObjects) { $node.SpecialMarkers += "arrayIndex=$arrayIndex" } } $allNodeObjects += $nodeObjects $nodeObjectArrays[$arrayIndex] = $nodeObjects $arrayIndex += 1 } Write-PSFMessage "$($nodeObjectArrays.count) Array mit Nodes erstellt" if ($compareMode) { # foreach ($node in $nodeObjectArrays[0]) { # $node.attributes.fillcolor = "cyan" # $node.attributes.style = "filled" # } foreach ($node in $nodeObjectArrays[1]) { if ($nodeObjectArrays[0] | Where-Object { $_.name -eq $node.name }) { $node.SpecialMarkers += "arrayIndex=2" } # if ($nodeObjectArrays[0] | Where-Object { $_.name -eq $node.name }) { $color = "green" }else { $color = "yellow" } # $node.attributes.fillcolor = $color # $node.attributes.style = "filled" } } Write-PSFMessage "Starting Formatting" foreach ($array in $nodeObjectArrays) { $array | ForEach-Object { Format-ADADGraphNodeObject -Node $_ } } foreach ($array in $edgeObjectArrays) { $array | ForEach-Object { Format-ADADGraphNodeObject -Edge $_ } } Invoke-PSFProtectedCommand -ActionString 'New-ADGraphGroupGraph.CreateGraph' -ActionStringValues $measurement.Count, $allEdgeObjects.count -ScriptBlock { $myGraph = (graph -Debug:$false g -Attributes @{overlap = "false"; rankdir = "LR"; charset = "utf-8" } { "/* StartObjectDN=$($StartObjectDN -join ";") */" foreach ($array in $edgeObjectArrays) { $array | ForEach-Object { edge $_.from -to $_.to -Attributes $_.attributes } } foreach ($array in $nodeObjectArrays) { $array | ForEach-Object { node $_.name -Attributes $_.attributes } } # $edgeObjectsFirst | ForEach-Object { edge $_.from -to $_.to -Attributes $_.attributes } # $nodeObjectsFirst | ForEach-Object { node $_.name -Attributes $_.attributes } # $edgeObjectsSecond | ForEach-Object { edge $_.from -to $_.to -Attributes $_.attributes } # $nodeObjectsSecond | ForEach-Object { node $_.name -Attributes $_.attributes } } ) $myGraph | select-object -Unique } -PSCmdlet $PSCmdlet -EnableException $true } Import-Module PSGraph Import-Module PSFramework function New-ADGraph { <# .SYNOPSIS Creates a new GraphViz graph for an AD object. .DESCRIPTION Creates a new GraphViz graph for an AD object. .PARAMETER Domain Which domain should be inspected? Used as a connection server. .PARAMETER DistinguishedName The DN of the user or group which should be used as a starting point .PARAMETER MemberOf Should the memberOf attribute be considered? .PARAMETER Members Should the members attribute be considered? .PARAMETER Users Should user objects be included into the graph= .PARAMETER ReturnType Specifies the return type. .PARAMETER Path Optional parameter: In which output path should the generated PDF Files be saved? Defaults to the users TEMP directory .PARAMETER ShowPDF Optional Parameter: If a PDF file is created, should it be directly opened? .EXAMPLE $graph = Get-ADUser -Identity "jane"| New-ADGraph -Domain "myDomain" -ReturnType "SingleGraph" Greates a graph for the user Jane .NOTES General notes #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] param ( [Parameter(Mandatory = $true)] [string[]]$Domain, [Alias('DN')] [parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [string[]]$DistinguishedName, [bool]$MemberOf = $true, [bool]$Members = $true, [bool]$Users = $true, [ValidateSet("SingleGraph", "GraphArray", "SinglePDF", "MultiPDF", "ExcelFile")] $ReturnType = "SinglePDF", [string]$Path = $env:TEMP, [bool]$ShowPDF = $true ) begin { Write-PSFMessage "Begin" Write-PSFMessage "Begin Domain=$Domain" Write-PSFMessage "Begin DistinguishedName=$DistinguishedName" $graphOptions = @{ StartObjectDN = @() RemoveUsers = ($Users -eq $false) linkAttribute = @() } $allExistingGroupsAndUsersHash = Get-ADGraphCache -Domain $Domain -ReturnType HashTable $startObjects = @() } process { if ($Verbose) { $VerbosePreference = "Continue" } Write-PSFMessage "PROCESS: DistinguishedName=$DistinguishedName" # $graphOptions.StartObjectDN+=$DistinguishedName $startObjects += ($DistinguishedName | foreach-object { $allExistingGroupsAndUsersHash[$_] }) } end { Write-PSFMessage "End Domain=$Domain" Write-PSFMessage "Create $ReturnType for $DistinguishedName" # Write-PSFMessage "graphOptions=$($graphOptions|ConvertTo-Json)" Write-PSFMessage "startObjects=$startObjects" # In which directions should be searched for relationship? if ($Members) { $graphOptions.linkAttribute += "members" } if ($MemberOf) { $graphOptions.linkAttribute += "memberOf" } # Create the graph switch ($ReturnType) { "SingleGraph" { $graphOptions.StartObjectDN = ($startObjects | Select-Object -ExpandProperty DistinguishedName) Write-PSFMessage "graphOptions=$($graphOptions|ConvertTo-Json)" $myGraph = New-ADGraphGroupGraph @graphOptions return $myGraph | Out-String } "GraphArray" { $graphArray = @() foreach ($startObjectDN in ($startObjects | Select-Object -ExpandProperty DistinguishedName) ) { $graphOptions.StartObjectDN = $startObjectDN Write-PSFMessage "graphOptions=$($graphOptions|ConvertTo-Json)" $graphArray += ((New-ADGraphGroupGraph @graphOptions) | Out-String) } return $graphArray } "SinglePDF" { $graphOptions.StartObjectDN = ($startObjects | Select-Object -ExpandProperty DistinguishedName) Write-PSFMessage "graphOptions=$($graphOptions|ConvertTo-Json)" $myGraph = New-ADGraphGroupGraph @graphOptions $DistinguishedNameFileNamePart = ($graphOptions.StartObjectDN -replace 'CN=([^,]*),.*?,DC=', '$1-' -replace ',DC=', '.') -join "_" # $fileName = "$Path\$($graphOptions.StartObjectDN).pdf" -replace 'CN=([^,]*),.*?,DC=', '$1-' -replace ',DC=', '.' $fileName = "$Path\$DistinguishedNameFileNamePart.pdf" Write-PSFMessage "SinglePDF, $fileName" $myGraph | Export-PSGraph -ShowGraph:$ShowPDF -OutputFormat pdf -DestinationPath $fileName -Debug:$false return $fileName } "MultiPDF" { $fileNameArray = @() foreach ($startObjectDN in ($startObjects | Select-Object -ExpandProperty DistinguishedName) ) { $graphOptions.StartObjectDN = $startObjectDN Write-PSFMessage "graphOptions=$($graphOptions|ConvertTo-Json)" $myGraph = New-ADGraphGroupGraph @graphOptions $fileName = "$Path\$startObjectDN.pdf" -replace 'CN=([^,]*),.*?,DC=', '$1-' -replace ',DC=', '.' $myGraph | Export-PSGraph -ShowGraph:$ShowPDF -OutputFormat pdf -DestinationPath $fileName -Debug:$false $fileNameArray+=$fileName } return $fileNameArray } "ExcelFile" { $graphOptions.StartObjectDN = ($startObjects | Select-Object -ExpandProperty DistinguishedName) Write-PSFMessage "graphOptions=$($graphOptions|ConvertTo-Json)" $myGraph = New-ADGraphGroupGraph @graphOptions $fileName = "$Path\$($graphOptions.StartObjectDN).xlsx" -replace 'CN=([^,]*),.*?,DC=', '$1-' -replace ',DC=', '.' $myGraph | Out-String | Export-ADGraphExcelFile -Path $fileName return $fileName } Default {} } } # if ($fileName) { # New-ADGraphExcelFile @graphOptions -Path $fileName # } } function Start-ADGraph { <# .SYNOPSIS Starts a simple GUI for creating ADGraphs. .DESCRIPTION Starts a simple GUI for creating ADGraphs. .PARAMETER Verbose If set to $true VerbosePreference is set to "Continue" .EXAMPLE Start-ADGraph Starts the GUI. .NOTES General notes #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] param ( [switch]$Verbose ) if ($Verbose) { $VerbosePreference = "Continue" } # Which domain should be focused? $allDomains = (get-adforest).domains # Loop infinitely, script can be closed by clicking cancel on any dialog while ($true) { $chosenDomain = $allDomains | Out-GridView -Title (Get-PSFLocalizedString -Module "ADGraph" -Name "Start-ADGraph.ChooseDomain") -outputmode single if ($null -eq $chosenDomain) { Write-PSFMessage -Level Host -String 'Start-ADGraph.NoInput' -StringValues "Domain" return } $allExistingGroupsAndUsers = Get-ADGraphCache -Domain $chosenDomain -ReturnType Array $possibleOptions = [ordered] @{ "Mode: Default" = (Get-PSFLocalizedString -Module 'ADGraph' -Name 'Start-ADGraph.OptionGrid.Mode-Default') "Mode: Compare 2 Objects" = (Get-PSFLocalizedString -Module 'ADGraph' -Name 'Start-ADGraph.OptionGrid.Mode-Compare-2-Objects') "Mode: Multi-Object>One PDF" = (Get-PSFLocalizedString -Module 'ADGraph' -Name 'Start-ADGraph.OptionGrid.Mode-Multi-Object-One-PDF') "Mode: Multi-Object>Multi-PDF" = (Get-PSFLocalizedString -Module 'ADGraph' -Name 'Start-ADGraph.OptionGrid.Mode-Multi-Object-Multi-PDF') "Mode: Create Test-XLSX" = (Get-PSFLocalizedString -Module 'ADGraph' -Name 'Start-ADGraph.OptionGrid.Mode-Create-Test-XLSX') "Option: Visualize MemberOf only" = (Get-PSFLocalizedString -Module 'ADGraph' -Name 'Start-ADGraph.OptionGrid.Option-Visualize-MemberOf-only') "Option: Visualize Members only" = (Get-PSFLocalizedString -Module 'ADGraph' -Name 'Start-ADGraph.OptionGrid.Option-Visualize-Members-only') "Option: No User" = (Get-PSFLocalizedString -Module 'ADGraph' -Name 'Start-ADGraph.OptionGrid.Option-No-User') } $options = $possibleOptions | Out-GridView -Title (Get-PSFLocalizedString -Module "ADGraph" -Name "Start-ADGraph.ChooseOptions") -OutputMode Multiple | Select-Object -ExpandProperty Name if ($null -eq $options) { Write-PSFMessage -Level Host -String 'Start-ADGraph.NoInput' -StringValues "Option" return } $newADGraphOptions = @{ Domain=$chosenDomain DistinguishedName = "" MemberOf=$true Members=$true Users = $true ReturnType = "SinglePDF" } # Hinterlegung, in welche Richtung Beziehungen nachverfolgt werden sollen if ($options.contains("Option: Visualize Members only" )) { $newADGraphOptions.MemberOf=$false } if ($options.contains("Option: Visualize MemberOf only" )) { $newADGraphOptions.Members=$false } if ($options.contains("Option: No User")) { $newADGraphOptions.Users = $false } if ($options.contains("Mode: Compare 2 Objects")) { # Vergleichs Verfahren, 2 Startobjekte $startObjectFirst = $allExistingGroupsAndUsers | Select-Object -Property DistinguishedName, DisplayName | Out-GridView -Title (Get-PSFLocalizedString -Module "ADGraph" -Name "Start-ADGraph.CompareFirstObject") -OutputMode Single $startObjectSecond = $allExistingGroupsAndUsers | Select-Object -Property DistinguishedName, DisplayName | Out-GridView -Title (Get-PSFLocalizedString -Module "ADGraph" -Name "Start-ADGraph.CompareSecondObject" ) -OutputMode Single if (($null -eq $startObjectFirst) -or ($null -eq $startObjectSecond)) { Write-PSFMessage -Level Host -String 'Start-ADGraph.NoInput' -StringValues "2 Objects" return } $newADGraphOptions.DistinguishedName = @($startObjectFirst.DistinguishedName, $startObjectSecond.DistinguishedName) $myGraph = New-ADGraph @newADGraphOptions # $fileName = "$($env:temp)\Compare-$($startObjectFirst.DistinguishedName)-with-$($startObjectSecond.DistinguishedName).pdf" -replace 'CN=([^,]*),.*?,DC=', '$1-' -replace ',DC=', '.' # $myGraph | Export-PSGraph -ShowGraph -OutputFormat pdf -DestinationPath $fileName -Debug:$false } elseif ($options.contains("Mode: Multi-Object>One PDF")) { $startObjects = $allExistingGroupsAndUsers | Select-Object -Property DistinguishedName, DisplayName | Out-GridView -Title (Get-PSFLocalizedString -Module "ADGraph" -Name "Start-ADGraph.CompareXobjects") -OutputMode Multiple | Select-Object -ExpandProperty DistinguishedName if (($null -eq $startObjects) ) { Write-PSFMessage -Level Host -String 'Start-ADGraph.NoInput' -StringValues "startObject" return } $newADGraphOptions.DistinguishedName = $startObjects $myGraph = New-ADGraph @newADGraphOptions # $fileName = "$($env:temp)\Visualize-$($startObjects.count)-objects.pdf" # $myGraph | Export-PSGraph -ShowGraph -OutputFormat pdf -DestinationPath $fileName -Debug:$false } elseif ($options.contains("Mode: Multi-Object>Multi-PDF")) { $newADGraphOptions.ReturnType = "MultiPDF" # Beliebig viele Startobjekte, das Ergebnis wird in eine PDF je Objekt gepackt $startObjectDNs = $allExistingGroupsAndUsers | Select-Object -Property DistinguishedName, DisplayName | Out-GridView -Title (Get-PSFLocalizedString -Module "ADGraph" -Name "Start-ADGraph.CompareXobjects") -OutputMode Multiple | Select-Object -ExpandProperty DistinguishedName if (($null -eq $startObjectDNs) ) { Write-PSFMessage -Level Host -String 'Start-ADGraph.NoInput' -StringValues "startObject" return } $newADGraphOptions.DistinguishedName = $startObjectDNs $myGraph = New-ADGraph @newADGraphOptions # foreach ($startObjectDN in $startObjects) { # $newADGraphOptions.DistinguishedName = $startObjectDN # $myGraph = New-ADGraph @newADGraphOptions # $fileName = "$($env:temp)\$($startObjectDN).pdf" -replace 'CN=([^,]*),.*?,DC=', '$1-' -replace ',DC=', '.' # $myGraph | Export-PSGraph -ShowGraph -OutputFormat pdf -DestinationPath $fileName -Debug:$false # } } elseif ($options.contains("Mode: Create Test-XLSX")) { $newADGraphOptions.ReturnType = "ExcelFile" $startObject = $allExistingGroupsAndUsers | Select-Object -Property DistinguishedName, DisplayName | Out-GridView -Title (Get-PSFLocalizedString -Module "ADGraph" -Name "Start-ADGraph.ChooseStartobject") -OutputMode Single if ($null -eq $startObject) { Write-PSFMessage -Level Host -String 'Start-ADGraph.NoInput' -StringValues "startObject" return } Write-PSFMessage "$($startObject|ConvertTo-Json)" $newADGraphOptions.DistinguishedName = $startObject.DistinguishedName $myGraph = New-ADGraph @newADGraphOptions } else { # Standard Verfahren, 1 Startobjekt $startObject = $allExistingGroupsAndUsers | Select-Object -Property DistinguishedName, DisplayName | Out-GridView -Title (Get-PSFLocalizedString -Module "ADGraph" -Name "Start-ADGraph.ChooseStartobject") -OutputMode Single if ($null -eq $startObject) { Write-PSFMessage -Level Host -String 'Start-ADGraph.NoInput' -StringValues "startObject" return } $newADGraphOptions.DistinguishedName = $startObject.DistinguishedName $myGraph = New-ADGraph @newADGraphOptions # $fileName = "$($env:temp)\$($startObject.DistinguishedName).pdf" -replace 'CN=([^,]*),.*?,DC=', '$1-' -replace ',DC=', '.' # $myGraph | Export-PSGraph -ShowGraph -OutputFormat pdf -DestinationPath $fileName -Debug:$false } Write-PSFMessage "myGraph=$myGraph" # if ($myGraph) {$myGraph|Set-Clipboard} } } <# This is an example configuration file By default, it is enough to have a single one of them, however if you have enough configuration settings to justify having multiple copies of it, feel totally free to split them into multiple files. #> <# # Example Configuration Set-PSFConfig -Module 'ADGraph' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'" #> Set-PSFConfig -Module 'ADGraph' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging." Set-PSFConfig -Module 'ADGraph' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments." <# Stored scriptblocks are available in [PsfValidateScript()] attributes. This makes it easier to centrally provide the same scriptblock multiple times, without having to maintain it in separate locations. It also prevents lengthy validation scriptblocks from making your parameter block hard to read. Set-PSFScriptblock -Name 'ADGraph.ScriptBlockName' -Scriptblock { } #> <# # Example: Register-PSFTeppScriptblock -Name "ADGraph.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #> <# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name ADGraph.alcohol #> New-PSFLicense -Product 'ADGraph' -Manufacturer 'b10057231' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-02-04") -Text @" Copyright (c) 2021 b10057231 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "@ #endregion Load compiled code |