Search is not available for this dataset
filename
stringlengths
5
114
module_name
stringlengths
8
67
content
stringlengths
0
282M
ADGrouper.psm1
ADGrouper-0.0.1
#Module vars $ModulePath = $PSScriptRoot #Get public and private function definition files. $Public = Get-ChildItem $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue $Private = Get-ChildItem $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue [string[]]$PrivateModules = Get-ChildItem $PSScriptRoot\Private -ErrorAction SilentlyContinue | Where-Object {$_.PSIsContainer} | Select -ExpandProperty FullName # Dot source the files Foreach($import in @($Public + $Private)) { Try { . $import.fullname } Catch { Write-Error "Failed to import function $($import.fullname): $_" } } # Load up dependency modules foreach($Module in $PrivateModules) { Try { Import-Module $Module -ErrorAction Stop } Catch { Write-Error "Failed to import module $Module`: $_" } } Export-ModuleMember -Function $Public.Basename
Invoke-ADGrouper.ps1
ADGrouper-0.0.1
Function Invoke-ADGrouper { <# .SYNOPSIS Adjust AD group membership based on yaml config files .DESCRIPTION Adjust AD group membership based on yaml config files YAML schema: 'Target Group': # Target security group we are populating Purge: # Whether to remove existing accounts in the groupthat aren't included in this definition. Defaults to false Recurse: # Whether to recurse membership when source is a group. Defaults to true Expand: # Whether to expand to individual accounts within the group, or use the group explicitly. Defaults to true Exclude: # Accounts to exclude from this group BadUser: # Exclude account BadGroup: # Exclude account with overriden Recurse - Recurse: False ExcludeQuery: # One or more LDAP queries whose resulting accounts are excluded from the target group - '(b=a)' Include: # Accounts to include in this group GoodGroup: # Include account with global settings GoodGroup2: # Include account with overriden Expand and Recurse - Expand: False - Recurse: False IncludeQuery: # One or more LDAP queries whose resulting accounts are included in the target group - '(a=b)' - '(c=d)' .FUNCTIONALITY Active Directory .PARAMETER InputObject Yaml dynamic group definition .PARAMETER Path Path to yaml containing dynamic group definition .EXAMPLE Invoke-ADGrouper $Yaml -Whatif # See what Invoke-ADGrouper would do with yaml, without doing it .Example Invoke-ADGrouper -Path \\Path\To\example.yaml -Confirm:$False -Force # Run example.yaml through Invoke-ADGrouper without confirmation .LINK Get-ADDynamicGroup .LINK Expand-ADDynamicGroup .LINK about_ADGrouper #> [cmdletbinding( DefaultParameterSetName = 'yaml', SupportsShouldProcess=$True, ConfirmImpact='High')] param( [parameter(ParameterSetName = 'yaml', ValueFromPipeline = $True)] [string]$InputObject, [parameter(ParameterSetName = 'file', ValueFromPipelineByPropertyName = $True)] [Alias('FullName')] [string[]]$Path, [switch]$Force ) begin { $RejectAll = $false $ConfirmAll = $false } process { $ToProcess = [System.Collections.ArrayList]@() if($PSCmdlet.ParameterSetName -eq 'file') { foreach($File in $Path) { $ToProcess.AddRange( @(Get-Content $File -Raw) ) } } else { [void]$ToProcess.Add($InputObject) } Write-Verbose ($ToProcess | Out-String) $ToExpand = $ToProcess | Get-ADDynamicGroup $ToChange = Expand-ADDynamicGroup -InputObject $ToExpand foreach($Change in $ToChange) { $Todo = "[{0}] [{1}] to/from [{2}]" -f $Change.Action, $Change.Account, $Change.Group if($PSCmdlet.ShouldProcess( "Group changed '$Todo'", "Group change '$Todo'?", "Changing group membership" )) { if($Force -or $PSCmdlet.ShouldContinue("Are you REALLY sure you want to change '$Todo'?", "Removing '$Todo'", [ref]$ConfirmAll, [ref]$RejectAll)) { switch ($Change.Action) { 'Add' { Add-ADGroupMember -Identity $Change.Group -Members $Change.Account } 'Remove' { Remove-ADGroupMember -Identity $Change.Group -Members $Change.Account } } } } } } }
Expand-ADDynamicGroup.ps1
ADGrouper-0.0.1
Function Expand-ADDynamicGroup { <# .SYNOPSIS Expand dynamic security group definition to describe actions to take .DESCRIPTION Expand dynamic security group definition to describe actions to take Takes the output of Get-ADDynamicGroup and expands this into an array of actions with the following properties: Group # The target group we will take this action on Account # The account we will act on for this target group Action # The action we will take on thie target group and account pair Type # If IncludeType parameter is specified, whether the account is a group or a user Definition # The raw input we parsed from Get-ADDynamicGroup .FUNCTIONALITY Active Directory .PARAMETER InputObject Dynamic group definition generated by Get-ADDynamicGroup .PARAMETER IncludeType If specified, parse the AD type for each AD account to be added or removed from the target group .EXAMPLE Get-ADDynamicGroup $Yaml | Expand-ADDynamicGroup .EXAMPLE Get-ADDynamicGroup $Yaml | Expand-ADDynamicGroup -IncludeType .LINK Get-ADDynamicGroup .LINK Invoke-ADGrouper .LINK about_ADGrouper #> [cmdletbinding()] param( [parameter(ValueFromPipeline= $True)] [PSTypeName('adgrouper.group')] [psobject[]]$InputObject, [switch]$IncludeType ) begin { function Get-Params { param($Target, $Account) $Props = Get-PropertyOrder $Account $ThisRecurse = if($Props -contains 'Recurse') {$Account.Recurse} else {$Target.Recurse} $ThisExpand = if($Props -contains 'Expand') {$Account.Expand} else {$Target.Expand} @{ Identity = $Account.Account Recurse = $ThisRecurse Expand = $ThisExpand } } } process { Write-Verbose "Expanding $($InputObject | Out-String)" foreach($Group in $InputObject) { $Excludes = New-Object System.Collections.ArrayList $Includes = New-Object System.Collections.ArrayList foreach($ADObject in @( $Group.Exclude | Where {$_.Account})) { $Type = $null $Type = Get-ADObjectClass -sAMAccountName $ADObject.Account if($Type) { $Params = Get-Params -Target $Group -Account $ADObject Write-Verbose "Expanding removal of $($ADObject.account) with type [$Type] and expand [$($Group.Expand)]" [void]$Excludes.AddRange( @(Expand-Account @Params -Type $Type ) ) } else { Write-Warning "No type found for $($ADObject.Account) exclude, skipping" } } foreach($ADObject in @( $Group.Include | Where {$_.Account})) { $Type = $null $Type = Get-ADObjectClass -sAMAccountName $ADObject.Account if($Type) { $Params = Get-Params -Target $Group -Account $ADObject Write-Verbose "Expanding inclusion of $($ADObject.account) with type [$Type], expand [$($Params.Expand)], recurse [$($Params.Recurse)]" [void]$Includes.AddRange( @(Expand-Account @Params -Type $Type) ) } else { Write-Warning "No type found for $($ADObject.Account) include, skipping" } } foreach($Query in @( $Group.IncludeQuery | Where {$_}) ) { $DiscoveredAccounts = $null [string[]]$DiscoveredAccounts = Get-ADSIObject -Query $Query | Select -ExpandProperty sAMAccountName | Where {$_} if($DiscoveredAccounts.count -gt 0) { Write-Verbose "Including $($DiscoveredAccounts.count) accounts from query [$Query]" [void]$Includes.AddRange( $DiscoveredAccounts ) } else { Write-Verbose "No accounts found for IncludeQuery [$Query]" } } foreach($Query in @( $Group.ExcludeQuery | Where {$_}) ) { $DiscoveredAccounts = $null [string[]]$DiscoveredAccounts = Get-ADSIObject -Query $Query | Select -ExpandProperty sAMAccountName | Where {$_} if($DiscoveredAccounts.count -gt 0) { Write-Verbose "Excluding $($DiscoveredAccounts.count) accounts from query [$Query]" [void]$Excludes.AddRange( $DiscoveredAccounts ) } else { Write-Verbose "No accounts found for ExcludeQuery [$Query]" } } $Excludes = $Excludes | Sort -Unique $Includes = $Includes | Where {$Excludes -notcontains $_} | Select -Unique $Existing = Expand-Account -Type Group -Identity $Group.TargetGroup -Expand $ToRemove = $Existing | Where {$Includes -notcontains $_} | Sort -Unique $ToAdd = $Includes | Where {$Existing -notcontains $_} | Sort -Unique if($Group.Purge -and $null -notlike $ToRemove) { foreach($Account in $ToRemove) { [pscustomobject]@{ PSTypeName = 'adgrouper.action' Group = $Group.TargetGroup Account = $Account Action = 'Remove' Type = Get-ADObjectClass -sAMAccountName $Account -IncludeType $IncludeType Definition = $Group } } } foreach($Account in $ToAdd) { [pscustomobject]@{ PSTypeName = 'adgrouper.action' Group = $Group.TargetGroup Account = $Account Action = 'Add' Type = Get-ADObjectClass -sAMAccountName $Account -IncludeType $IncludeType Definition = $Group } } } } }
Get-ADDynamicGroup.ps1
ADGrouper-0.0.1
Function Get-ADDynamicGroup { <# .SYNOPSIS Parse yaml describing dynamic security groups .DESCRIPTION Parse yaml describing dynamic security groups This parses the yaml without hitting Active Directory .FUNCTIONALITY Active Directory .PARAMETER InputObject Yaml dynamic group definition .PARAMETER Path Path to yaml containing dynamic group definition .EXAMPLE Get-ADDynamicGroup $Yaml .LINK https://github.com/RamblingCookieMonster/ADGrouper .LINK Expand-ADDynamicGroup .LINK Invoke-ADGrouper .LINK about_ADGrouper #> [cmdletbinding( DefaultParameterSetName = 'yaml' )] param( [parameter(ParameterSetName = 'yaml', ValueFromPipeline = $True)] [string]$InputObject, [parameter(ParameterSetName = 'file', ValueFromPipelineByPropertyName = $True)] [Alias('FullName')] [string[]]$Path ) begin { function Parse-Option { param($Target, $Name, $Type) $ThisItem = $Target.$Type.get_item($Name) $ThisRecurse = if($ThisItem -is [hashtable] -and $ThisItem.ContainsKey('Recurse')) {$ThisItem.Recurse} else {$Recurse} $ThisPurge = if($ThisItem -is [hashtable] -and $ThisItem.ContainsKey('Purge')) {$ThisItem.Purge} else {$Purge} $ThisExpand = if($ThisItem -is [hashtable] -and $ThisItem.ContainsKey('Expand')) {$ThisItem.Expand} else {$Expand} [pscustomobject]@{ Account = $Name Recurse = $ThisRecurse Purge = $ThisPurge Expand = $ThisExpand } } } process { $ToProcess = [System.Collections.ArrayList]@() if($PSCmdlet.ParameterSetName -eq 'file') { foreach($File in $Path) { $ToProcess.AddRange( @(Get-Content $File -Raw) ) } } else { [void]$ToProcess.Add($InputObject) } $ValuesForTrue = '1', 'True', 'Yes', $True foreach($Yaml in $ToProcess) { $Groups = ConvertFrom-Yaml -Yaml $Yaml foreach($GroupName in $Groups.keys) { $Group = $Groups[$GroupName] # Parse global options $Recurse = $False if($null -eq $Group.Recurse -or $ValuesForTrue -contains $Group.Recurse) { $Recurse = $True } $Expand = $False if($null -eq $Group.Expand -or $ValuesForTrue -contains $Group.Expand) { $Expand = $True } $Purge = $False if($ValuesForTrue -contains $Group.Purge) { $Purge = $True } $IncludeQuery = $null if($Group.IncludeQuery) { $IncludeQuery = $Group.IncludeQuery } $ExcludeQuery = $null if($Group.ExcludeQuery) { $ExcludeQuery = $Group.ExcludeQuery } [pscustomobject]@{ PSTypeName = 'adgrouper.group' TargetGroup = $GroupName Recurse = $Recurse Purge = $Purge Expand = $Expand IncludeQuery = $IncludeQuery Include = $Group.Include.keys | Foreach { Parse-Option -Target $Group -Name $_ -Type Include } Exclude = $Group.Exclude.keys | Foreach { Parse-Option -Target $Group -Name $_ -Type Exclude } ExcludeQuery = $ExcludeQuery } } } } }
Expand-Account.ps1
ADGrouper-0.0.1
function Expand-Account { [cmdletbinding()] param( $Identity, $Type, [switch]$Recurse, [switch]$Expand ) if($Type -eq 'Group' -and $Expand) { $params = @{ Identity = $Identity } if($Recurse) { $params.add('Recursive', $True) } (Get-ADGroupMember @params).samaccountname # TODO: Consider non-ActiveDirectory module implementation } else { $Identity } }
powershell-yaml.psm1
ADGrouper-0.0.1
# Copyright 2016 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # function Get-YamlDocuments { [CmdletBinding()] Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [string]$Yaml ) PROCESS { $stringReader = new-object System.IO.StringReader($Yaml) $yamlStream = New-Object "YamlDotNet.RepresentationModel.YamlStream" $yamlStream.Load([System.IO.TextReader] $stringReader) $stringReader.Close() return $yamlStream } } function Convert-ValueToProperType { [CmdletBinding()] Param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Object]$Value ) PROCESS { if (!($Value -is [string])) { return $Value } $types = @([int], [long], [double], [boolean], [datetime]) foreach($i in $types){ try { return $i::Parse($Value) } catch { continue } } return $Value } } function Convert-YamlMappingToHashtable { [CmdletBinding()] Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [YamlDotNet.RepresentationModel.YamlMappingNode]$Node ) PROCESS { $ret = @{} foreach($i in $Node.Children.Keys) { $ret[$i.Value] = Convert-YamlDocumentToPSObject $Node.Children[$i] } return $ret } } function Convert-YamlSequenceToArray { [CmdletBinding()] Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [YamlDotNet.RepresentationModel.YamlSequenceNode]$Node ) PROCESS { $ret = [System.Collections.Generic.List[object]](New-Object "System.Collections.Generic.List[object]") foreach($i in $Node.Children){ $ret.Add((Convert-YamlDocumentToPSObject $i)) } return $ret } } function Convert-YamlDocumentToPSObject { [CmdletBinding()] Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [System.Object]$Node ) PROCESS { switch($Node.GetType().FullName){ "YamlDotNet.RepresentationModel.YamlMappingNode"{ return Convert-YamlMappingToHashtable $Node } "YamlDotNet.RepresentationModel.YamlSequenceNode" { return Convert-YamlSequenceToArray $Node } "YamlDotNet.RepresentationModel.YamlScalarNode" { return (Convert-ValueToProperType $Node.Value) } } } } function Convert-HashtableToDictionary { Param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [hashtable]$Data ) foreach($i in $($data.Keys)) { $Data[$i] = Convert-PSObjectToGenericObject $Data[$i] } return $Data } function Convert-ListToGenericList { Param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [array]$Data ) for($i=0; $i -lt $Data.Count; $i++) { $Data[$i] = Convert-PSObjectToGenericObject $Data[$i] } return ,$Data } function Convert-PSCustomObjectToDictionary { Param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [PSCustomObject]$Data ) $ret = [System.Collections.Generic.Dictionary[string,object]](New-Object 'System.Collections.Generic.Dictionary[string,object]') foreach ($i in $Data.psobject.properties) { $ret[$i.Name] = Convert-PSObjectToGenericObject $i.Value } return $ret } function Convert-PSObjectToGenericObject { Param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Object]$Data ) # explicitly cast object to its type. Without this, it gets wrapped inside a powershell object # which causes YamlDotNet to fail $data = $data -as $data.GetType().FullName switch($data.GetType()) { ($_.FullName -eq "System.Management.Automation.PSCustomObject") { return Convert-PSCustomObjectToDictionary $data } default { if (([System.Collections.IDictionary].IsAssignableFrom($_))){ return Convert-HashtableToDictionary $data } elseif (([System.Collections.IList].IsAssignableFrom($_))) { return Convert-ListToGenericList $data } return $data } } } function ConvertFrom-Yaml { [CmdletBinding()] Param( [Parameter(Mandatory=$false, ValueFromPipeline=$true)] [string]$Yaml, [switch]$AllDocuments=$false ) PROCESS { if(!$Yaml){ return } $documents = Get-YamlDocuments -Yaml $Yaml if (!$documents.Count) { return } if($documents.Count -eq 1){ return Convert-YamlDocumentToPSObject $documents[0].RootNode } if(!$AllDocuments) { return Convert-YamlDocumentToPSObject $documents[0].RootNode } $ret = @() foreach($i in $documents) { $ret += Convert-YamlDocumentToPSObject $i.RootNode } return $ret } } function ConvertTo-Yaml { [CmdletBinding()] Param( [Parameter(Mandatory=$false,ValueFromPipeline=$true)] [System.Object]$Data, [Parameter(Mandatory=$false)] [string]$OutFile, [switch]$Force=$false ) BEGIN { $d = [System.Collections.Generic.List[object]](New-Object "System.Collections.Generic.List[object]") } PROCESS { if($data -ne $null) { $d.Add($data) } } END { if($d -eq $null -or $d.Count -eq 0){ return } if($d.Count -eq 1) { $d = $d[0] } $norm = Convert-PSObjectToGenericObject $d if($OutFile) { $parent = Split-Path $OutFile if(!(Test-Path $parent)) { Throw "Parent folder for specified path does not exist" } if((Test-Path $OutFile) -and !$Force){ Throw "Target file already exists. Use -Force to overwrite." } $wrt = New-Object "System.IO.StreamWriter" $OutFile } else { $wrt = New-Object "System.IO.StringWriter" } try { $serializer = New-Object "YamlDotNet.Serialization.Serializer" 0 $serializer.Serialize($wrt, $norm) } finally { $wrt.Close() } if($OutFile){ return }else { return $wrt.ToString() } } } Export-ModuleMember -Function * -Alias *
Load-Assemblies.ps1
ADGrouper-0.0.1
# Copyright 2016 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # $here = Split-Path -Parent $MyInvocation.MyCommand.Path function Initialize-Assemblies { $libDir = Join-Path $here "lib" $assemblies = @{ "portable" = Join-Path $libDir "net45\YamlDotNet.dll"; "released" = Join-Path $libDir "net35\YamlDotNet.dll"; } try { [YamlDotNet.Serialization.Serializer] | Out-Null } catch [System.Management.Automation.RuntimeException] { try { return [Microsoft.PowerShell.CoreCLR.AssemblyExtensions]::LoadFrom($assemblies["portable"]) } catch [System.Management.Automation.RuntimeException] { return [Reflection.Assembly]::LoadFrom($assemblies["released"]) } } } Initialize-Assemblies | Out-Null
Get-PropertyOrder.ps1
ADGrouper-0.0.1
#function to extract properties Function Get-PropertyOrder { <# .SYNOPSIS Gets property order for specified object .DESCRIPTION Gets property order for specified object .PARAMETER InputObject A single object to convert to an array of property value pairs. .PARAMETER Membertype Membertypes to include .PARAMETER ExcludeProperty Specific properties to exclude .FUNCTIONALITY PowerShell Language #> [cmdletbinding()] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromRemainingArguments=$false)] [PSObject]$InputObject, [validateset("AliasProperty", "CodeProperty", "Property", "NoteProperty", "ScriptProperty", "Properties", "PropertySet", "Method", "CodeMethod", "ScriptMethod", "Methods", "ParameterizedProperty", "MemberSet", "Event", "Dynamic", "All")] [string[]]$MemberType = @( "NoteProperty", "Property", "ScriptProperty" ), [string[]]$ExcludeProperty = $null ) begin { if($PSBoundParameters.ContainsKey('inputObject')) { $firstObject = $InputObject[0] } } process{ #we only care about one object... $firstObject = $InputObject } end{ #Get properties that meet specified parameters $firstObject.psobject.properties | Where-Object { $memberType -contains $_.memberType } | Select -ExpandProperty Name | Where-Object{ -not $excludeProperty -or $excludeProperty -notcontains $_ } } } #Get-PropertyOrder
ADGrouper.psd1
ADGrouper-0.0.1
# # Module manifest for module 'ADGrouper' # # Generated by: Warren Frame # # Generated on: 3/10/2017 # @{ # Script module or binary module file associated with this manifest. RootModule = 'ADGrouper.psm1' # Version number of this module. ModuleVersion = '0.0.1' # ID used to uniquely identify this module GUID = '89228f0f-a5a2-4188-af98-28588ff601b1' # Author of this module Author = 'Warren Frame' # Company or vendor of this module CompanyName = 'Unknown' # Copyright statement for this module Copyright = '(c) 2017 Warren Frame. All rights reserved.' # Description of the functionality provided by this module Description = 'PowerShell module to dynamically populate AD groups via yaml' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '3.0' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = 'ADGrouper.Format.ps1xml' # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module FunctionsToExport = '*' # Cmdlets to export from this module # CmdletsToExport = '*' # Variables to export from this module # VariablesToExport = '*' # Aliases to export from this module AliasesToExport = '*' # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @('ActiveDirectory', 'AD', 'Identity', 'Security', 'Group', 'SecurityGroup', 'Domain') # A URL to the license for this module. LicenseUri = 'https://github.com/RamblingCookieMonster/ADGrouper/blob/master/LICENSE' # A URL to the main website for this project. ProjectUri = 'https://github.com/RamblingCookieMonster/ADGrouper/' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module ReleaseNotes = 'WARNING: This is a pre-release. See ProjectUri for details' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
Get-ADObjectClass.ps1
ADGrouper-0.0.1
function Get-ADObjectClass { [cmdletbinding()] param( $sAMAccountName, $IncludeType = $True ) if($IncludeType) { $Type = ( Get-ADSIObject $sAMAccountName -Property objectClass ).objectClass if($Type.count -gt 0) { switch ($Type[-1]) { 'user' {'User'} 'group' {'Group'} Default { Write-Warning "sAMAccountName [$sAMAccountName] is an unsupported type, [$($Type -join ', ')]"} } } } }
powershell-yaml.psd1
ADGrouper-0.0.1
# Copyright 2016 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # Module manifest for module 'powershell-yaml' # # Generated by: Gabriel Adrian Samfira # # Generated on: 10/01/2016 # @{ # Script module or binary module file associated with this manifest. RootModule = 'powershell-yaml.psm1' # Version number of this module. ModuleVersion = '0.1' # ID used to uniquely identify this module GUID = '6a75a662-7f53-425a-9777-ee61284407da' # Author of this module Author = 'Gabriel Adrian Samfira','Alessandro Pilotti' # Company or vendor of this module CompanyName = 'Cloudbase Solutions SRL' # Copyright statement for this module Copyright = '(c) 2016 Cloudbase Solutions SRL. All rights reserved.' # Description of the functionality provided by this module Description = 'Powershell module for serializing and deserializing YAML' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '3.0' # Script files (.ps1) that are run in the caller's environment prior to importing this module. ScriptsToProcess = @("Load-Assemblies.ps1") # Functions to export from this module FunctionsToExport = "ConvertTo-Yaml","ConvertFrom-Yaml" }
Get-ADSIObject.ps1
ADGrouper-0.0.1
function Get-ADSIObject { <# .SYNOPSIS Get AD object (user, group, etc.) via ADSI. .DESCRIPTION Get AD object (user, group, etc.) via ADSI. Invoke a specify an LDAP Query, or search based on samaccountname and/or objectcategory .FUNCTIONALITY Active Directory .PARAMETER samAccountName Specific samaccountname to filter on .PARAMETER ObjectCategory Specific objectCategory to filter on .PARAMETER Query LDAP filter to invoke .PARAMETER Path LDAP Path. e.g. contoso.com, DomainController1 LDAP:// is prepended when omitted .PARAMETER Property Specific properties to query for .PARAMETER Limit If specified, limit results to this size .PARAMETER Credential Credential to use for query If specified, the Path parameter must be specified as well. .PARAMETER As SearchResult = results directly from DirectorySearcher DirectoryEntry = Invoke GetDirectoryEntry against each DirectorySearcher object returned PSObject (Default) = Create a PSObject with expected properties and types .EXAMPLE Get-ADSIObject jdoe # Find an AD object with the samaccountname jdoe .EXAMPLE Get-ADSIObject -Query "(&(objectCategory=Group)(samaccountname=domain admins))" # Find an AD object meeting the specified criteria .EXAMPLE Get-ADSIObject -Query "(objectCategory=Group)" -Path contoso.com # List all groups at the root of contoso.com .EXAMPLE Echo jdoe, cmonster | Get-ADSIObject -property mail -ObjectCategory User | Select -expandproperty mail # Find an AD object for a few users, extract the mail property only .EXAMPLE $DirectoryEntry = Get-ADSIObject TESTUSER -as DirectoryEntry $DirectoryEntry.put(‘Title’,’Test’) $DirectoryEntry.setinfo() #Get the AD object for TESTUSER in a usable form (DirectoryEntry), set the title attribute to Test, and make the change. .LINK https://gallery.technet.microsoft.com/scriptcenter/Get-ADSIObject-Portable-ae7f9184 #> [cmdletbinding(DefaultParameterSetName='SAM')] Param( [Parameter( Position=0, Mandatory = $true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='SAM')] [string[]]$samAccountName = "*", [Parameter( Position=1, ParameterSetName='SAM')] [string[]]$ObjectCategory = "*", [Parameter( ParameterSetName='Query', Mandatory = $true )] [string]$Query = $null, [string]$Path = $Null, [string[]]$Property = $Null, [int]$Limit, [System.Management.Automation.PSCredential]$Credential, [validateset("PSObject","DirectoryEntry","SearchResult")] [string]$As = "PSObject" ) Begin { #Define parameters for creating the object $Params = @{ TypeName = "System.DirectoryServices.DirectoryEntry" ErrorAction = "Stop" } #If we have an LDAP path, add it in. if($Path){ if($Path -notlike "^LDAP") { $Path = "LDAP://$Path" } $Params.ArgumentList = @($Path) #if we have a credential, add it in if($Credential) { $Params.ArgumentList += $Credential.UserName $Params.ArgumentList += $Credential.GetNetworkCredential().Password } } elseif($Credential) { Throw "Using the Credential parameter requires a valid Path parameter" } #Create the domain entry for search root Try { Write-Verbose "Bound parameters:`n$($PSBoundParameters | Format-List | Out-String )`nCreating DirectoryEntry with parameters:`n$($Params | Out-String)" $DomainEntry = New-Object @Params } Catch { Throw "Could not establish DirectoryEntry: $_" } $DomainName = $DomainEntry.name #Set up the searcher $Searcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher $Searcher.PageSize = 1000 $Searcher.SearchRoot = $DomainEntry if($Limit) { $Searcher.SizeLimit = $limit } if($Property) { foreach($Prop in $Property) { $Searcher.PropertiesToLoad.Add($Prop) | Out-Null } } #Define a function to get ADSI results from a specific query Function Get-ADSIResult { [cmdletbinding()] param( [string[]]$Property = $Null, [string]$Query, [string]$As, $Searcher ) #Invoke the query $Results = $null $Searcher.Filter = $Query $Results = $Searcher.FindAll() #If SearchResult, just spit out the results. if($As -eq "SearchResult") { $Results } #If DirectoryEntry, invoke GetDirectoryEntry elseif($As -eq "DirectoryEntry") { $Results | ForEach-Object { $_.GetDirectoryEntry() } } #Otherwise, get properties from the object else { $Results | ForEach-Object { #Get the keys. They aren't an array, so split them up, remove empty, and trim just in case I screwed something up... $object = $_ #cast to array of strings or else PS2 breaks when we select down the line [string[]]$properties = ($object.properties.PropertyNames) -split "`r|`n" | Where-Object { $_ } | ForEach-Object { $_.Trim() } #Filter properties if desired if($Property) { $properties = $properties | Where-Object {$Property -Contains $_} } #Build up an object to output. Loop through each property, extract from ResultPropertyValueCollection #Create the object, PS2 compatibility. can't just pipe to select, props need to exist $hash = @{} foreach($prop in $properties) { $hash.$prop = $null } $Temp = New-Object -TypeName PSObject -Property $hash | Select -Property $properties foreach($Prop in $properties) { Try { $Temp.$Prop = foreach($item in $object.properties.$prop) { $item } } Catch { Write-Warning "Could not get property '$Prop': $_" } } $Temp } } } } Process { #Set up the query as defined, or look for a samaccountname. Probably a cleaner way to do this... if($PsCmdlet.ParameterSetName -eq 'Query'){ Write-Verbose "Working on Query '$Query'" Get-ADSIResult -Searcher $Searcher -Property $Property -Query $Query -As $As } else { foreach($AccountName in $samAccountName) { #Build up the LDAP query... $QueryArray = @( "(samAccountName=$AccountName)" ) if($ObjectCategory) { [string]$TempString = ( $ObjectCategory | ForEach-Object {"(objectCategory=$_)"} ) -join "" $QueryArray += "(|$TempString)" } $Query = "(&$($QueryArray -join ''))" Write-Verbose "Working on built Query '$Query'" Get-ADSIResult -Searcher $Searcher -Property $Property -Query $Query -As $As } } } End { $Searcher = $null $DomainEntry = $null } }
example.tepp.ps1
ADLDSMF-1.0.0
<# # Example: Register-PSFTeppScriptblock -Name "ADLDSMF.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #>
Update-LdsConfiguration.ps1
ADLDSMF-1.0.0
function Update-LdsConfiguration { <# .SYNOPSIS Updates the reference to the currently "connected to" LDS instance. .DESCRIPTION Updates the reference to the currently "connected to" LDS instance. This is used by Get-LdsDomain, which is injected into the ADSec module to avoid issues with domain resolution. .PARAMETER LdsServer The server hosting the LDS instance. .PARAMETER LdsPartition The partition of the LDS instance. .EXAMPLE PS C:\> Update-LdsConfiguration -LdsServer lds1.contoso.com -LdsPartition 'DC=Fabrikam,DC=org' Registers lds1.contoso.com as the current server and 'DC=Fabrikam,DC=org' as the current partition. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $LdsServer, [Parameter(Mandatory = $true)] [string] $LdsPartition ) $script:_ldsServer = $LdsServer $script:_ldsPartition = $LdsPartition }
scriptblocks.ps1
ADLDSMF-1.0.0
<# 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 'ADLDSMF.ScriptBlockName' -Scriptblock { } #>
preimport.ps1
ADLDSMF-1.0.0
<# Add all things you want to run before importing the main function code. WARNING: ONLY provide paths to files! After building the module, this file will be completely ignored, adding anything but paths to files ... - Will not work after publishing - Could break the build process #> $moduleRoot = Split-Path (Split-Path $PSScriptRoot) # Load the strings used in messages "$moduleRoot\internal\scripts\strings.ps1"
Resolve-SchemaGuid.ps1
ADLDSMF-1.0.0
function Resolve-SchemaGuid { <# .SYNOPSIS Resolves the name of an attribute or objectclass to its GUID form. .DESCRIPTION Resolves the name of an attribute or objectclass to its GUID form. Used to enable user-friendly names in configuration. + Supports caching requests to optimize performance + Will return guids unmodified .PARAMETER Name The name or guid of the attribute or object class. Guids will be returned unverified. .PARAMETER Server The LDS Server to connect to. .PARAMETER Credential The credentials - if any - to use to the specified server. .PARAMETER Cache A hashtable used for caching requests. .EXAMPLE PS C:\> Resolve-SchemaGuid -Name contact -Server lds1.contoso.com -Cache $cache Returns the GUID form of the "contact" object class if present. #> [OutputType([string])] [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string] $Name, [Parameter(Mandatory = $true)] [string] $Server, [PSCredential] $Credential, [hashtable] $Cache = @{ } ) begin { $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential } process { if ($Name -as [Guid]) { return $Name } if ($Cache[$Name]) { return $Cache[$Name] } $rootDSE = [adsi]"LDAP://$Server/rootDSE" $targetObjectClassObj = Get-ADObject @ldsParam -SearchBase ($rootdse.schemaNamingContext.value) -LDAPFilter "CN=$Name" -Properties 'schemaIDGUID' if (-not $targetObjectClassObj) { throw "Unknown attribute or object class: $Name" } $bytes = [byte[]]$targetObjectClassObj.schemaIDGUID $guid = [guid]::new($bytes) $Cache[$Name] = "$guid" "$guid" } }
pester.ps1
ADLDSMF-1.0.0
param ( $TestGeneral = $true, $TestFunctions = $true, [ValidateSet('None', 'Normal', 'Detailed', 'Diagnostic')] [Alias('Show')] $Output = "None", $Include = "*", $Exclude = "" ) Write-PSFMessage -Level Important -Message "Starting Tests" Write-PSFMessage -Level Important -Message "Importing Module" $global:testroot = $PSScriptRoot $global:__pester_data = @{ } Remove-Module ADLDSMF -ErrorAction Ignore Import-Module "$PSScriptRoot\..\ADLDSMF.psd1" Import-Module "$PSScriptRoot\..\ADLDSMF.psm1" -Force # Need to import explicitly so we can use the configuration class Import-Module Pester Write-PSFMessage -Level Important -Message "Creating test result folder" $null = New-Item -Path "$PSScriptRoot\..\.." -Name TestResults -ItemType Directory -Force $totalFailed = 0 $totalRun = 0 $testresults = @() $config = [PesterConfiguration]::Default $config.TestResult.Enabled = $true #region Run General Tests if ($TestGeneral) { Write-PSFMessage -Level Important -Message "Modules imported, proceeding with general tests" foreach ($file in (Get-ChildItem "$PSScriptRoot\general" | Where-Object Name -like "*.Tests.ps1")) { if ($file.Name -notlike $Include) { continue } if ($file.Name -like $Exclude) { continue } Write-PSFMessage -Level Significant -Message " Executing <c='em'>$($file.Name)</c>" $config.TestResult.OutputPath = Join-Path "$PSScriptRoot\..\..\TestResults" "TEST-$($file.BaseName).xml" $config.Run.Path = $file.FullName $config.Run.PassThru = $true $config.Output.Verbosity = $Output $results = Invoke-Pester -Configuration $config foreach ($result in $results) { $totalRun += $result.TotalCount $totalFailed += $result.FailedCount $result.Tests | Where-Object Result -ne 'Passed' | ForEach-Object { $testresults += [pscustomobject]@{ Block = $_.Block Name = "It $($_.Name)" Result = $_.Result Message = $_.ErrorRecord.DisplayErrorMessage } } } } } #endregion Run General Tests $global:__pester_data.ScriptAnalyzer | Out-Host #region Test Commands if ($TestFunctions) { Write-PSFMessage -Level Important -Message "Proceeding with individual tests" foreach ($file in (Get-ChildItem "$PSScriptRoot\functions" -Recurse -File | Where-Object Name -like "*Tests.ps1")) { if ($file.Name -notlike $Include) { continue } if ($file.Name -like $Exclude) { continue } Write-PSFMessage -Level Significant -Message " Executing $($file.Name)" $config.TestResult.OutputPath = Join-Path "$PSScriptRoot\..\..\TestResults" "TEST-$($file.BaseName).xml" $config.Run.Path = $file.FullName $config.Run.PassThru = $true $config.Output.Verbosity = $Output $results = Invoke-Pester -Configuration $config foreach ($result in $results) { $totalRun += $result.TotalCount $totalFailed += $result.FailedCount $result.Tests | Where-Object Result -ne 'Passed' | ForEach-Object { $testresults += [pscustomobject]@{ Block = $_.Block Name = "It $($_.Name)" Result = $_.Result Message = $_.ErrorRecord.DisplayErrorMessage } } } } } #endregion Test Commands $testresults | Sort-Object Describe, Context, Name, Result, Message | Format-List if ($totalFailed -eq 0) { Write-PSFMessage -Level Critical -Message "All <c='em'>$totalRun</c> tests executed without a single failure!" } else { Write-PSFMessage -Level Critical -Message "<c='em'>$totalFailed tests</c> out of <c='sub'>$totalRun</c> tests failed!" } if ($totalFailed -gt 0) { throw "$totalFailed / $totalRun tests failed!" }
Unprotect-OrganizationalUnit.ps1
ADLDSMF-1.0.0
function Unprotect-OrganizationalUnit { <# .SYNOPSIS Removes deny rules on OrganizationalUnits. .DESCRIPTION Removes deny rules on OrganizationalUnits. Necessary whenever we want to delete an OU. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Identity The OU to unprotect. Specify the full distinguishedname. .EXAMPLE PS C:\> Unprotect-OrganizationalUnit @ldsParam -Identity $ouPath Removes the deletion protection from the OU specified in $ouPath #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [Parameter(Mandatory = $true)] [string] $Identity ) begin { Update-ADSec $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential } process { $adObject = Get-ADObject @ldsParam -Identity $Identity -Partition $Partition -Properties DistinguishedName $acl = Get-AdsAcl @ldsParam -Path $adObject.DistinguishedName $denyRules = $acl.Access | Where-Object AccessControlType -eq Deny if (-not $denyRules) { return } foreach ($rule in $denyRules) { $null = $acl.RemoveAccessRule($rule) } $acl | Set-AdsAcl @ldsParam -Path $adObject.DistinguishedName } }
strings.ps1
ADLDSMF-1.0.0
<# 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 'ADLDSMF' -Language 'en-US'
Manifest.Tests.ps1
ADLDSMF-1.0.0
Describe "Validating the module manifest" { $moduleRoot = (Resolve-Path "$global:testroot\..").Path $manifest = ((Get-Content "$moduleRoot\ADLDSMF.psd1") -join "`n") | Invoke-Expression Context "Basic resources validation" { $files = Get-ChildItem "$moduleRoot\functions" -Recurse -File | Where-Object Name -like "*.ps1" It "Exports all functions in the public folder" -TestCases @{ files = $files; manifest = $manifest } { $functions = (Compare-Object -ReferenceObject $files.BaseName -DifferenceObject $manifest.FunctionsToExport | Where-Object SideIndicator -Like '<=').InputObject $functions | Should -BeNullOrEmpty } It "Exports no function that isn't also present in the public folder" -TestCases @{ files = $files; manifest = $manifest } { $functions = (Compare-Object -ReferenceObject $files.BaseName -DifferenceObject $manifest.FunctionsToExport | Where-Object SideIndicator -Like '=>').InputObject $functions | Should -BeNullOrEmpty } It "Exports none of its internal functions" -TestCases @{ moduleRoot = $moduleRoot; manifest = $manifest } { $files = Get-ChildItem "$moduleRoot\internal\functions" -Recurse -File -Filter "*.ps1" $files | Where-Object BaseName -In $manifest.FunctionsToExport | Should -BeNullOrEmpty } } Context "Individual file validation" { It "The root module file exists" -TestCases @{ moduleRoot = $moduleRoot; manifest = $manifest } { Test-Path "$moduleRoot\$($manifest.RootModule)" | Should -Be $true } foreach ($format in $manifest.FormatsToProcess) { It "The file $format should exist" -TestCases @{ moduleRoot = $moduleRoot; format = $format } { Test-Path "$moduleRoot\$format" | Should -Be $true } } foreach ($type in $manifest.TypesToProcess) { It "The file $type should exist" -TestCases @{ moduleRoot = $moduleRoot; type = $type } { Test-Path "$moduleRoot\$type" | Should -Be $true } } foreach ($assembly in $manifest.RequiredAssemblies) { if ($assembly -like "*.dll") { It "The file $assembly should exist" -TestCases @{ moduleRoot = $moduleRoot; assembly = $assembly } { Test-Path "$moduleRoot\$assembly" | Should -Be $true } } else { It "The file $assembly should load from the GAC" -TestCases @{ moduleRoot = $moduleRoot; assembly = $assembly } { { Add-Type -AssemblyName $assembly } | Should -Not -Throw } } } foreach ($tag in $manifest.PrivateData.PSData.Tags) { It "Tags should have no spaces in name" -TestCases @{ tag = $tag } { $tag -match " " | Should -Be $false } } } }
Help.Tests.ps1
ADLDSMF-1.0.0
<# .NOTES The original test this is based upon was written by June Blender. After several rounds of modifications it stands now as it is, but the honor remains hers. Thank you June, for all you have done! .DESCRIPTION This test evaluates the help for all commands in a module. .PARAMETER SkipTest Disables this test. .PARAMETER CommandPath List of paths under which the script files are stored. This test assumes that all functions have their own file that is named after themselves. These paths are used to search for commands that should exist and be tested. Will search recursively and accepts wildcards, make sure only functions are found .PARAMETER ModuleName Name of the module to be tested. The module must already be imported .PARAMETER ExceptionsFile File in which exceptions and adjustments are configured. In it there should be two arrays and a hashtable defined: $global:FunctionHelpTestExceptions $global:HelpTestEnumeratedArrays $global:HelpTestSkipParameterType These can be used to tweak the tests slightly in cases of need. See the example file for explanations on each of these usage and effect. #> [CmdletBinding()] Param ( [switch] $SkipTest, [string[]] $CommandPath = @("$global:testroot\..\functions", "$global:testroot\..\internal\functions"), [string] $ModuleName = "ADLDSMF", [string] $ExceptionsFile = "$global:testroot\general\Help.Exceptions.ps1" ) if ($SkipTest) { return } . $ExceptionsFile $includedNames = (Get-ChildItem $CommandPath -Recurse -File | Where-Object Name -like "*.ps1").BaseName $commandTypes = @('Cmdlet', 'Function') if ($PSVersionTable.PSEdition -eq 'Desktop' ) { $commandTypes += 'Workflow' } $commands = Get-Command -Module (Get-Module $ModuleName) -CommandType $commandTypes | Where-Object Name -In $includedNames ## When testing help, remember that help is cached at the beginning of each session. ## To test, restart session. foreach ($command in $commands) { $commandName = $command.Name # Skip all functions that are on the exclusions list if ($global:FunctionHelpTestExceptions -contains $commandName) { continue } # The module-qualified command fails on Microsoft.PowerShell.Archive cmdlets $Help = Get-Help $commandName -ErrorAction SilentlyContinue Describe "Test help for $commandName" { # If help is not found, synopsis in auto-generated help is the syntax diagram It "should not be auto-generated" -TestCases @{ Help = $Help } { $Help.Synopsis | Should -Not -BeLike '*`[`<CommonParameters`>`]*' } # Should be a description for every function It "gets description for $commandName" -TestCases @{ Help = $Help } { $Help.Description | Should -Not -BeNullOrEmpty } # Should be at least one example It "gets example code from $commandName" -TestCases @{ Help = $Help } { ($Help.Examples.Example | Select-Object -First 1).Code | Should -Not -BeNullOrEmpty } # Should be at least one example description It "gets example help from $commandName" -TestCases @{ Help = $Help } { ($Help.Examples.Example.Remarks | Select-Object -First 1).Text | Should -Not -BeNullOrEmpty } Context "Test parameter help for $commandName" { $common = 'Debug', 'ErrorAction', 'ErrorVariable', 'InformationAction', 'InformationVariable', 'OutBuffer', 'OutVariable', 'PipelineVariable', 'Verbose', 'WarningAction', 'WarningVariable', 'ProgressAction' $parameters = $command.ParameterSets.Parameters | Sort-Object -Property Name -Unique | Where-Object Name -notin $common $parameterNames = $parameters.Name $HelpParameterNames = $Help.Parameters.Parameter.Name | Sort-Object -Unique foreach ($parameter in $parameters) { $parameterName = $parameter.Name $parameterHelp = $Help.parameters.parameter | Where-Object Name -EQ $parameterName # Should be a description for every parameter It "gets help for parameter: $parameterName : in $commandName" -TestCases @{ parameterHelp = $parameterHelp } { $parameterHelp.Description.Text | Should -Not -BeNullOrEmpty } $codeMandatory = $parameter.IsMandatory.toString() It "help for $parameterName parameter in $commandName has correct Mandatory value" -TestCases @{ parameterHelp = $parameterHelp; codeMandatory = $codeMandatory } { $parameterHelp.Required | Should -Be $codeMandatory } if ($HelpTestSkipParameterType[$commandName] -contains $parameterName) { continue } $codeType = $parameter.ParameterType.Name if ($parameter.ParameterType.IsEnum) { # Enumerations often have issues with the typename not being reliably available $names = $parameter.ParameterType::GetNames($parameter.ParameterType) # Parameter type in Help should match code It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ parameterHelp = $parameterHelp; names = $names } { $parameterHelp.parameterValueGroup.parameterValue | Should -be $names } } elseif ($parameter.ParameterType.FullName -in $HelpTestEnumeratedArrays) { # Enumerations often have issues with the typename not being reliably available $names = [Enum]::GetNames($parameter.ParameterType.DeclaredMembers[0].ReturnType) It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ parameterHelp = $parameterHelp; names = $names } { $parameterHelp.parameterValueGroup.parameterValue | Should -be $names } } else { # To avoid calling Trim method on a null object. $helpType = if ($parameterHelp.parameterValue) { $parameterHelp.parameterValue.Trim() } # Parameter type in Help should match code It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ helpType = $helpType; codeType = $codeType } { $helpType | Should -be $codeType } } } foreach ($helpParm in $HelpParameterNames) { # Shouldn't find extra parameters in help. It "finds help parameter in code: $helpParm" -TestCases @{ helpParm = $helpParm; parameterNames = $parameterNames } { $helpParm -in $parameterNames | Should -Be $true } } } } }
license.ps1
ADLDSMF-1.0.0
New-PSFLicense -Product 'ADLDSMF' -Manufacturer 'frweinma' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2023-12-11") -Text @" Copyright (c) 2023 frweinma 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. "@
Invoke-LdsAccessRule.ps1
ADLDSMF-1.0.0
function Invoke-LdsAccessRule { <# .SYNOPSIS Applies all the configured access rules. .DESCRIPTION Applies all the configured access rules. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsAccessRule -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Apply all configured access rules to the 'DC=fabrikam,DC=org' partition on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-ADSec Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential } process { if (-not $TestResult) { $TestResult = Test-LdsAccessRule @ldsParam -Partition $Partition -Delete:$Delete } foreach ($testItem in $TestResult | Sort-Object Action -Descending) { switch ($testItem.Action) { 'Add' { $acl = Get-AdsAcl @ldsParam -Path $testItem.Identity $acl.AddAccessRule($testItem.Change.Rule) $acl | Set-AdsAcl @ldsParam -Path $testItem.Identity } 'Remove' { $acl = Get-AdsAcl @ldsParam -Path $testItem.Identity $null = $acl.RemoveAccessRule($testItem.Change.Rule) $acl | Set-AdsAcl @ldsParam -Path $testItem.Identity } } } } }
ADLDSMF.psd1
ADLDSMF-1.0.0
@{ # Script module or binary module file associated with this manifest RootModule = 'ADLDSMF.psm1' # Version number of this module. ModuleVersion = '1.0.0' # ID used to uniquely identify this module GUID = '4152b344-748f-43f4-9982-e0f0bec21185' # Author of this module Author = 'Friedrich Weinmann' # Company or vendor of this module CompanyName = ' ' # Copyright statement for this module Copyright = 'Copyright (c) 2023 Friedrich Weinmann' # Description of the functionality provided by this module Description = 'Provisions the content of AD LDS instances' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '5.1' # Modules that must be imported into the global environment prior to importing # this module RequiredModules = @( @{ ModuleName = 'PSFramework'; ModuleVersion = '1.10.318' } @{ ModuleName = 'ADSec'; ModuleVersion = '1.0.1' } ) # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @('bin\ADLDSMF.dll') # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @('xml\ADLDSMF.Types.ps1xml') # Format files (.ps1xml) to be loaded when importing this module FormatsToProcess = @('xml\ADLDSMF.Format.ps1xml') # Functions to export from this module FunctionsToExport = @( 'Get-LdsDomain' 'Import-LdsConfiguration' 'Invoke-LdsAccessRule' 'Invoke-LdsConfiguration' 'Invoke-LdsGroup' 'Invoke-LdsGroupMembership' 'Invoke-LdsOrganizationalUnit' 'Invoke-LdsSchemaAttribute' 'Invoke-LdsUser' 'Reset-LdsAccountPassword' 'Reset-LdsConfiguration' 'Test-LdsAccessRule' 'Test-LdsConfiguration' 'Test-LdsGroup' 'Test-LdsGroupMembership' 'Test-LdsOrganizationalUnit' 'Test-LdsSchemaAttribute' 'Test-LdsUser' ) # Cmdlets to export from this module CmdletsToExport = @() # Variables to export from this module VariablesToExport = @() # Aliases to export from this module AliasesToExport = @() # List of all modules packaged with this module ModuleList = @() # List of all files packaged with this module FileList = @() # Private data to pass to the module specified in ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ #Support for PowerShellGet galleries. PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @('ldap','adlds') # A URL to the license for this module. LicenseUri = 'https://github.com/FriedrichWeinmann/ADLDSMF/blob/master/LICENSE' # A URL to the main website for this project. ProjectUri = 'https://github.com/FriedrichWeinmann/ADLDSMF' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module ReleaseNotes = 'https://github.com/FriedrichWeinmann/ADLDSMF/blob/master/ADLDSMF/changelog.md' } # End of PSData hashtable } # End of PrivateData hashtable }
FileIntegrity.Exceptions.ps1
ADLDSMF-1.0.0
# List of forbidden commands $global:BannedCommands = @( 'Write-Host' #'Write-Verbose' #'Write-Warning' #'Write-Error' 'Write-Output' 'Write-Information' 'Write-Debug' # Use CIM instead where possible 'Get-WmiObject' 'Invoke-WmiMethod' 'Register-WmiEvent' 'Remove-WmiObject' 'Set-WmiInstance' # Use Get-WinEvent instead 'Get-EventLog' ) <# Contains list of exceptions for banned cmdlets. Insert the file names of files that may contain them. Example: "Write-Host" = @('Write-PSFHostColor.ps1','Write-PSFMessage.ps1') #> $global:MayContainCommand = @{ "Write-Host" = @() "Write-Verbose" = @() "Write-Warning" = @() "Write-Error" = @() "Write-Output" = @() "Write-Information" = @() "Write-Debug" = @() }
Import-LdsConfiguration.ps1
ADLDSMF-1.0.0
function Import-LdsConfiguration { <# .SYNOPSIS Import a set of configuration files. .DESCRIPTION Import a set of configuration files. Each configuration file must be a psd1, json or (at PS7+) jsonc file. They can be stored any levels of nested folder deep, but they cannot be hidden. Each file shall contain an array of entries and each entry shall have an objectclass plus all the attributes it should have. Note to include everything an object of the given type must have. For each entry, specifying an objectclass is optional: If none is specified, the name of the parent folder is chosen instead. Thus, creating a folder named "user" will have all settings directly within default to the objectclass "user". Supported Object Classes: - AccessRule - Group - GroupMembership - OrganizationalUnit - SchemaAttribute - User Note: Group Memberships and access rules are not really object entities in AD LDS, but are treated the same for configuration purposes. Example Content: > user.psd1 @{ Name = 'Thomas' Path = 'OU=Admin,%DomainDN%' Enabled = $true } .PARAMETER Path Path to a folder containing all configuration sets. .EXAMPLE PS C:\> Import-LdsConfiguration -Path C:\scripts\lds\config Imports all the configuration files under the specified path, no matter how deeply nested. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Path ) $objectClasses = 'AccessRule', 'Group', 'GroupMembership', 'OrganizationalUnit', 'SchemaAttribute', 'User' $extensions = '.json', '.psd1' if ($PSVersionTable.PSVersion.Major -ge 7) {$extensions = '.json', '.jsonc', '.psd1'} foreach ($file in Get-ChildItem -Path $Path -Recurse -File | Where-Object Extension -In $extensions) { $datasets = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Psd1Mode Unsafe $defaultObjectClass = $file.Directory.Name.ToLower() foreach ($dataset in $datasets) { if (-not $dataset.ObjectClass) { $dataset.ObjectClass = $defaultObjectClass } switch ($dataset.ObjectClass) { 'groupmembership' { $identity = "$($dataset.Group)|$($dataset.Member)|$($dataset.Type)" $script:content.groupmembership.$identity = $dataset } 'accessrule' { $identity = "$($dataset.Path)|$($dataset.Identity)|$($dataset.IdentityType)|$($dataset.Rights)|$($dataset.ObjectType)" $script:content.accessrule.$identity = $dataset } 'SchemaAttribute' { $script:content.SchemaAttribute[$dataSet.AttributeID] = $dataSet } default { if ($dataset.ObjectClass -notin $objectClasses) { Write-PSFMessage -Level Warning -Message 'Invalid Object Class: {0} Importing file "{1}". Legal Values: {2}' -StringValues $dataset.ObjectClass, $file.FullName, ($objectClasses -join ', ') -Tag 'badClass' -Target $dataset } $identity = "$($dataset.Name),$($dataset.Path)" if (-not $script:content.$($dataset.ObjectClass)) { $script:content.$($dataset.ObjectClass) = @{ } } $script:content.$($dataset.ObjectClass)[$identity] = $dataset } } } } }
Invoke-LdsOrganizationalUnit.ps1
ADLDSMF-1.0.0
function Invoke-LdsOrganizationalUnit { <# .SYNOPSIS Creates the desired organizational units. .DESCRIPTION Creates the desired organizational units. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsOrganizationalUnit -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Creates the desired organizational units in 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'Path', 'Name' $filter = { # Delete actions should go from innermost to top-level # Create actions should go from top-level to most nested if ($_.Action -eq 'Delete') { $_.Identity.Length * -1 } else { $_.Identity.Length } } } process { if (-not $TestResult) { $TestResult = Test-LdsOrganizationalUnit @ldsParam -Delete:$Delete } foreach ($testItem in $TestResult | Sort-Object Action, $filter) { switch ($testItem.Action) { 'Create' { $attributes = $testItem.Configuration | ConvertTo-PSFHashtable -Exclude $systemProperties $newParam = @{ Name = $testItem.Configuration.Name Path = ($testItem.Identity -replace '^.+?,') } if (0 -lt $attributes.Count) { $newParam.OtherAttributes = $attributes } New-ADOrganizationalUnit @ldsParamLight @newParam } 'Delete' { Unprotect-OrganizationalUnit @ldsParam -Identity $testItem.ADObject.ObjectGUID Remove-ADOrganizationalUnit @ldsParam -Identity $testItem.ADObject.ObjectGUID -Recursive -Confirm:$false } 'Update' { $update = @{ } foreach ($change in $testItem.Change) { $update[$change.Property] = $change.New } Set-ADObject @ldsParam -Identity $testItem.ADObject.ObjectGUID -Replace $update } } } } }
Test-LdsConfiguration.ps1
ADLDSMF-1.0.0
function Test-LdsConfiguration { <# .SYNOPSIS Test all configured settings against the target LDS instance. .DESCRIPTION Test all configured settings against the target LDS instance. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Options Which part of the configuration to test for. Defaults to all of them ('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute') .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsConfiguration -Server lds1.contoso.com -Partition 'DC=Fabrikam,DC=org' Test all configured settings against the 'DC=Fabrikam,DC=org' LDS instance on server lds1.contoso.com. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [ValidateSet('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute')] [string[]] $Options = @('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute'), [switch] $Delete ) begin { $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential, Delete } process { if ($Options -contains 'SchemaAttribute' -and -not $Delete) { Test-LdsSchemaAttribute @ldsParam } if ($Options -contains 'OrganizationalUnit') { Test-LdsOrganizationalUnit @ldsParam } if ($Options -contains 'Group') { Test-LdsGroup @ldsParam } if ($Options -contains 'User') { Test-LdsUser @ldsParam } if ($Options -contains 'GroupMembership') { Test-LdsGroupMembership @ldsParam } if ($Options -contains 'AccessRule') { Test-LdsAccessRule @ldsParam } } }
initialize.ps1
ADLDSMF-1.0.0
# Make ACL work again $null = Get-Acl -Path . -ErrorAction Ignore # Disable AD Connection Check Set-PSFConfig -FullName 'ADSec.Connect.NoAssertion' -Value $true # Load config if present if (Test-Path -Path "$script:ModuleRoot\Config") { Import-LdsConfiguration -Path "$script:ModuleRoot\Config" }
Test-LdsGroupMembership.ps1
ADLDSMF-1.0.0
function Test-LdsGroupMembership { <# .SYNOPSIS Test whether the group memberships are in their desired state. .DESCRIPTION Test whether the group memberships are in their desired state. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsGroupMembership -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Test whether the group memberships are in their desired state for 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Remap @{ Partition = 'SearchBase' } $members = @{ } $ldsObjects = @{ } } process { foreach ($configurationSets in $script:content.groupmembership.Values | Group-Object { $_.Group }) { Write-PSFMessage -Level Verbose -Message "Processing group memberships of {0}" -StringValues $configurationSets.Name $groupObject = Get-ADGroup @ldsParamLight -LDAPFilter "(name=$($configurationSets.Name))" -Properties * if (-not $groupObject) { Write-PSFMessage -Level Warning -Message "Group not found: {0}! Cannot process members" -StringValues $configurationSets.Name continue } $ldsObjects[$groupObject.DistinguishedName] = $groupObject #region Determine intended members $intendedMembers = foreach ($entry in $configurationSets.Group) { # Read from Cache if ($members["$($entry.Type):$($entry.Member)"]) { $members["$($entry.Type):$($entry.Member)"] continue } # Read from LDS Instance $ldsObject = Get-ADObject @ldsParamLight -LDAPFilter "(&(objectClass=$($entry.Type))(name=$($entry.Member)))" -Properties * # Not Yet Created if (-not $ldsObject) { Write-PSFMessage -Level Warning -Message 'Unable to find {0} {1}, will be unable to add it to group {2}' -StringValues $entry.Type, $entry.Member, $entry.Group continue } $members["$($entry.Type):$($entry.Member)"] = $ldsObject $ldsObjects[$ldsObject.DistinguishedName] = $ldsObject $ldsObject } #endregion Determine intended members #region Determine actual members $actualMembers = foreach ($member in $groupObject.Members) { if ($ldsObjects[$member]) { $ldsObjects[$member] continue } try { $ldsObject = Get-ADObject @ldsParam -Identity $member -Properties * -ErrorAction Stop } catch { Write-PSFMessage -Level Warning -Message "Error resolving member of {0}: {1}" -StringValues $configurationSets.Name, $member -ErrorRecord $_ continue } $ldsObjects[$ldsObject.DistinguishedName] = $ldsObject $ldsObject } #endregion Determine actual members #region Compare and generate changes $toAdd = $intendedMembers | Where-Object DistinguishedName -NotIn $actualMembers.DistinguishedName | ForEach-Object { [PSCustomObject]@{ PSTypename = 'AdLdsTools.Change.GroupMembership' Action = 'Add' Member = $_.Name Type = $_.ObjectClass DN = $_.DistinguishedName Group = $configurationSets.Name } } if ($Delete) { $toAdd = @() } $toRemove = $actualMembers | Where-Object { (-not $Delete -and $_.DistinguishedName -NotIn $intendedMembers.DistinguishedName) -or ($Delete -and $_.DistinguishedName -in $intendedMembers.DistinguishedName) } | ForEach-Object { [PSCustomObject]@{ PSTypename = 'AdLdsTools.Change.GroupMembership' Action = 'Remove' Member = $_.Name Type = $_.ObjectClass DN = $_.DistinguishedName Group = $configurationSets.Name } } $changes = @($toAdd) + @($toRemove) | Remove-PSFNull | Add-Member -MemberType ScriptMethod -Name ToString -Value { '{0} -> {1}' -f $this.Action, $this.Member } -Force -PassThru #endregion Compare and generate changes if ($changes) { New-TestResult -Type GroupMemberShip -Action Update -Identity $groupObject.Name -ADObject $groupObject -Configuration $configurationSets -Change $changes } } } }
New-Change.ps1
ADLDSMF-1.0.0
function New-Change { <# .SYNOPSIS Create a new change object. .DESCRIPTION Create a new change object. Helper command that unifies result generation. .PARAMETER Identity The identity the change applies to. .PARAMETER Property What property is being modified. .PARAMETER OldValue The old value that is being updated. .PARAMETER NewValue The new value that will be set instead. .PARAMETER DisplayStyle How the change will display in text form. Defaults to: NewValue .PARAMETER Data Additional data to include in the change. .EXAMPLE PS C:\> New-Change -Identity "CN=max,OU=Users,DC=Fabrikam,DC=org" Property LuckyNumber -OldValue 1 -NewValue 42 Creates a new change. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Identity, [Parameter(Mandatory = $true)] [string] $Property, [AllowEmptyCollection()] [AllowNull()] $OldValue, [AllowEmptyCollection()] [AllowNull()] $NewValue, [ValidateSet('NewValue', 'RemoveValue')] [string] $DisplayStyle = 'NewValue', [AllowEmptyCollection()] [AllowNull()] $Data ) $dsStyles = @{ 'NewValue' = { '{0} -> {1}' -f $this.Property, $this.New } 'RemoveValue' = { '{0} Remove {1}' -f $this.Property, $this.Old } } $object = [PSCustomObject]@{ PSTypeName = 'AdLds.Change' Identity = $Identity Property = $Property Old = $OldValue New = $NewValue Data = $Data } Add-Member -InputObject $object -MemberType ScriptMethod -Name ToString -Value $dsStyles[$DisplayStyle] -Force $object }
configuration.ps1
ADLDSMF-1.0.0
<# 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 'ADLDSMF' -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 'ADLDSMF' -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 'ADLDSMF' -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."
strings.psd1
ADLDSMF-1.0.0
# This is where the strings go, that are written by # Write-PSFMessage, Stop-PSFFunction or the PSFramework validation scriptblocks @{ 'key' = 'Value' }
Reset-LdsConfiguration.ps1
ADLDSMF-1.0.0
function Reset-LdsConfiguration { <# .SYNOPSIS Removes all registered configuration settings. .DESCRIPTION Removes all registered configuration settings. .EXAMPLE PS C:\> Reset-LdsConfiguration Removes all registered configuration settings. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param () $script:content = @{ user = @{ } group = @{ } organizationalUnit = @{ } groupmembership = @{ } accessrule = @{ } SchemaAttribute = @{ } } }
FileIntegrity.Tests.ps1
ADLDSMF-1.0.0
$moduleRoot = (Resolve-Path "$global:testroot\..").Path . "$global:testroot\general\FileIntegrity.Exceptions.ps1" Describe "Verifying integrity of module files" { BeforeAll { function Get-FileEncoding { <# .SYNOPSIS Tests a file for encoding. .DESCRIPTION Tests a file for encoding. .PARAMETER Path The file to test #> [CmdletBinding()] Param ( [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [Alias('FullName')] [string] $Path ) if ($PSVersionTable.PSVersion.Major -lt 6) { [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path } else { [byte[]]$byte = Get-Content -AsByteStream -ReadCount 4 -TotalCount 4 -Path $Path } if ($byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf) { 'UTF8 BOM' } elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff) { 'Unicode' } elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff) { 'UTF32' } elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76) { 'UTF7' } else { 'Unknown' } } } Context "Validating PS1 Script files" { $allFiles = Get-ChildItem -Path $moduleRoot -Recurse | Where-Object Name -like "*.ps1" | Where-Object FullName -NotLike "$moduleRoot\tests\*" foreach ($file in $allFiles) { $name = $file.FullName.Replace("$moduleRoot\", '') It "[$name] Should have UTF8 encoding with Byte Order Mark" -TestCases @{ file = $file } { Get-FileEncoding -Path $file.FullName | Should -Be 'UTF8 BOM' } It "[$name] Should have no trailing space" -TestCases @{ file = $file } { ($file | Select-String "\s$" | Where-Object { $_.Line.Trim().Length -gt 0}).LineNumber | Should -BeNullOrEmpty } $tokens = $null $parseErrors = $null $ast = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$tokens, [ref]$parseErrors) It "[$name] Should have no syntax errors" -TestCases @{ parseErrors = $parseErrors } { $parseErrors | Should -BeNullOrEmpty } foreach ($command in $global:BannedCommands) { if ($global:MayContainCommand["$command"] -notcontains $file.Name) { It "[$name] Should not use $command" -TestCases @{ tokens = $tokens; command = $command } { $tokens | Where-Object Text -EQ $command | Should -BeNullOrEmpty } } } } } Context "Validating help.txt help files" { $allFiles = Get-ChildItem -Path $moduleRoot -Recurse | Where-Object Name -like "*.help.txt" | Where-Object FullName -NotLike "$moduleRoot\tests\*" foreach ($file in $allFiles) { $name = $file.FullName.Replace("$moduleRoot\", '') It "[$name] Should have UTF8 encoding" -TestCases @{ file = $file } { Get-FileEncoding -Path $file.FullName | Should -Be 'UTF8 BOM' } It "[$name] Should have no trailing space" -TestCases @{ file = $file } { ($file | Select-String "\s$" | Where-Object { $_.Line.Trim().Length -gt 0 } | Measure-Object).Count | Should -Be 0 } } } }
Test-LdsOrganizationalUnit.ps1
ADLDSMF-1.0.0
function Test-LdsOrganizationalUnit { <# .SYNOPSIS Tests, whether the desired organizational units exist. .DESCRIPTION Tests, whether the desired organizational units exist. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsOrganizationalUnit -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests, whether the desired organizational units exist in 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $systemProperties = 'ObjectClass', 'Path', 'Name' } process { foreach ($configurationItem in $script:content.organizationalUnit.Values) { $path = 'OU={0},{1}' -f $configurationItem.Name, ($configurationItem.Path -replace '%DomainDN%',$Partition) if ($path -notmatch ',DC=') { $path = $path, $Partition -join ',' } $resultDefaults = @{ Type = 'OrganizationalUnit' Identity = $path Configuration = $configurationItem } $failed = $null $adObject = $null try { $adObject = Get-ADOrganizationalUnit @ldsParam -Identity $path -Properties * -ErrorAction SilentlyContinue -ErrorVariable failed } catch { $failed = $_ } if ($failed -and $failed.CategoryInfo.Category -ne 'ObjectNotFound') { foreach ($failure in $failed) { Write-Error $failure } continue } #region Cases # Case: Does not Exist if (-not $adObject) { if ($Delete) { continue } New-TestResult @resultDefaults -Action Create continue } # Case: Exists $resultDefaults.ADObject = $adObject if ($Delete) { New-TestResult @resultDefaults -Action Delete continue } $changes = foreach ($pair in $configurationItem.GetEnumerator()) { if ($pair.Key -in $systemProperties) { continue } if ($pair.Value -ne $adObject.$($pair.Key)) { New-Change -Identity $path -Property $pair.Key -OldValue $adObject.$($pair.Key) -NewValue $pair.Value } } if ($changes) { New-TestResult @resultDefaults -Action Update -Change $changes } #endregion Cases } } }
Update-ADSec.ps1
ADLDSMF-1.0.0
function Update-ADSec { <# .SYNOPSIS Injects Get-LdsDomain into the ADSec module to overwrite its use of Get-ADDomain. .DESCRIPTION Injects Get-LdsDomain into the ADSec module to overwrite its use of Get-ADDomain. This enables us to override the AD domain connection verification performed by the module. .EXAMPLE PS C:\> Update-ADSec Injects Get-LdsDomain into the ADSec module to overwrite its use of Get-ADDomain. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param () & (Get-Module ADSec) { Set-Alias -Name Get-ADDomain -Value Get-LdsDomain -Scope Script } }
Test-LdsSchemaAttribute.ps1
ADLDSMF-1.0.0
function Test-LdsSchemaAttribute { <# .SYNOPSIS Tests, whether the intended schema attributes have been applied. .DESCRIPTION Tests, whether the intended schema attributes have been applied. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .EXAMPLE PS C:\> Test-LdsSchemaAttribute -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests, whether the intended schema attributes have been applied to 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'AttributeID', 'IsDeleted', 'Optional', 'MayContain' $rootDSE = Get-ADRootDSE @ldsParamLight $classes = Get-ADObject @ldsParamLight -SearchBase $rootDSE.schemaNamingContext -LDAPFilter '(objectClass=classSchema)' -Properties mayContain, adminDisplayName } process { foreach ($schemaSetting in $script:content.SchemaAttribute.Values) { $schemaObject = $null $schemaObject = Get-ADObject @ldsParamLight -LDAPFilter "(attributeID=$($schemaSetting.AttributeID))" -SearchBase $rootDSE.schemaNamingContext -ErrorAction Ignore -Properties * $resultDefaults = @{ Type = 'SchemaAttribute' Identity = $schemaSetting.AdminDisplayName Configuration = $schemaSetting } if (-not $schemaObject) { # If we already want to disable the attribute, no need to create it if ($schemaSetting.IsDeleted) { continue } if ($schemaSetting.Optional) { continue } New-TestResult @resultDefaults -Action Create foreach ($entry in $schemaSetting.MayContain) { if ($classes.AdminDisplayName -notcontains $entry) { continue } New-TestResult @resultDefaults -Action Add -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property MayContain -NewValue $entry -Data ($classes | Where-Object AdminDisplayName -EQ $entry) ) } continue } $resultDefaults.ADObject = $schemaObject if ($schemaSetting.IsDeleted -and -not $schemaObject.isDeleted) { New-TestResult @resultDefaults -Action Delete -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property IsDeleted -OldValue $false -NewValue $true ) } if ($schemaSetting.Name -and $schemaSetting.Name -cne $schemaObject.Name) { New-TestResult @resultDefaults -Action Rename -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property Name -OldValue $schemaObject.Name -NewValue $schemaSetting.Name ) } $changes = foreach ($pair in $schemaSetting.GetEnumerator()) { if ($pair.Key -in $systemProperties) { continue } if ($pair.Value -cne $schemaObject.$($pair.Key)) { New-Change -Identity $schemaSetting.AdminDisplayName -Property $pair.Key -OldValue $schemaObject.$($pair.Key) -NewValue $pair.Value } } if ($changes) { New-TestResult @resultDefaults -Action Update -Change $changes } $mayBeContainedIn = $schemaSetting.MayContain if ($schemaSetting.IsDeleted) { $mayBeContainedIn = @() } $classesMatch = $classes | Where-Object mayContain -Contains $schemaObject.LdapDisplayName foreach ($matchingclass in $classesMatch) { if ($matchingclass.AdminDisplayName -in $mayBeContainedIn) { continue } New-TestResult @resultDefaults -Action Remove -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property MayContain -OldValue $matchingclass.AdminDisplayName -DisplayStyle RemoveValue -Data $matchingClass ) } foreach ($allowedClass in $mayBeContainedIn) { if ($classesMatch.AdminDisplayName -contains $allowedClass) { continue } New-TestResult @resultDefaults -Action Add -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property MayContain -NewValue $allowedClass -Data ($classes | Where-Object AdminDisplayName -EQ $allowedClass) ) } } } }
New-TestResult.ps1
ADLDSMF-1.0.0
function New-TestResult { <# .SYNOPSIS A new test result, as produced by any of the test commands. .DESCRIPTION A new test result, as produced by any of the test commands. This helper function ensures that all test results look the same. .PARAMETER Type What kind object is being tested. Should receive the objectclass being affected. .PARAMETER Action What we do with the object in question. .PARAMETER Identity The specific object being changed. .PARAMETER Change Any specific change data that will be applied to the object. See New-Change for more details on that structure. .PARAMETER ADObject The actual AD LDS Object being modified. Will usually be $null when creating something new. .PARAMETER Configuration The configuration object based on which the change will be applied. .EXAMPLE PS C:\> New-TestResult -Type User -Action Create -Identity $userName -Configuration $configSet Test result heralding the creation of a new user. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [string] $Type, [ValidateSet('Create', 'Update', 'Delete', 'Add', 'Remove', 'Rename')] [string] $Action, [string] $Identity, $Change, $ADObject, $Configuration ) [PSCustomObject]@{ PSTypeName = 'AdLds.Testresult' Type = $Type Action = $Action Identity = $Identity Change = $Change ADObject = $ADObject Configuration = $Configuration } }
strings.Exceptions.ps1
ADLDSMF-1.0.0
$exceptions = @{ } <# A list of entries that MAY be in the language files, without causing the tests to fail. This is commonly used in modules that generate localized messages straight from C#. Specify the full key as it is written in the language files, do not prepend the modulename, as you would have to in C# code. Example: $exceptions['LegalSurplus'] = @( 'Exception.Streams.FailedCreate' 'Exception.Streams.FailedDispose' ) #> $exceptions['LegalSurplus'] = @( ) <# A list of entries that MAY be used without needing to have text defined. This is intended for modules (re-)using strings provided by another module #> $exceptions['NoTextNeeded'] = @( 'Validate.FSPath' 'Validate.FSPath.File' 'Validate.FSPath.FileOrParent' 'Validate.FSPath.Folder' 'Validate.Path' 'Validate.Path.Container' 'Validate.Path.Leaf' 'Validate.TimeSpan.Positive' 'Validate.Uri.Absolute' 'Validate.Uri.Absolute.File' 'Validate.Uri.Absolute.Https' ) $exceptions
Test-LdsAccessRule.ps1
ADLDSMF-1.0.0
function Test-LdsAccessRule { <# .SYNOPSIS Tests, whether the current access rules match the configured state. .DESCRIPTION Tests, whether the current access rules match the configured state. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsAccessRule -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests, whether the current access rules on lds1.contoso.com match the configured state. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { #region Functions function Resolve-AccessRule { [OutputType([System.DirectoryServices.ActiveDirectoryAccessRule])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] $RuleCfg, [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [hashtable] $SchemaCache = @{ }, [hashtable] $PrincipalCache = @{ }, [string] $DomainSID ) $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential $rights = $script:adrights[$RuleCfg.Rights] # resolve AccessRule settings $inheritanceType = 'None' if ($RuleCfg.Inheritance) { $inheritanceType = $RuleCfg.Inheritance } $objectType = [guid]::Empty $inheritedObjectType = [guid]::Empty if ($RuleCfg.ObjectType) { $objectType = $RuleCfg.ObjectType | Resolve-SchemaGuid @ldsParam -Cache $SchemaCache } if ($RuleCfg.InheritedObjectType) { $inheritedObjectType = $RuleCfg.InheritedObjectType | Resolve-SchemaGuid @ldsParam -Cache $SchemaCache } $type = 'Allow' if ($RuleCfg.Type) { $type = $RuleCfg.Type } $principal = $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] if (-not $principal -and 'SID' -eq $RuleCfg.IdentityType){ $ruleIdentity = $RuleCfg.Identity -replace '%DomainSID%', $DomainSID $sid = $ruleIdentity -as [System.Security.Principal.SecurityIdentifier] if (-not $sid) { throw "Principal is not a legal SID: $($RuleCfg.Identity)!" } $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] = $sid $principal = $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] } elseif (-not $principal) { $principalObject = Get-ADObject @ldsParam -SearchBase $Partition -LDAPFilter "(&(objectClass=$($RuleCfg.IdentityType))(name=$($RuleCfg.Identity)))" -Properties ObjectSID -ErrorAction Stop if (-not $principalObject) { throw "Principal not found: $($RuleCfg.IdentityType) - $($RuleCfg.Identity)" } $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] = $principalObject.ObjectSID $principal = $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] } [System.DirectoryServices.ActiveDirectoryAccessRule]::new( $principal, $rights, $type, $objectType, $inheritanceType, $inheritedObjectType ) } function Compare-AccessRule { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.DirectoryServices.ActiveDirectoryAccessRule[]] $Reference, [Parameter(Mandatory = $true, ValueFromPipeline = $true)] $InputObject, [switch] $NoMatch ) process { if (-not $InputObject) { return } $isMatched = $false foreach ($referenceObject in $Reference) { if ($referenceObject.ActiveDirectoryRights -bxor $InputObject.ActiveDirectoryRights) { continue } if ($referenceObject.InheritanceType -ne $InputObject.InheritanceType) { continue } if ($referenceObject.ObjectType -ne $InputObject.ObjectType) { continue } if ($referenceObject.InheritedObjectType -ne $InputObject.InheritedObjectType) { continue } if ($referenceObject.AccessControlType -ne $InputObject.AccessControlType) { continue } if ("$($referenceObject.IdentityReference)" -ne "$($InputObject.IdentityReference)") { continue } $isMatched = $true break } if ($isMatched -eq -not $NoMatch) { $InputObject } } } function Get-ObjectDefaultRule { [CmdletBinding()] param ( [string] $Path, [hashtable] $LdsParam, [hashtable] $LdsParamLight, $RootDSE, [hashtable] $DefaultPermissions ) $adObject = Get-ADObject @LdsParam -Identity $Path -Properties ObjectClass if ($DefaultPermissions.ContainsKey($adObject.ObjectClass)) { return $DefaultPermissions[$adObject.ObjectClass] } $class = Get-ADObject @ldsParamLight -SearchBase $RootDSE.schemaNamingContext -LDAPFilter "(&(objectClass=classSchema)(ldapDisplayName=$($adObject.ObjectClass)))" -Properties defaultSecurityDescriptor $acl = [System.DirectoryServices.ActiveDirectorySecurity]::new() $acl.SetSecurityDescriptorSddlForm($class.defaultSecurityDescriptor) $DefaultPermissions[$adObject.ObjectClass] = $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) $DefaultPermissions[$adObject.ObjectClass] } #endregion Functions Update-ADSec Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $rootDSE = Get-ADRootDSE @ldsParamLight $domainSID = (Get-ADObject @ldsParamLight -LDAPFilter '(&(objectCategory=group)(name=Administrators))' -SearchBase $ldsParam.Partition -Properties objectSID).ObjectSID.Value -replace '-512$' $principals = @{ } $schemaCache = @{ } $pathCache = @{ } } process { #region Adding foreach ($ruleCfg in $script:content.accessrule.Values) { $resolvedPath = $ruleCfg.Path -replace '%DomainDN%', $Partition try { $rule = Resolve-AccessRule @ldsParam -RuleCfg $ruleCfg -SchemaCache $schemaCache -PrincipalCache $principals -DomainSID $domainSID } catch { Write-PSFMessage -Level Warning -Message "Failed to process rule for $resolvedPath, granting $($ruleCfg.Rights) to $($ruleCfg.Identity)" -ErrorRecord $_ continue } if (-not $pathCache[$resolvedPath]) { $pathCache[$resolvedPath] = @($rule) } else { $pathCache[$resolvedPath] = @($pathCache[$resolvedPath]) + @($rule) } $acl = Get-AdsAcl @ldsParamLight -Path $resolvedPath $currentRules = $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) $matching = $currentRules | Compare-AccessRule -Reference $rule $change = [PSCustomObject]@{ Path = $resolvedPath Name = $ruleCfg.Identity Right = $ruleCfg.Rights Type = $rule.AccessControlType Rule = $rule } Add-Member -InputObject $change -MemberType ScriptMethod -Name ToString -Force -Value { if ('Allow' -eq $this.Type) { '{0} -> {1}' -f $this.Name, $this.Right } else { '{0} != {1}' -f $this.Name, $this.Right } } if ($matching) { if ($Delete) { $change.Rule = $matching New-TestResult -Type AccessRule -Action Remove -Identity $resolvedPath -Configuration $ruleCfg -ADObject $acl -Change $change } continue } if ($Delete) { continue } New-TestResult -Type AccessRule -Action Add -Identity $resolvedPath -Configuration $ruleCfg -ADObject $acl -Change $change } #endregion Adding #region Removing $schemaDefaultPermissions = @{ } $sidToName = @{ } foreach ($adPath in $pathCache.Keys) { $defaultRules = Get-ObjectDefaultRule -Path $adPath -LdsParam $ldsParam -LdsParamLight $ldsParamLight -RootDSE $rootDSE -DefaultPermissions $schemaDefaultPermissions $intendedRules = @($defaultRules) + @($pathCache[$adPath]) | Remove-PSFNull $acl = Get-AdsAcl @ldsParamLight -Path $adPath $currentRules = $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) $surplusRules = $currentRules | Compare-AccessRule -Reference $intendedRules -NoMatch foreach ($surplusRule in $surplusRules) { # Skip OU deletion protection if ('S-1-1-0' -eq $surplusRule.IdentityReference -and 'Deny' -eq $surplusRule.AccessControlType) { continue } if (-not $sidToName[$surplusRule.IdentityReference]) { try { $sidToName[$surplusRule.IdentityReference] = Get-ADObject @ldsParamLight -SearchBase $Partition -LDAPFilter "(objectSID=$($surplusRule.IdentityReference))" -Properties Name } catch { $sidToName[$surplusRule.IdentityReference] = @{ Name = $surplusRule.IdentityReference }} if (-not $sidToName[$surplusRule.IdentityReference]) { $sidToName[$surplusRule.IdentityReference] = @{ Name = $surplusRule.IdentityReference } } } $change = [PSCustomObject]@{ Path = $adPath Name = $sidToName[$surplusRule.IdentityReference].Name Right = $surplusRule.ActiveDirectoryRights Type = $surplusRule.AccessControlType Rule = $surplusRule } Add-Member -InputObject $change -MemberType ScriptMethod -Name ToString -Force -Value { if ('Allow' -eq $this.Type) { '{0} -> {1}' -f $this.Name, $this.Right } else { '{0} != {1}' -f $this.Name, $this.Right } } New-TestResult -Type AccessRule -Action Remove -Identity $adPath -ADObject $acl -Change $change } } #endregion Removing } }
assignment.ps1
ADLDSMF-1.0.0
<# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name ADLDSMF.alcohol #>
postimport.ps1
ADLDSMF-1.0.0
<# Add all things you want to run after importing the main function code WARNING: ONLY provide paths to files! After building the module, this file will be completely ignored, adding anything but paths to files ... - Will not work after publishing - Could break the build process #> $moduleRoot = Split-Path (Split-Path $PSScriptRoot) # Load Configurations (Get-ChildItem "$moduleRoot\internal\configurations\*.ps1" -ErrorAction Ignore).FullName # Load Scriptblocks (Get-ChildItem "$moduleRoot\internal\scriptblocks\*.ps1" -ErrorAction Ignore).FullName # Load Tab Expansion (Get-ChildItem "$moduleRoot\internal\tepp\*.tepp.ps1" -ErrorAction Ignore).FullName # Load Tab Expansion Assignment "$moduleRoot\internal\tepp\assignment.ps1" # Load variables "$moduleRoot\internal\scripts\variables.ps1" # Start stuff "$moduleRoot\internal\scripts\initialize.ps1" # Load License "$moduleRoot\internal\scripts\license.ps1"
Get-LdsDomain.ps1
ADLDSMF-1.0.0
function Get-LdsDomain { <# .SYNOPSIS Returns a pseudo-domain object from an LDS instance. .DESCRIPTION Returns a pseudo-domain object from an LDS instance. Use to transparently redirect Get-ADDomain calls. .PARAMETER LdsServer LDS Server instance to use. Reads from cache if provided. .PARAMETER LdsPartition LDS partition to use. Reads from cache if provided. .EXAMPLE PS C:\> Get-LdsDomain Returns the default domain #> param ( [string] $LdsServer = $script:_ldsServer, [string] $LdsPartition = $script:_ldsPartition ) $object = Get-ADObject -LdapFilter '(objectClass=domainDns)' -Server $LdsServer -SearchBase $LdsPartition -Properties * Add-Member -InputObject $object -MemberType NoteProperty -Name NetbiosName -Value $object.Name -Force Add-Member -InputObject $object -MemberType NoteProperty -Name DnsRoot -Value ($object.DistinguishedName -replace "DC=" -replace ",", ".") -Force $groupSid = Get-ADObject -LdapFilter '(&(objectClass=group)(isCriticalSystemObject=TRUE))' -Server $LdsServer -SearchBase $LdsPartition -Properties ObjectSID -ResultSetSize 1 | ForEach-Object ObjectSID Add-Member -InputObject $object -MemberType NoteProperty -Name DomainSID -Value (($groupSid.Value -replace '-\d+$') -as [System.Security.Principal.SecurityIdentifier]) -Force $object }
PSScriptAnalyzer.Tests.ps1
ADLDSMF-1.0.0
[CmdletBinding()] Param ( [switch] $SkipTest, [string[]] $CommandPath = @("$global:testroot\..\functions", "$global:testroot\..\internal\functions") ) if ($SkipTest) { return } $global:__pester_data.ScriptAnalyzer = New-Object System.Collections.ArrayList Describe 'Invoking PSScriptAnalyzer against commandbase' { $commandFiles = foreach ($path in $CommandPath) { Get-ChildItem -Path $path -Recurse | Where-Object Name -like "*.ps1" } $scriptAnalyzerRules = Get-ScriptAnalyzerRule foreach ($file in $commandFiles) { Context "Analyzing $($file.BaseName)" { $analysis = Invoke-ScriptAnalyzer -Path $file.FullName -ExcludeRule PSAvoidTrailingWhitespace, PSShouldProcess forEach ($rule in $scriptAnalyzerRules) { It "Should pass $rule" -TestCases @{ analysis = $analysis; rule = $rule } { If ($analysis.RuleName -contains $rule) { $analysis | Where-Object RuleName -EQ $rule -outvariable failures | ForEach-Object { $null = $global:__pester_data.ScriptAnalyzer.Add($_) } 1 | Should -Be 0 } else { 0 | Should -Be 0 } } } } } }
Invoke-LdsSchemaAttribute.ps1
ADLDSMF-1.0.0
function Invoke-LdsSchemaAttribute { <# .SYNOPSIS Applies the intended schema attributes. .DESCRIPTION Applies the intended schema attributes. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsSchemaAttribute -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Applies the intended schema attributes to 'DC=fabrikam,DC=org' on lds1.contoso.com. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'AttributeID', 'IsDeleted', 'Optional', 'MayContain' $rootDSE = Get-ADRootDSE @ldsParamLight } process { if (-not $TestResult) { $TestResult = Test-LdsSchemaAttribute @ldsParam } $testResultsSorted = $TestResult | Sort-Object { switch ($_.Action) { Create { 1 } Delete { 2 } Update { 3 } Add { 4 } Remove { 5 } Default { 6 } } } foreach ($testItem in $testResultsSorted) { switch ($testItem.Action) { 'Create' { $attributes = $testItem.Configuration | ConvertTo-PSFHashtable -Exclude $systemProperties $attributes.AttributeID = $testItem.Configuration.AttributeID $name = $testItem.Configuration.Name if (-not $name) { $name = $testItem.Configuration.AdminDisplayName } New-ADObject @ldsParamLight -Type attributeSchema -Name $name -Path $rootDSE.schemaNamingContext -OtherAttributes $attributes } 'Delete' { $testItem.ADObject | Set-ADObject @ldsParamLight -Replace @{ IsDeleted = $true } } 'Update' { $replacements = @{ } foreach ($change in $testItem.Change) { $replacements[$change.Property] = $change.New } $testItem.ADObject | Set-ADObject @ldsParamLight -Replace $replacements } 'Add' { $testItem.Change.Data | Set-ADObject @ldsParamLight -Add @{ mayContain = $testItem.ADObject.lDAPDisplayName } } 'Remove' { $testItem.Change.Data | Set-ADObject @ldsParamLight -Remove @{ mayContain = $testItem.Identity } } 'Rename' { $testItem.ADObject | Rename-ADObject @ldsParamLight -NewName @($testItem.Change.New)[0] } } } } }
strings.Tests.ps1
ADLDSMF-1.0.0
<# .DESCRIPTION This test verifies, that all strings that have been used, are listed in the language files and thus have a message being displayed. It also checks, whether the language files have orphaned entries that need cleaning up. #> Describe "Testing localization strings" { $moduleRoot = (Get-Module ADLDSMF).ModuleBase $stringsResults = Export-PSMDString -ModuleRoot $moduleRoot $exceptions = & "$global:testroot\general\strings.Exceptions.ps1" foreach ($stringEntry in $stringsResults) { if ($stringEntry.String -eq "key") { continue } # Skipping the template default entry It "Should be used & have text: $($stringEntry.String)" -TestCases @{ stringEntry = $stringEntry; exceptions = $exceptions } { if ($exceptions.LegalSurplus -notcontains $stringEntry.String) { $stringEntry.Surplus | Should -BeFalse } if ($exceptions.NoTextNeeded -notcontains $stringEntry.String) { $stringEntry.Text | Should -Not -BeNullOrEmpty } } } }
Invoke-LdsConfiguration.ps1
ADLDSMF-1.0.0
function Invoke-LdsConfiguration { <# .SYNOPSIS Applies all currently configured settings to the target AD LDS server. .DESCRIPTION Applies all currently configured settings to the target AD LDS server. Use Import-LdsConfiguration first to load one or more configuration sets. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Options Which part of the configuration to deploy. Defaults to all of them ('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute') .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Invoke-LdsConfiguration -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Applies all currently configured settings to the target AD LDS server. .EXAMPLE PS C:\> Invoke-LdsConfiguration -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' -Options User, Group, OrganizationalUnit Applies all currently configured users, groups and OUs to the target AD LDS server. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [ValidateSet('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute')] [string[]] $Options = @('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute'), [switch] $Delete ) begin { $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential } process { if ($Options -contains 'SchemaAttribute') { Invoke-LdsSchemaAttribute @ldsParam } if ($Options -contains 'OrganizationalUnit') { Invoke-LdsOrganizationalUnit @ldsParam -Delete:$Delete } if ($Options -contains 'Group') { Invoke-LdsGroup @ldsParam -Delete:$Delete } if ($Options -contains 'User') { Invoke-LdsUser @ldsParam -Delete:$Delete } if ($Options -contains 'GroupMembership') { Invoke-LdsGroupMembership @ldsParam -Delete:$Delete } if ($Options -contains 'AccessRule') { Invoke-LdsAccessRule @ldsParam -Delete:$Delete } } }
ADLDSMF.psm1
ADLDSMF-1.0.0
$script:ModuleRoot = $PSScriptRoot $script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\ADLDSMF.psd1").ModuleVersion # Detect whether at some level dotsourcing was enforced $script:doDotSource = Get-PSFConfigValue -FullName ADLDSMF.Import.DoDotSource -Fallback $false if ($ADLDSMF_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 ADLDSMF.Import.IndividualFiles -Fallback $false if ($ADLDSMF_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 'ADLDSMF' -Language 'en-US' function New-Change { <# .SYNOPSIS Create a new change object. .DESCRIPTION Create a new change object. Helper command that unifies result generation. .PARAMETER Identity The identity the change applies to. .PARAMETER Property What property is being modified. .PARAMETER OldValue The old value that is being updated. .PARAMETER NewValue The new value that will be set instead. .PARAMETER DisplayStyle How the change will display in text form. Defaults to: NewValue .PARAMETER Data Additional data to include in the change. .EXAMPLE PS C:\> New-Change -Identity "CN=max,OU=Users,DC=Fabrikam,DC=org" Property LuckyNumber -OldValue 1 -NewValue 42 Creates a new change. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Identity, [Parameter(Mandatory = $true)] [string] $Property, [AllowEmptyCollection()] [AllowNull()] $OldValue, [AllowEmptyCollection()] [AllowNull()] $NewValue, [ValidateSet('NewValue', 'RemoveValue')] [string] $DisplayStyle = 'NewValue', [AllowEmptyCollection()] [AllowNull()] $Data ) $dsStyles = @{ 'NewValue' = { '{0} -> {1}' -f $this.Property, $this.New } 'RemoveValue' = { '{0} Remove {1}' -f $this.Property, $this.Old } } $object = [PSCustomObject]@{ PSTypeName = 'AdLds.Change' Identity = $Identity Property = $Property Old = $OldValue New = $NewValue Data = $Data } Add-Member -InputObject $object -MemberType ScriptMethod -Name ToString -Value $dsStyles[$DisplayStyle] -Force $object } function New-Password { <# .SYNOPSIS Generate a new, complex password. .DESCRIPTION Generate a new, complex password. .PARAMETER Length The length of the password calculated. Defaults to 32 .PARAMETER AsSecureString Returns the password as secure string. .EXAMPLE PS C:\> New-Password Generates a new 32v character password. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] [CmdletBinding()] Param ( [int] $Length = 32, [switch] $AsSecureString ) begin { $characters = @{ 0 = @('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z') 1 = @('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') 2 = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 3 = @('#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@') 4 = @('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z') 5 = @('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') 6 = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 7 = @('#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@') } } process { $letters = foreach ($number in (5..$Length)) { $characters[(($number % 4) + (0..4 | Get-Random))] | Get-Random } 0, 1, 2, 3 | ForEach-Object { $letters += $characters[$_] | Get-Random } $letters = $letters | Sort-Object { Get-Random } if ($AsSecureString) { $letters -join "" | ConvertTo-SecureString -AsPlainText -Force } else { $letters -join "" } } } function New-TestResult { <# .SYNOPSIS A new test result, as produced by any of the test commands. .DESCRIPTION A new test result, as produced by any of the test commands. This helper function ensures that all test results look the same. .PARAMETER Type What kind object is being tested. Should receive the objectclass being affected. .PARAMETER Action What we do with the object in question. .PARAMETER Identity The specific object being changed. .PARAMETER Change Any specific change data that will be applied to the object. See New-Change for more details on that structure. .PARAMETER ADObject The actual AD LDS Object being modified. Will usually be $null when creating something new. .PARAMETER Configuration The configuration object based on which the change will be applied. .EXAMPLE PS C:\> New-TestResult -Type User -Action Create -Identity $userName -Configuration $configSet Test result heralding the creation of a new user. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [string] $Type, [ValidateSet('Create', 'Update', 'Delete', 'Add', 'Remove', 'Rename')] [string] $Action, [string] $Identity, $Change, $ADObject, $Configuration ) [PSCustomObject]@{ PSTypeName = 'AdLds.Testresult' Type = $Type Action = $Action Identity = $Identity Change = $Change ADObject = $ADObject Configuration = $Configuration } } function Resolve-SchemaGuid { <# .SYNOPSIS Resolves the name of an attribute or objectclass to its GUID form. .DESCRIPTION Resolves the name of an attribute or objectclass to its GUID form. Used to enable user-friendly names in configuration. + Supports caching requests to optimize performance + Will return guids unmodified .PARAMETER Name The name or guid of the attribute or object class. Guids will be returned unverified. .PARAMETER Server The LDS Server to connect to. .PARAMETER Credential The credentials - if any - to use to the specified server. .PARAMETER Cache A hashtable used for caching requests. .EXAMPLE PS C:\> Resolve-SchemaGuid -Name contact -Server lds1.contoso.com -Cache $cache Returns the GUID form of the "contact" object class if present. #> [OutputType([string])] [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string] $Name, [Parameter(Mandatory = $true)] [string] $Server, [PSCredential] $Credential, [hashtable] $Cache = @{ } ) begin { $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential } process { if ($Name -as [Guid]) { return $Name } if ($Cache[$Name]) { return $Cache[$Name] } $rootDSE = [adsi]"LDAP://$Server/rootDSE" $targetObjectClassObj = Get-ADObject @ldsParam -SearchBase ($rootdse.schemaNamingContext.value) -LDAPFilter "CN=$Name" -Properties 'schemaIDGUID' if (-not $targetObjectClassObj) { throw "Unknown attribute or object class: $Name" } $bytes = [byte[]]$targetObjectClassObj.schemaIDGUID $guid = [guid]::new($bytes) $Cache[$Name] = "$guid" "$guid" } } function Unprotect-OrganizationalUnit { <# .SYNOPSIS Removes deny rules on OrganizationalUnits. .DESCRIPTION Removes deny rules on OrganizationalUnits. Necessary whenever we want to delete an OU. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Identity The OU to unprotect. Specify the full distinguishedname. .EXAMPLE PS C:\> Unprotect-OrganizationalUnit @ldsParam -Identity $ouPath Removes the deletion protection from the OU specified in $ouPath #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [Parameter(Mandatory = $true)] [string] $Identity ) begin { Update-ADSec $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential } process { $adObject = Get-ADObject @ldsParam -Identity $Identity -Partition $Partition -Properties DistinguishedName $acl = Get-AdsAcl @ldsParam -Path $adObject.DistinguishedName $denyRules = $acl.Access | Where-Object AccessControlType -eq Deny if (-not $denyRules) { return } foreach ($rule in $denyRules) { $null = $acl.RemoveAccessRule($rule) } $acl | Set-AdsAcl @ldsParam -Path $adObject.DistinguishedName } } function Update-ADSec { <# .SYNOPSIS Injects Get-LdsDomain into the ADSec module to overwrite its use of Get-ADDomain. .DESCRIPTION Injects Get-LdsDomain into the ADSec module to overwrite its use of Get-ADDomain. This enables us to override the AD domain connection verification performed by the module. .EXAMPLE PS C:\> Update-ADSec Injects Get-LdsDomain into the ADSec module to overwrite its use of Get-ADDomain. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param () & (Get-Module ADSec) { Set-Alias -Name Get-ADDomain -Value Get-LdsDomain -Scope Script } } function Update-LdsConfiguration { <# .SYNOPSIS Updates the reference to the currently "connected to" LDS instance. .DESCRIPTION Updates the reference to the currently "connected to" LDS instance. This is used by Get-LdsDomain, which is injected into the ADSec module to avoid issues with domain resolution. .PARAMETER LdsServer The server hosting the LDS instance. .PARAMETER LdsPartition The partition of the LDS instance. .EXAMPLE PS C:\> Update-LdsConfiguration -LdsServer lds1.contoso.com -LdsPartition 'DC=Fabrikam,DC=org' Registers lds1.contoso.com as the current server and 'DC=Fabrikam,DC=org' as the current partition. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $LdsServer, [Parameter(Mandatory = $true)] [string] $LdsPartition ) $script:_ldsServer = $LdsServer $script:_ldsPartition = $LdsPartition } function Get-LdsDomain { <# .SYNOPSIS Returns a pseudo-domain object from an LDS instance. .DESCRIPTION Returns a pseudo-domain object from an LDS instance. Use to transparently redirect Get-ADDomain calls. .PARAMETER LdsServer LDS Server instance to use. Reads from cache if provided. .PARAMETER LdsPartition LDS partition to use. Reads from cache if provided. .EXAMPLE PS C:\> Get-LdsDomain Returns the default domain #> param ( [string] $LdsServer = $script:_ldsServer, [string] $LdsPartition = $script:_ldsPartition ) $object = Get-ADObject -LdapFilter '(objectClass=domainDns)' -Server $LdsServer -SearchBase $LdsPartition -Properties * Add-Member -InputObject $object -MemberType NoteProperty -Name NetbiosName -Value $object.Name -Force Add-Member -InputObject $object -MemberType NoteProperty -Name DnsRoot -Value ($object.DistinguishedName -replace "DC=" -replace ",", ".") -Force $groupSid = Get-ADObject -LdapFilter '(&(objectClass=group)(isCriticalSystemObject=TRUE))' -Server $LdsServer -SearchBase $LdsPartition -Properties ObjectSID -ResultSetSize 1 | ForEach-Object ObjectSID Add-Member -InputObject $object -MemberType NoteProperty -Name DomainSID -Value (($groupSid.Value -replace '-\d+$') -as [System.Security.Principal.SecurityIdentifier]) -Force $object } function Import-LdsConfiguration { <# .SYNOPSIS Import a set of configuration files. .DESCRIPTION Import a set of configuration files. Each configuration file must be a psd1, json or (at PS7+) jsonc file. They can be stored any levels of nested folder deep, but they cannot be hidden. Each file shall contain an array of entries and each entry shall have an objectclass plus all the attributes it should have. Note to include everything an object of the given type must have. For each entry, specifying an objectclass is optional: If none is specified, the name of the parent folder is chosen instead. Thus, creating a folder named "user" will have all settings directly within default to the objectclass "user". Supported Object Classes: - AccessRule - Group - GroupMembership - OrganizationalUnit - SchemaAttribute - User Note: Group Memberships and access rules are not really object entities in AD LDS, but are treated the same for configuration purposes. Example Content: > user.psd1 @{ Name = 'Thomas' Path = 'OU=Admin,%DomainDN%' Enabled = $true } .PARAMETER Path Path to a folder containing all configuration sets. .EXAMPLE PS C:\> Import-LdsConfiguration -Path C:\scripts\lds\config Imports all the configuration files under the specified path, no matter how deeply nested. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Path ) $objectClasses = 'AccessRule', 'Group', 'GroupMembership', 'OrganizationalUnit', 'SchemaAttribute', 'User' $extensions = '.json', '.psd1' if ($PSVersionTable.PSVersion.Major -ge 7) {$extensions = '.json', '.jsonc', '.psd1'} foreach ($file in Get-ChildItem -Path $Path -Recurse -File | Where-Object Extension -In $extensions) { $datasets = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Psd1Mode Unsafe $defaultObjectClass = $file.Directory.Name.ToLower() foreach ($dataset in $datasets) { if (-not $dataset.ObjectClass) { $dataset.ObjectClass = $defaultObjectClass } switch ($dataset.ObjectClass) { 'groupmembership' { $identity = "$($dataset.Group)|$($dataset.Member)|$($dataset.Type)" $script:content.groupmembership.$identity = $dataset } 'accessrule' { $identity = "$($dataset.Path)|$($dataset.Identity)|$($dataset.IdentityType)|$($dataset.Rights)|$($dataset.ObjectType)" $script:content.accessrule.$identity = $dataset } 'SchemaAttribute' { $script:content.SchemaAttribute[$dataSet.AttributeID] = $dataSet } default { if ($dataset.ObjectClass -notin $objectClasses) { Write-PSFMessage -Level Warning -Message 'Invalid Object Class: {0} Importing file "{1}". Legal Values: {2}' -StringValues $dataset.ObjectClass, $file.FullName, ($objectClasses -join ', ') -Tag 'badClass' -Target $dataset } $identity = "$($dataset.Name),$($dataset.Path)" if (-not $script:content.$($dataset.ObjectClass)) { $script:content.$($dataset.ObjectClass) = @{ } } $script:content.$($dataset.ObjectClass)[$identity] = $dataset } } } } } function Invoke-LdsConfiguration { <# .SYNOPSIS Applies all currently configured settings to the target AD LDS server. .DESCRIPTION Applies all currently configured settings to the target AD LDS server. Use Import-LdsConfiguration first to load one or more configuration sets. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Options Which part of the configuration to deploy. Defaults to all of them ('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute') .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Invoke-LdsConfiguration -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Applies all currently configured settings to the target AD LDS server. .EXAMPLE PS C:\> Invoke-LdsConfiguration -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' -Options User, Group, OrganizationalUnit Applies all currently configured users, groups and OUs to the target AD LDS server. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [ValidateSet('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute')] [string[]] $Options = @('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute'), [switch] $Delete ) begin { $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential } process { if ($Options -contains 'SchemaAttribute') { Invoke-LdsSchemaAttribute @ldsParam } if ($Options -contains 'OrganizationalUnit') { Invoke-LdsOrganizationalUnit @ldsParam -Delete:$Delete } if ($Options -contains 'Group') { Invoke-LdsGroup @ldsParam -Delete:$Delete } if ($Options -contains 'User') { Invoke-LdsUser @ldsParam -Delete:$Delete } if ($Options -contains 'GroupMembership') { Invoke-LdsGroupMembership @ldsParam -Delete:$Delete } if ($Options -contains 'AccessRule') { Invoke-LdsAccessRule @ldsParam -Delete:$Delete } } } function Reset-LdsAccountPassword { <# .SYNOPSIS Reset the password of any given user account. .DESCRIPTION Reset the password of any given user account. The new password will be pasted to clipboard. .PARAMETER UserName Name of the user to reset. .PARAMETER Server LDS Server to contact. .PARAMETER Partition Partition of the LDS Server to search. .PARAMETER NewPassword The new password to assign. Autogenerates a random password if not specified. .PARAMETER Credential Credential to use for the request .EXAMPLE PS C:\> Reset-LdsAccountPassword -Name svc_whatever -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Resets the password of account 'svc_whatever' #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $UserName, [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [SecureString] $NewPassword = (New-Password -AsSecureString), [PSCredential] $Credential ) $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $userObject = Get-ADUser @ldsParamLight -LDAPFilter "(name=$UserName)" -SearchBase $Partition if (-not $userObject) { Stop-PSFFunction -Cmdlet $PSCmdlet -Message "Unable to find $UserName!" -EnableException $true } if (1 -lt @($userObject).Count) { Stop-PSFFunction -Cmdlet $PSCmdlet -Message "More than one account found for $UserName!`n$($userObject.DistinguishedName -join "`n")" -EnableException $true } Set-ADAccountPassword @ldsParam -NewPassword $NewPassword -Identity $userObject.ObjectGUID if (-not $userObject.Enabled) { Write-PSFMessage -Level Host -Message "Enabling account: $($userObject.Name)" Enable-ADAccount @ldsParam -Identity $userObject.ObjectGuid } Write-PSFMessage -Level Host -Message "Password reset for $($userObject.Name) executed." $null = Read-Host "Press enter to paste the new password to the clipboard." $cred = [PSCredential]::new("whatever", $NewPassword) $cred.GetNetworkCredential().Password | Set-Clipboard Write-PSFMessage -Level Host -Message "Password for $($userObject.Name) has been written to clipboard." } function Reset-LdsConfiguration { <# .SYNOPSIS Removes all registered configuration settings. .DESCRIPTION Removes all registered configuration settings. .EXAMPLE PS C:\> Reset-LdsConfiguration Removes all registered configuration settings. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param () $script:content = @{ user = @{ } group = @{ } organizationalUnit = @{ } groupmembership = @{ } accessrule = @{ } SchemaAttribute = @{ } } } function Test-LdsConfiguration { <# .SYNOPSIS Test all configured settings against the target LDS instance. .DESCRIPTION Test all configured settings against the target LDS instance. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Options Which part of the configuration to test for. Defaults to all of them ('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute') .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsConfiguration -Server lds1.contoso.com -Partition 'DC=Fabrikam,DC=org' Test all configured settings against the 'DC=Fabrikam,DC=org' LDS instance on server lds1.contoso.com. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [ValidateSet('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute')] [string[]] $Options = @('User', 'Group', 'OrganizationalUnit', 'GroupMembership', 'AccessRule', 'SchemaAttribute'), [switch] $Delete ) begin { $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential, Delete } process { if ($Options -contains 'SchemaAttribute' -and -not $Delete) { Test-LdsSchemaAttribute @ldsParam } if ($Options -contains 'OrganizationalUnit') { Test-LdsOrganizationalUnit @ldsParam } if ($Options -contains 'Group') { Test-LdsGroup @ldsParam } if ($Options -contains 'User') { Test-LdsUser @ldsParam } if ($Options -contains 'GroupMembership') { Test-LdsGroupMembership @ldsParam } if ($Options -contains 'AccessRule') { Test-LdsAccessRule @ldsParam } } } function Invoke-LdsAccessRule { <# .SYNOPSIS Applies all the configured access rules. .DESCRIPTION Applies all the configured access rules. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsAccessRule -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Apply all configured access rules to the 'DC=fabrikam,DC=org' partition on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-ADSec Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential } process { if (-not $TestResult) { $TestResult = Test-LdsAccessRule @ldsParam -Partition $Partition -Delete:$Delete } foreach ($testItem in $TestResult | Sort-Object Action -Descending) { switch ($testItem.Action) { 'Add' { $acl = Get-AdsAcl @ldsParam -Path $testItem.Identity $acl.AddAccessRule($testItem.Change.Rule) $acl | Set-AdsAcl @ldsParam -Path $testItem.Identity } 'Remove' { $acl = Get-AdsAcl @ldsParam -Path $testItem.Identity $null = $acl.RemoveAccessRule($testItem.Change.Rule) $acl | Set-AdsAcl @ldsParam -Path $testItem.Identity } } } } } function Test-LdsAccessRule { <# .SYNOPSIS Tests, whether the current access rules match the configured state. .DESCRIPTION Tests, whether the current access rules match the configured state. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsAccessRule -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests, whether the current access rules on lds1.contoso.com match the configured state. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { #region Functions function Resolve-AccessRule { [OutputType([System.DirectoryServices.ActiveDirectoryAccessRule])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] $RuleCfg, [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [hashtable] $SchemaCache = @{ }, [hashtable] $PrincipalCache = @{ }, [string] $DomainSID ) $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential $rights = $script:adrights[$RuleCfg.Rights] # resolve AccessRule settings $inheritanceType = 'None' if ($RuleCfg.Inheritance) { $inheritanceType = $RuleCfg.Inheritance } $objectType = [guid]::Empty $inheritedObjectType = [guid]::Empty if ($RuleCfg.ObjectType) { $objectType = $RuleCfg.ObjectType | Resolve-SchemaGuid @ldsParam -Cache $SchemaCache } if ($RuleCfg.InheritedObjectType) { $inheritedObjectType = $RuleCfg.InheritedObjectType | Resolve-SchemaGuid @ldsParam -Cache $SchemaCache } $type = 'Allow' if ($RuleCfg.Type) { $type = $RuleCfg.Type } $principal = $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] if (-not $principal -and 'SID' -eq $RuleCfg.IdentityType){ $ruleIdentity = $RuleCfg.Identity -replace '%DomainSID%', $DomainSID $sid = $ruleIdentity -as [System.Security.Principal.SecurityIdentifier] if (-not $sid) { throw "Principal is not a legal SID: $($RuleCfg.Identity)!" } $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] = $sid $principal = $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] } elseif (-not $principal) { $principalObject = Get-ADObject @ldsParam -SearchBase $Partition -LDAPFilter "(&(objectClass=$($RuleCfg.IdentityType))(name=$($RuleCfg.Identity)))" -Properties ObjectSID -ErrorAction Stop if (-not $principalObject) { throw "Principal not found: $($RuleCfg.IdentityType) - $($RuleCfg.Identity)" } $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] = $principalObject.ObjectSID $principal = $PrincipalCache["$($RuleCfg.IdentityType):$($RuleCfg.Identity)"] } [System.DirectoryServices.ActiveDirectoryAccessRule]::new( $principal, $rights, $type, $objectType, $inheritanceType, $inheritedObjectType ) } function Compare-AccessRule { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.DirectoryServices.ActiveDirectoryAccessRule[]] $Reference, [Parameter(Mandatory = $true, ValueFromPipeline = $true)] $InputObject, [switch] $NoMatch ) process { if (-not $InputObject) { return } $isMatched = $false foreach ($referenceObject in $Reference) { if ($referenceObject.ActiveDirectoryRights -bxor $InputObject.ActiveDirectoryRights) { continue } if ($referenceObject.InheritanceType -ne $InputObject.InheritanceType) { continue } if ($referenceObject.ObjectType -ne $InputObject.ObjectType) { continue } if ($referenceObject.InheritedObjectType -ne $InputObject.InheritedObjectType) { continue } if ($referenceObject.AccessControlType -ne $InputObject.AccessControlType) { continue } if ("$($referenceObject.IdentityReference)" -ne "$($InputObject.IdentityReference)") { continue } $isMatched = $true break } if ($isMatched -eq -not $NoMatch) { $InputObject } } } function Get-ObjectDefaultRule { [CmdletBinding()] param ( [string] $Path, [hashtable] $LdsParam, [hashtable] $LdsParamLight, $RootDSE, [hashtable] $DefaultPermissions ) $adObject = Get-ADObject @LdsParam -Identity $Path -Properties ObjectClass if ($DefaultPermissions.ContainsKey($adObject.ObjectClass)) { return $DefaultPermissions[$adObject.ObjectClass] } $class = Get-ADObject @ldsParamLight -SearchBase $RootDSE.schemaNamingContext -LDAPFilter "(&(objectClass=classSchema)(ldapDisplayName=$($adObject.ObjectClass)))" -Properties defaultSecurityDescriptor $acl = [System.DirectoryServices.ActiveDirectorySecurity]::new() $acl.SetSecurityDescriptorSddlForm($class.defaultSecurityDescriptor) $DefaultPermissions[$adObject.ObjectClass] = $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) $DefaultPermissions[$adObject.ObjectClass] } #endregion Functions Update-ADSec Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $rootDSE = Get-ADRootDSE @ldsParamLight $domainSID = (Get-ADObject @ldsParamLight -LDAPFilter '(&(objectCategory=group)(name=Administrators))' -SearchBase $ldsParam.Partition -Properties objectSID).ObjectSID.Value -replace '-512$' $principals = @{ } $schemaCache = @{ } $pathCache = @{ } } process { #region Adding foreach ($ruleCfg in $script:content.accessrule.Values) { $resolvedPath = $ruleCfg.Path -replace '%DomainDN%', $Partition try { $rule = Resolve-AccessRule @ldsParam -RuleCfg $ruleCfg -SchemaCache $schemaCache -PrincipalCache $principals -DomainSID $domainSID } catch { Write-PSFMessage -Level Warning -Message "Failed to process rule for $resolvedPath, granting $($ruleCfg.Rights) to $($ruleCfg.Identity)" -ErrorRecord $_ continue } if (-not $pathCache[$resolvedPath]) { $pathCache[$resolvedPath] = @($rule) } else { $pathCache[$resolvedPath] = @($pathCache[$resolvedPath]) + @($rule) } $acl = Get-AdsAcl @ldsParamLight -Path $resolvedPath $currentRules = $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) $matching = $currentRules | Compare-AccessRule -Reference $rule $change = [PSCustomObject]@{ Path = $resolvedPath Name = $ruleCfg.Identity Right = $ruleCfg.Rights Type = $rule.AccessControlType Rule = $rule } Add-Member -InputObject $change -MemberType ScriptMethod -Name ToString -Force -Value { if ('Allow' -eq $this.Type) { '{0} -> {1}' -f $this.Name, $this.Right } else { '{0} != {1}' -f $this.Name, $this.Right } } if ($matching) { if ($Delete) { $change.Rule = $matching New-TestResult -Type AccessRule -Action Remove -Identity $resolvedPath -Configuration $ruleCfg -ADObject $acl -Change $change } continue } if ($Delete) { continue } New-TestResult -Type AccessRule -Action Add -Identity $resolvedPath -Configuration $ruleCfg -ADObject $acl -Change $change } #endregion Adding #region Removing $schemaDefaultPermissions = @{ } $sidToName = @{ } foreach ($adPath in $pathCache.Keys) { $defaultRules = Get-ObjectDefaultRule -Path $adPath -LdsParam $ldsParam -LdsParamLight $ldsParamLight -RootDSE $rootDSE -DefaultPermissions $schemaDefaultPermissions $intendedRules = @($defaultRules) + @($pathCache[$adPath]) | Remove-PSFNull $acl = Get-AdsAcl @ldsParamLight -Path $adPath $currentRules = $acl.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) $surplusRules = $currentRules | Compare-AccessRule -Reference $intendedRules -NoMatch foreach ($surplusRule in $surplusRules) { # Skip OU deletion protection if ('S-1-1-0' -eq $surplusRule.IdentityReference -and 'Deny' -eq $surplusRule.AccessControlType) { continue } if (-not $sidToName[$surplusRule.IdentityReference]) { try { $sidToName[$surplusRule.IdentityReference] = Get-ADObject @ldsParamLight -SearchBase $Partition -LDAPFilter "(objectSID=$($surplusRule.IdentityReference))" -Properties Name } catch { $sidToName[$surplusRule.IdentityReference] = @{ Name = $surplusRule.IdentityReference }} if (-not $sidToName[$surplusRule.IdentityReference]) { $sidToName[$surplusRule.IdentityReference] = @{ Name = $surplusRule.IdentityReference } } } $change = [PSCustomObject]@{ Path = $adPath Name = $sidToName[$surplusRule.IdentityReference].Name Right = $surplusRule.ActiveDirectoryRights Type = $surplusRule.AccessControlType Rule = $surplusRule } Add-Member -InputObject $change -MemberType ScriptMethod -Name ToString -Force -Value { if ('Allow' -eq $this.Type) { '{0} -> {1}' -f $this.Name, $this.Right } else { '{0} != {1}' -f $this.Name, $this.Right } } New-TestResult -Type AccessRule -Action Remove -Identity $adPath -ADObject $acl -Change $change } } #endregion Removing } } function Invoke-LdsGroup { <# .SYNOPSIS Applies all configured groups. .DESCRIPTION Applies all configured groups, creating or updating their settings as needed. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsGroup -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Applies all configured groups to 'DC=fabrikam,DC=org' on the server 'lds1.contoso.com'. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'Path', 'Name', 'GroupScope' } process { if (-not $TestResult) { $TestResult = Test-LdsGroup @ldsParam -Delete:$Delete } foreach ($testItem in $TestResult) { switch ($testItem.Action) { 'Create' { $attributes = $testItem.Configuration | ConvertTo-PSFHashtable -Exclude $systemProperties $newParam = @{ Name = $testItem.Configuration.Name GroupScope = $testItem.Configuration.GroupScope Path = ($testItem.Identity -replace '^.+?,') } if (0 -lt $attributes.Count) { $newParam.OtherAttributes = $attributes } if (-not $newParam.GroupScope) { $newParam.GroupScope = 'DomainLocal' } New-ADGroup @ldsParamLight @newParam } 'Delete' { Remove-ADGroup @ldsParam -Identity $testItem.ADObject.ObjectGUID -Recursive -Confirm:$false } 'Update' { $update = @{ } foreach ($change in $testItem.Change) { $update[$change.Property] = $change.New } Set-ADObject @ldsParam -Identity $testItem.ADObject.ObjectGUID -Replace $update } } } } } function Test-LdsGroup { <# .SYNOPSIS Tests, whether the targeted ad lds server conforms to the group configuration. .DESCRIPTION Tests, whether the targeted ad lds server conforms to the group configuration. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsGroup -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests whether the groups in 'DC=fabrikam,DC=org' on lds1.contoso.com are in their desired state. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $systemProperties = 'ObjectClass', 'Path', 'Name' } process { foreach ($configurationItem in $script:content.group.Values) { $path = 'CN={0},{1}' -f $configurationItem.Name, ($configurationItem.Path -replace '%DomainDN%',$Partition) if ($path -notmatch ',DC=') { $path = $path, $Partition -join ',' } $resultDefaults = @{ Type = 'Group' Identity = $path Configuration = $configurationItem } $failed = $null $adObject = $null try { $adObject = Get-ADGroup @ldsParam -Identity $path -Properties * -ErrorAction SilentlyContinue -ErrorVariable failed } catch { $failed = $_ } if ($failed -and $failed.CategoryInfo.Category -ne 'ObjectNotFound') { foreach ($failure in $failed) { Write-Error $failure } continue } #region Cases # Case: Does not Exist if (-not $adObject) { if ($Delete) { continue } New-TestResult @resultDefaults -Action Create continue } # Case: Exists $resultDefaults.ADObject = $adObject if ($Delete) { New-TestResult @resultDefaults -Action Delete continue } $changes = foreach ($pair in $configurationItem.GetEnumerator()) { if ($pair.Key -in $systemProperties) { continue } if ($pair.Value -ne $adObject.$($pair.Key)) { New-Change -Identity $path -Property $pair.Key -OldValue $adObject.$($pair.Key) -NewValue $pair.Value } } if ($changes) { New-TestResult @resultDefaults -Action Update -Change $changes } #endregion Cases } } } function Invoke-LdsGroupMembership { <# .SYNOPSIS Applies the configuration-defined group memberships. .DESCRIPTION Applies the configuration-defined group memberships. It is generally good idea to apply groups and users first. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsGroupMembership -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Applies the configuration-defined group memberships against 'DC=fabrikam,DC=org' on lds1.contoso.com. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential } process { if (-not $TestResult) { $TestResult = Test-LdsGroupMembership @ldsParam -Delete:$Delete } foreach ($testItem in $TestResult) { switch ($testItem.Action) { 'Update' { foreach ($change in $testItem.Change) { switch ($change.Action) { 'Add' { Add-ADGroupMember @ldsParam -Identity $testItem.ADObject -Members $change.DN } 'Remove' { Remove-ADGroupMember @ldsParam -Identity $testItem.ADObject -Members $change.DN } } } } } } } } function Test-LdsGroupMembership { <# .SYNOPSIS Test whether the group memberships are in their desired state. .DESCRIPTION Test whether the group memberships are in their desired state. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsGroupMembership -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Test whether the group memberships are in their desired state for 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Remap @{ Partition = 'SearchBase' } $members = @{ } $ldsObjects = @{ } } process { foreach ($configurationSets in $script:content.groupmembership.Values | Group-Object { $_.Group }) { Write-PSFMessage -Level Verbose -Message "Processing group memberships of {0}" -StringValues $configurationSets.Name $groupObject = Get-ADGroup @ldsParamLight -LDAPFilter "(name=$($configurationSets.Name))" -Properties * if (-not $groupObject) { Write-PSFMessage -Level Warning -Message "Group not found: {0}! Cannot process members" -StringValues $configurationSets.Name continue } $ldsObjects[$groupObject.DistinguishedName] = $groupObject #region Determine intended members $intendedMembers = foreach ($entry in $configurationSets.Group) { # Read from Cache if ($members["$($entry.Type):$($entry.Member)"]) { $members["$($entry.Type):$($entry.Member)"] continue } # Read from LDS Instance $ldsObject = Get-ADObject @ldsParamLight -LDAPFilter "(&(objectClass=$($entry.Type))(name=$($entry.Member)))" -Properties * # Not Yet Created if (-not $ldsObject) { Write-PSFMessage -Level Warning -Message 'Unable to find {0} {1}, will be unable to add it to group {2}' -StringValues $entry.Type, $entry.Member, $entry.Group continue } $members["$($entry.Type):$($entry.Member)"] = $ldsObject $ldsObjects[$ldsObject.DistinguishedName] = $ldsObject $ldsObject } #endregion Determine intended members #region Determine actual members $actualMembers = foreach ($member in $groupObject.Members) { if ($ldsObjects[$member]) { $ldsObjects[$member] continue } try { $ldsObject = Get-ADObject @ldsParam -Identity $member -Properties * -ErrorAction Stop } catch { Write-PSFMessage -Level Warning -Message "Error resolving member of {0}: {1}" -StringValues $configurationSets.Name, $member -ErrorRecord $_ continue } $ldsObjects[$ldsObject.DistinguishedName] = $ldsObject $ldsObject } #endregion Determine actual members #region Compare and generate changes $toAdd = $intendedMembers | Where-Object DistinguishedName -NotIn $actualMembers.DistinguishedName | ForEach-Object { [PSCustomObject]@{ PSTypename = 'AdLdsTools.Change.GroupMembership' Action = 'Add' Member = $_.Name Type = $_.ObjectClass DN = $_.DistinguishedName Group = $configurationSets.Name } } if ($Delete) { $toAdd = @() } $toRemove = $actualMembers | Where-Object { (-not $Delete -and $_.DistinguishedName -NotIn $intendedMembers.DistinguishedName) -or ($Delete -and $_.DistinguishedName -in $intendedMembers.DistinguishedName) } | ForEach-Object { [PSCustomObject]@{ PSTypename = 'AdLdsTools.Change.GroupMembership' Action = 'Remove' Member = $_.Name Type = $_.ObjectClass DN = $_.DistinguishedName Group = $configurationSets.Name } } $changes = @($toAdd) + @($toRemove) | Remove-PSFNull | Add-Member -MemberType ScriptMethod -Name ToString -Value { '{0} -> {1}' -f $this.Action, $this.Member } -Force -PassThru #endregion Compare and generate changes if ($changes) { New-TestResult -Type GroupMemberShip -Action Update -Identity $groupObject.Name -ADObject $groupObject -Configuration $configurationSets -Change $changes } } } } function Invoke-LdsOrganizationalUnit { <# .SYNOPSIS Creates the desired organizational units. .DESCRIPTION Creates the desired organizational units. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsOrganizationalUnit -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Creates the desired organizational units in 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'Path', 'Name' $filter = { # Delete actions should go from innermost to top-level # Create actions should go from top-level to most nested if ($_.Action -eq 'Delete') { $_.Identity.Length * -1 } else { $_.Identity.Length } } } process { if (-not $TestResult) { $TestResult = Test-LdsOrganizationalUnit @ldsParam -Delete:$Delete } foreach ($testItem in $TestResult | Sort-Object Action, $filter) { switch ($testItem.Action) { 'Create' { $attributes = $testItem.Configuration | ConvertTo-PSFHashtable -Exclude $systemProperties $newParam = @{ Name = $testItem.Configuration.Name Path = ($testItem.Identity -replace '^.+?,') } if (0 -lt $attributes.Count) { $newParam.OtherAttributes = $attributes } New-ADOrganizationalUnit @ldsParamLight @newParam } 'Delete' { Unprotect-OrganizationalUnit @ldsParam -Identity $testItem.ADObject.ObjectGUID Remove-ADOrganizationalUnit @ldsParam -Identity $testItem.ADObject.ObjectGUID -Recursive -Confirm:$false } 'Update' { $update = @{ } foreach ($change in $testItem.Change) { $update[$change.Property] = $change.New } Set-ADObject @ldsParam -Identity $testItem.ADObject.ObjectGUID -Replace $update } } } } } function Test-LdsOrganizationalUnit { <# .SYNOPSIS Tests, whether the desired organizational units exist. .DESCRIPTION Tests, whether the desired organizational units exist. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsOrganizationalUnit -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests, whether the desired organizational units exist in 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $systemProperties = 'ObjectClass', 'Path', 'Name' } process { foreach ($configurationItem in $script:content.organizationalUnit.Values) { $path = 'OU={0},{1}' -f $configurationItem.Name, ($configurationItem.Path -replace '%DomainDN%',$Partition) if ($path -notmatch ',DC=') { $path = $path, $Partition -join ',' } $resultDefaults = @{ Type = 'OrganizationalUnit' Identity = $path Configuration = $configurationItem } $failed = $null $adObject = $null try { $adObject = Get-ADOrganizationalUnit @ldsParam -Identity $path -Properties * -ErrorAction SilentlyContinue -ErrorVariable failed } catch { $failed = $_ } if ($failed -and $failed.CategoryInfo.Category -ne 'ObjectNotFound') { foreach ($failure in $failed) { Write-Error $failure } continue } #region Cases # Case: Does not Exist if (-not $adObject) { if ($Delete) { continue } New-TestResult @resultDefaults -Action Create continue } # Case: Exists $resultDefaults.ADObject = $adObject if ($Delete) { New-TestResult @resultDefaults -Action Delete continue } $changes = foreach ($pair in $configurationItem.GetEnumerator()) { if ($pair.Key -in $systemProperties) { continue } if ($pair.Value -ne $adObject.$($pair.Key)) { New-Change -Identity $path -Property $pair.Key -OldValue $adObject.$($pair.Key) -NewValue $pair.Value } } if ($changes) { New-TestResult @resultDefaults -Action Update -Change $changes } #endregion Cases } } } function Invoke-LdsSchemaAttribute { <# .SYNOPSIS Applies the intended schema attributes. .DESCRIPTION Applies the intended schema attributes. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsSchemaAttribute -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Applies the intended schema attributes to 'DC=fabrikam,DC=org' on lds1.contoso.com. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'AttributeID', 'IsDeleted', 'Optional', 'MayContain' $rootDSE = Get-ADRootDSE @ldsParamLight } process { if (-not $TestResult) { $TestResult = Test-LdsSchemaAttribute @ldsParam } $testResultsSorted = $TestResult | Sort-Object { switch ($_.Action) { Create { 1 } Delete { 2 } Update { 3 } Add { 4 } Remove { 5 } Default { 6 } } } foreach ($testItem in $testResultsSorted) { switch ($testItem.Action) { 'Create' { $attributes = $testItem.Configuration | ConvertTo-PSFHashtable -Exclude $systemProperties $attributes.AttributeID = $testItem.Configuration.AttributeID $name = $testItem.Configuration.Name if (-not $name) { $name = $testItem.Configuration.AdminDisplayName } New-ADObject @ldsParamLight -Type attributeSchema -Name $name -Path $rootDSE.schemaNamingContext -OtherAttributes $attributes } 'Delete' { $testItem.ADObject | Set-ADObject @ldsParamLight -Replace @{ IsDeleted = $true } } 'Update' { $replacements = @{ } foreach ($change in $testItem.Change) { $replacements[$change.Property] = $change.New } $testItem.ADObject | Set-ADObject @ldsParamLight -Replace $replacements } 'Add' { $testItem.Change.Data | Set-ADObject @ldsParamLight -Add @{ mayContain = $testItem.ADObject.lDAPDisplayName } } 'Remove' { $testItem.Change.Data | Set-ADObject @ldsParamLight -Remove @{ mayContain = $testItem.Identity } } 'Rename' { $testItem.ADObject | Rename-ADObject @ldsParamLight -NewName @($testItem.Change.New)[0] } } } } } function Test-LdsSchemaAttribute { <# .SYNOPSIS Tests, whether the intended schema attributes have been applied. .DESCRIPTION Tests, whether the intended schema attributes have been applied. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .EXAMPLE PS C:\> Test-LdsSchemaAttribute -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests, whether the intended schema attributes have been applied to 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'AttributeID', 'IsDeleted', 'Optional', 'MayContain' $rootDSE = Get-ADRootDSE @ldsParamLight $classes = Get-ADObject @ldsParamLight -SearchBase $rootDSE.schemaNamingContext -LDAPFilter '(objectClass=classSchema)' -Properties mayContain, adminDisplayName } process { foreach ($schemaSetting in $script:content.SchemaAttribute.Values) { $schemaObject = $null $schemaObject = Get-ADObject @ldsParamLight -LDAPFilter "(attributeID=$($schemaSetting.AttributeID))" -SearchBase $rootDSE.schemaNamingContext -ErrorAction Ignore -Properties * $resultDefaults = @{ Type = 'SchemaAttribute' Identity = $schemaSetting.AdminDisplayName Configuration = $schemaSetting } if (-not $schemaObject) { # If we already want to disable the attribute, no need to create it if ($schemaSetting.IsDeleted) { continue } if ($schemaSetting.Optional) { continue } New-TestResult @resultDefaults -Action Create foreach ($entry in $schemaSetting.MayContain) { if ($classes.AdminDisplayName -notcontains $entry) { continue } New-TestResult @resultDefaults -Action Add -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property MayContain -NewValue $entry -Data ($classes | Where-Object AdminDisplayName -EQ $entry) ) } continue } $resultDefaults.ADObject = $schemaObject if ($schemaSetting.IsDeleted -and -not $schemaObject.isDeleted) { New-TestResult @resultDefaults -Action Delete -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property IsDeleted -OldValue $false -NewValue $true ) } if ($schemaSetting.Name -and $schemaSetting.Name -cne $schemaObject.Name) { New-TestResult @resultDefaults -Action Rename -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property Name -OldValue $schemaObject.Name -NewValue $schemaSetting.Name ) } $changes = foreach ($pair in $schemaSetting.GetEnumerator()) { if ($pair.Key -in $systemProperties) { continue } if ($pair.Value -cne $schemaObject.$($pair.Key)) { New-Change -Identity $schemaSetting.AdminDisplayName -Property $pair.Key -OldValue $schemaObject.$($pair.Key) -NewValue $pair.Value } } if ($changes) { New-TestResult @resultDefaults -Action Update -Change $changes } $mayBeContainedIn = $schemaSetting.MayContain if ($schemaSetting.IsDeleted) { $mayBeContainedIn = @() } $classesMatch = $classes | Where-Object mayContain -Contains $schemaObject.LdapDisplayName foreach ($matchingclass in $classesMatch) { if ($matchingclass.AdminDisplayName -in $mayBeContainedIn) { continue } New-TestResult @resultDefaults -Action Remove -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property MayContain -OldValue $matchingclass.AdminDisplayName -DisplayStyle RemoveValue -Data $matchingClass ) } foreach ($allowedClass in $mayBeContainedIn) { if ($classesMatch.AdminDisplayName -contains $allowedClass) { continue } New-TestResult @resultDefaults -Action Add -Change @( New-Change -Identity $schemaSetting.AdminDisplayName -Property MayContain -NewValue $allowedClass -Data ($classes | Where-Object AdminDisplayName -EQ $allowedClass) ) } } } } function Invoke-LdsUser { <# .SYNOPSIS Creates the intended user objects. .DESCRIPTION Creates the intended user objects. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsUser -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Creates the intended user objects for 'DC=fabrikam,DC=org' on lds1.contoso.com. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'Path', 'Name', 'Enabled' } process { if (-not $TestResult) { $TestResult = Test-LdsUser @ldsParam -Delete:$Delete } foreach ($testItem in $TestResult) { switch ($testItem.Action) { 'Create' { $attributes = $testItem.Configuration | ConvertTo-PSFHashtable -Exclude $systemProperties $newParam = @{ Name = $testItem.Configuration.Name Path = ($testItem.Identity -replace '^.+?,') OtherAttributes = $attributes } if ($testItem.Configuration.Enabled) { $newParam += @{ Enabled = $true AccountPassword = New-Password -AsSecureString } } if (0 -eq $newParam.OtherAttributes.Count) { $newParam.Remove('OtherAttributes') } New-ADUser @ldsParamLight @newParam } 'Delete' { Remove-ADUser @ldsParam -Identity $testItem.ADObject.ObjectGUID -Recursive -Confirm:$false } 'Update' { $update = @{ } foreach ($change in $testItem.Change) { $update[$change.Property] = $change.New } Set-ADObject @ldsParam -Identity $testItem.ADObject.ObjectGUID -Replace $update } } } } } function Test-LdsUser { <# .SYNOPSIS Tests, whether the desired users have already been created. .DESCRIPTION Tests, whether the desired users have already been created. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsUser -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests, whether the desired users have already been created for 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $systemProperties = 'ObjectClass', 'Path', 'Name', 'Enabled' } process { foreach ($configurationItem in $script:content.user.Values) { if ($configurationItem.SamAccountName -and -not $configurationItem.Name) { $configurationItem.Name = $configurationItem.SamAccountName } $path = 'CN={0},{1}' -f $configurationItem.Name, ($configurationItem.Path -replace '%DomainDN%',$Partition) if ($path -notmatch ',DC=') { $path = $path, $Partition -join ',' } $resultDefaults = @{ Type = 'User' Identity = $path Configuration = $configurationItem } $failed = $null $adObject = $null try { $adObject = Get-ADUser @ldsParam -Identity $path -Properties * -ErrorAction SilentlyContinue -ErrorVariable failed } catch { $failed = $_ } if ($failed -and $failed.CategoryInfo.Category -ne 'ObjectNotFound') { foreach ($failure in $failed) { Write-Error $failure } continue } #region Cases # Case: Does not Exist if (-not $adObject) { if ($Delete) { continue } New-TestResult @resultDefaults -Action Create continue } # Case: Exists $resultDefaults.ADObject = $adObject if ($Delete) { New-TestResult @resultDefaults -Action Delete continue } $changes = foreach ($pair in $configurationItem.GetEnumerator()) { if ($pair.Key -in $systemProperties) { continue } if ($pair.Value -ne $adObject.$($pair.Key)) { New-Change -Identity $path -Property $pair.Key -OldValue $adObject.$($pair.Key) -NewValue $pair.Value } } if ($changes) { New-TestResult @resultDefaults -Action Update -Change $changes } #endregion Cases } } } <# 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 'ADLDSMF' -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 'ADLDSMF' -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 'ADLDSMF' -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 'ADLDSMF.ScriptBlockName' -Scriptblock { } #> <# # Example: Register-PSFTeppScriptblock -Name "ADLDSMF.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #> <# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name ADLDSMF.alcohol #> $script:content = @{ user = @{ } group = @{ } organizationalUnit = @{ } groupmembership = @{ } accessrule = @{ } SchemaAttribute = @{ } } $script:adrights = @{ 'FullControl' = @( [System.DirectoryServices.ActiveDirectoryRights]::GenericAll ) 'Enumerate' = @( [System.DirectoryServices.ActiveDirectoryRights]::ListChildren [System.DirectoryServices.ActiveDirectoryRights]::ListObject ) 'Read' = @( [System.DirectoryServices.ActiveDirectoryRights]::GenericRead ) 'EditObject' = @( [System.DirectoryServices.ActiveDirectoryRights]::Delete [System.DirectoryServices.ActiveDirectoryRights]::ReadProperty [System.DirectoryServices.ActiveDirectoryRights]::WriteProperty ) 'ManageChildren' = @( [System.DirectoryServices.ActiveDirectoryRights]::CreateChild [System.DirectoryServices.ActiveDirectoryRights]::DeleteChild ) 'Extended' = @( [System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight ) } # Make ACL work again $null = Get-Acl -Path . -ErrorAction Ignore # Disable AD Connection Check Set-PSFConfig -FullName 'ADSec.Connect.NoAssertion' -Value $true # Load config if present if (Test-Path -Path "$script:ModuleRoot\Config") { Import-LdsConfiguration -Path "$script:ModuleRoot\Config" } New-PSFLicense -Product 'ADLDSMF' -Manufacturer 'frweinma' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2023-12-11") -Text @" Copyright (c) 2023 frweinma 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
Reset-LdsAccountPassword.ps1
ADLDSMF-1.0.0
function Reset-LdsAccountPassword { <# .SYNOPSIS Reset the password of any given user account. .DESCRIPTION Reset the password of any given user account. The new password will be pasted to clipboard. .PARAMETER UserName Name of the user to reset. .PARAMETER Server LDS Server to contact. .PARAMETER Partition Partition of the LDS Server to search. .PARAMETER NewPassword The new password to assign. Autogenerates a random password if not specified. .PARAMETER Credential Credential to use for the request .EXAMPLE PS C:\> Reset-LdsAccountPassword -Name svc_whatever -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Resets the password of account 'svc_whatever' #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $UserName, [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [SecureString] $NewPassword = (New-Password -AsSecureString), [PSCredential] $Credential ) $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $userObject = Get-ADUser @ldsParamLight -LDAPFilter "(name=$UserName)" -SearchBase $Partition if (-not $userObject) { Stop-PSFFunction -Cmdlet $PSCmdlet -Message "Unable to find $UserName!" -EnableException $true } if (1 -lt @($userObject).Count) { Stop-PSFFunction -Cmdlet $PSCmdlet -Message "More than one account found for $UserName!`n$($userObject.DistinguishedName -join "`n")" -EnableException $true } Set-ADAccountPassword @ldsParam -NewPassword $NewPassword -Identity $userObject.ObjectGUID if (-not $userObject.Enabled) { Write-PSFMessage -Level Host -Message "Enabling account: $($userObject.Name)" Enable-ADAccount @ldsParam -Identity $userObject.ObjectGuid } Write-PSFMessage -Level Host -Message "Password reset for $($userObject.Name) executed." $null = Read-Host "Press enter to paste the new password to the clipboard." $cred = [PSCredential]::new("whatever", $NewPassword) $cred.GetNetworkCredential().Password | Set-Clipboard Write-PSFMessage -Level Host -Message "Password for $($userObject.Name) has been written to clipboard." }
Test-LdsGroup.ps1
ADLDSMF-1.0.0
function Test-LdsGroup { <# .SYNOPSIS Tests, whether the targeted ad lds server conforms to the group configuration. .DESCRIPTION Tests, whether the targeted ad lds server conforms to the group configuration. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsGroup -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests whether the groups in 'DC=fabrikam,DC=org' on lds1.contoso.com are in their desired state. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $systemProperties = 'ObjectClass', 'Path', 'Name' } process { foreach ($configurationItem in $script:content.group.Values) { $path = 'CN={0},{1}' -f $configurationItem.Name, ($configurationItem.Path -replace '%DomainDN%',$Partition) if ($path -notmatch ',DC=') { $path = $path, $Partition -join ',' } $resultDefaults = @{ Type = 'Group' Identity = $path Configuration = $configurationItem } $failed = $null $adObject = $null try { $adObject = Get-ADGroup @ldsParam -Identity $path -Properties * -ErrorAction SilentlyContinue -ErrorVariable failed } catch { $failed = $_ } if ($failed -and $failed.CategoryInfo.Category -ne 'ObjectNotFound') { foreach ($failure in $failed) { Write-Error $failure } continue } #region Cases # Case: Does not Exist if (-not $adObject) { if ($Delete) { continue } New-TestResult @resultDefaults -Action Create continue } # Case: Exists $resultDefaults.ADObject = $adObject if ($Delete) { New-TestResult @resultDefaults -Action Delete continue } $changes = foreach ($pair in $configurationItem.GetEnumerator()) { if ($pair.Key -in $systemProperties) { continue } if ($pair.Value -ne $adObject.$($pair.Key)) { New-Change -Identity $path -Property $pair.Key -OldValue $adObject.$($pair.Key) -NewValue $pair.Value } } if ($changes) { New-TestResult @resultDefaults -Action Update -Change $changes } #endregion Cases } } }
Invoke-LdsUser.ps1
ADLDSMF-1.0.0
function Invoke-LdsUser { <# .SYNOPSIS Creates the intended user objects. .DESCRIPTION Creates the intended user objects. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsUser -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Creates the intended user objects for 'DC=fabrikam,DC=org' on lds1.contoso.com. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'Path', 'Name', 'Enabled' } process { if (-not $TestResult) { $TestResult = Test-LdsUser @ldsParam -Delete:$Delete } foreach ($testItem in $TestResult) { switch ($testItem.Action) { 'Create' { $attributes = $testItem.Configuration | ConvertTo-PSFHashtable -Exclude $systemProperties $newParam = @{ Name = $testItem.Configuration.Name Path = ($testItem.Identity -replace '^.+?,') OtherAttributes = $attributes } if ($testItem.Configuration.Enabled) { $newParam += @{ Enabled = $true AccountPassword = New-Password -AsSecureString } } if (0 -eq $newParam.OtherAttributes.Count) { $newParam.Remove('OtherAttributes') } New-ADUser @ldsParamLight @newParam } 'Delete' { Remove-ADUser @ldsParam -Identity $testItem.ADObject.ObjectGUID -Recursive -Confirm:$false } 'Update' { $update = @{ } foreach ($change in $testItem.Change) { $update[$change.Property] = $change.New } Set-ADObject @ldsParam -Identity $testItem.ADObject.ObjectGUID -Replace $update } } } } }
Test-LdsUser.ps1
ADLDSMF-1.0.0
function Test-LdsUser { <# .SYNOPSIS Tests, whether the desired users have already been created. .DESCRIPTION Tests, whether the desired users have already been created. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .EXAMPLE PS C:\> Test-LdsUser -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Tests, whether the desired users have already been created for 'DC=fabrikam,DC=org' on lds1.contoso.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $systemProperties = 'ObjectClass', 'Path', 'Name', 'Enabled' } process { foreach ($configurationItem in $script:content.user.Values) { if ($configurationItem.SamAccountName -and -not $configurationItem.Name) { $configurationItem.Name = $configurationItem.SamAccountName } $path = 'CN={0},{1}' -f $configurationItem.Name, ($configurationItem.Path -replace '%DomainDN%',$Partition) if ($path -notmatch ',DC=') { $path = $path, $Partition -join ',' } $resultDefaults = @{ Type = 'User' Identity = $path Configuration = $configurationItem } $failed = $null $adObject = $null try { $adObject = Get-ADUser @ldsParam -Identity $path -Properties * -ErrorAction SilentlyContinue -ErrorVariable failed } catch { $failed = $_ } if ($failed -and $failed.CategoryInfo.Category -ne 'ObjectNotFound') { foreach ($failure in $failed) { Write-Error $failure } continue } #region Cases # Case: Does not Exist if (-not $adObject) { if ($Delete) { continue } New-TestResult @resultDefaults -Action Create continue } # Case: Exists $resultDefaults.ADObject = $adObject if ($Delete) { New-TestResult @resultDefaults -Action Delete continue } $changes = foreach ($pair in $configurationItem.GetEnumerator()) { if ($pair.Key -in $systemProperties) { continue } if ($pair.Value -ne $adObject.$($pair.Key)) { New-Change -Identity $path -Property $pair.Key -OldValue $adObject.$($pair.Key) -NewValue $pair.Value } } if ($changes) { New-TestResult @resultDefaults -Action Update -Change $changes } #endregion Cases } } }
Invoke-LdsGroupMembership.ps1
ADLDSMF-1.0.0
function Invoke-LdsGroupMembership { <# .SYNOPSIS Applies the configuration-defined group memberships. .DESCRIPTION Applies the configuration-defined group memberships. It is generally good idea to apply groups and users first. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsGroupMembership -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Applies the configuration-defined group memberships against 'DC=fabrikam,DC=org' on lds1.contoso.com. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential } process { if (-not $TestResult) { $TestResult = Test-LdsGroupMembership @ldsParam -Delete:$Delete } foreach ($testItem in $TestResult) { switch ($testItem.Action) { 'Update' { foreach ($change in $testItem.Change) { switch ($change.Action) { 'Add' { Add-ADGroupMember @ldsParam -Identity $testItem.ADObject -Members $change.DN } 'Remove' { Remove-ADGroupMember @ldsParam -Identity $testItem.ADObject -Members $change.DN } } } } } } } }
Help.Exceptions.ps1
ADLDSMF-1.0.0
# List of functions that should be ignored $global:FunctionHelpTestExceptions = @( ) <# List of arrayed enumerations. These need to be treated differently. Add full name. Example: "Sqlcollaborative.Dbatools.Connection.ManagementConnectionType[]" #> $global:HelpTestEnumeratedArrays = @( ) <# Some types on parameters just fail their validation no matter what. For those it becomes possible to skip them, by adding them to this hashtable. Add by following this convention: <command name> = @(<list of parameter names>) Example: "Get-DbaCmObject" = @("DoNotUse") #> $global:HelpTestSkipParameterType = @{ }
New-Password.ps1
ADLDSMF-1.0.0
function New-Password { <# .SYNOPSIS Generate a new, complex password. .DESCRIPTION Generate a new, complex password. .PARAMETER Length The length of the password calculated. Defaults to 32 .PARAMETER AsSecureString Returns the password as secure string. .EXAMPLE PS C:\> New-Password Generates a new 32v character password. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] [CmdletBinding()] Param ( [int] $Length = 32, [switch] $AsSecureString ) begin { $characters = @{ 0 = @('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z') 1 = @('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') 2 = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 3 = @('#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@') 4 = @('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z') 5 = @('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') 6 = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 7 = @('#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@') } } process { $letters = foreach ($number in (5..$Length)) { $characters[(($number % 4) + (0..4 | Get-Random))] | Get-Random } 0, 1, 2, 3 | ForEach-Object { $letters += $characters[$_] | Get-Random } $letters = $letters | Sort-Object { Get-Random } if ($AsSecureString) { $letters -join "" | ConvertTo-SecureString -AsPlainText -Force } else { $letters -join "" } } }
Invoke-LdsGroup.ps1
ADLDSMF-1.0.0
function Invoke-LdsGroup { <# .SYNOPSIS Applies all configured groups. .DESCRIPTION Applies all configured groups, creating or updating their settings as needed. .PARAMETER Server The LDS Server to target. .PARAMETER Partition The Partition on the LDS Server to target. .PARAMETER Credential Credentials to use for the operation. .PARAMETER Delete Undo everything defined in configuration. Allows rolling back after deployment. .PARAMETER TestResult Result objects of the associated Test-Command. Allows cherry-picking which change to apply. If not specified, it will a test and apply all test results instead. .EXAMPLE PS C:\> Invoke-LdsGroup -Server lds1.contoso.com -Partition 'DC=fabrikam,DC=org' Applies all configured groups to 'DC=fabrikam,DC=org' on the server 'lds1.contoso.com'. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Server, [Parameter(Mandatory = $true)] [string] $Partition, [PSCredential] $Credential, [switch] $Delete, [Parameter(ValueFromPipeline = $true)] $TestResult ) begin { Update-LdsConfiguration -LdsServer $Server -LdsPartition $Partition $ldsParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Partition, Credential $ldsParamLight = $ldsParam | ConvertTo-PSFHashtable -Exclude Partition $systemProperties = 'ObjectClass', 'Path', 'Name', 'GroupScope' } process { if (-not $TestResult) { $TestResult = Test-LdsGroup @ldsParam -Delete:$Delete } foreach ($testItem in $TestResult) { switch ($testItem.Action) { 'Create' { $attributes = $testItem.Configuration | ConvertTo-PSFHashtable -Exclude $systemProperties $newParam = @{ Name = $testItem.Configuration.Name GroupScope = $testItem.Configuration.GroupScope Path = ($testItem.Identity -replace '^.+?,') } if (0 -lt $attributes.Count) { $newParam.OtherAttributes = $attributes } if (-not $newParam.GroupScope) { $newParam.GroupScope = 'DomainLocal' } New-ADGroup @ldsParamLight @newParam } 'Delete' { Remove-ADGroup @ldsParam -Identity $testItem.ADObject.ObjectGUID -Recursive -Confirm:$false } 'Update' { $update = @{ } foreach ($change in $testItem.Change) { $update[$change.Property] = $change.New } Set-ADObject @ldsParam -Identity $testItem.ADObject.ObjectGUID -Replace $update } } } } }
variables.ps1
ADLDSMF-1.0.0
$script:content = @{ user = @{ } group = @{ } organizationalUnit = @{ } groupmembership = @{ } accessrule = @{ } SchemaAttribute = @{ } } $script:adrights = @{ 'FullControl' = @( [System.DirectoryServices.ActiveDirectoryRights]::GenericAll ) 'Enumerate' = @( [System.DirectoryServices.ActiveDirectoryRights]::ListChildren [System.DirectoryServices.ActiveDirectoryRights]::ListObject ) 'Read' = @( [System.DirectoryServices.ActiveDirectoryRights]::GenericRead ) 'EditObject' = @( [System.DirectoryServices.ActiveDirectoryRights]::Delete [System.DirectoryServices.ActiveDirectoryRights]::ReadProperty [System.DirectoryServices.ActiveDirectoryRights]::WriteProperty ) 'ManageChildren' = @( [System.DirectoryServices.ActiveDirectoryRights]::CreateChild [System.DirectoryServices.ActiveDirectoryRights]::DeleteChild ) 'Extended' = @( [System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight ) }
ADLSCmdlets.psm1
ADLSCmdlets-23.0.8839.1
Set-StrictMode -Version Latest $PSModule = $ExecutionContext.SessionState.Module $PSModuleRoot = $PSModule.ModuleBase $binaryModuleManifestFile = 'ADLSCmdlets.psd1' $binaryModuleRootPath = $PSModuleRoot if (($PSVersionTable.Keys -contains "PSEdition") -and ($PSVersionTable.PSEdition -ne 'Desktop')) { $binaryModuleRootPath = Join-Path -Path $PSModuleRoot -ChildPath 'lib/netstandard2.1' } else { $binaryModuleRootPath = Join-Path -Path $PSModuleRoot -ChildPath 'lib/net40' } $binaryModulePath = Join-Path -Path $binaryModuleRootPath -ChildPath $binaryModuleManifestFile $binaryModule = Import-Module -Name $binaryModulePath -PassThru $PSModule.OnRemove = { Remove-Module -ModuleInfo $binaryModule } # SIG # Begin signature block # MIIt2gYJKoZIhvcNAQcCoIItyzCCLccCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDF3yqTkIdr064F # pLjLKbKCzc4teDPyNw8I5nNXacQoJKCCEzcwggbuMIIE1qADAgECAhAFHswF2GND # 2Gbwxke9mqRRMA0GCSqGSIb3DQEBCwUAMGkxCzAJBgNVBAYTAlVTMRcwFQYDVQQK # Ew5EaWdpQ2VydCwgSW5jLjFBMD8GA1UEAxM4RGlnaUNlcnQgVHJ1c3RlZCBHNCBD # b2RlIFNpZ25pbmcgUlNBNDA5NiBTSEEzODQgMjAyMSBDQTEwHhcNMjMwOTE5MDAw # MDAwWhcNMjYwOTE4MjM1OTU5WjB2MQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9y # dGggQ2Fyb2xpbmExFDASBgNVBAcTC0NoYXBlbCBIaWxsMRswGQYDVQQKExJDRGF0 # YSBTb2Z0d2FyZSBJTkMxGzAZBgNVBAMTEkNEYXRhIFNvZnR3YXJlIElOQzCCAaIw # DQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBAMUVrZoPq04XEojG1qOxj5zghTxb # l+9VciyBZ92PwckhMQHZ4DwXBthNyHcJHp8OvHopcbS4sYjXWE3TvIas3SzGjZRV # 8s9pcCY/Y7NWuaQuZLjwDeEQZpnRFfkH0otrT2SG+bk7DlZF4wCIMCkdBDSx/U1n # Grxa2wkbQTyfL+Q19ZQLGSxLBQWMw5LYyCBf0ZaFyMl4Z/MKml/Vevcg8f/4zbNP # VreSNH2kTvLbwnOup0mTJ+7eyDFSIM4P+Tv2XtHuEPkcetchRS2P+6IhsOzxQqWP # StWUcNtcSsZxDGmiguaBXVNoKFKRfOBrtqronLrL39YWcv5M40YHugBJK31C94qq # /IRjcPo/tgMyu5tgsdCFvebwYk/48g3MIWkWkyYALLY6Ukj6ME1/iU2NJfA8poRE # +A/TUbR0Y0kz+WjIP80K9BDjpVIt8O2PXaKyIrikXrnYiJOBoeVLlpiaJuIAHgqN # XU4pDx5t72xErOKHX6O07bi1/LKjyhPHcYyeGQIDAQABo4ICAzCCAf8wHwYDVR0j # BBgwFoAUaDfg67Y7+F8Rhvv+YXsIiGX0TkIwHQYDVR0OBBYEFBZqyu6J1RSziUcT # azH9+2qAl3qZMD4GA1UdIAQ3MDUwMwYGZ4EMAQQBMCkwJwYIKwYBBQUHAgEWG2h0 # dHA6Ly93d3cuZGlnaWNlcnQuY29tL0NQUzAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0l # BAwwCgYIKwYBBQUHAwMwgbUGA1UdHwSBrTCBqjBToFGgT4ZNaHR0cDovL2NybDMu # ZGlnaWNlcnQuY29tL0RpZ2lDZXJ0VHJ1c3RlZEc0Q29kZVNpZ25pbmdSU0E0MDk2 # U0hBMzg0MjAyMUNBMS5jcmwwU6BRoE+GTWh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNv # bS9EaWdpQ2VydFRydXN0ZWRHNENvZGVTaWduaW5nUlNBNDA5NlNIQTM4NDIwMjFD # QTEuY3JsMIGUBggrBgEFBQcBAQSBhzCBhDAkBggrBgEFBQcwAYYYaHR0cDovL29j # c3AuZGlnaWNlcnQuY29tMFwGCCsGAQUFBzAChlBodHRwOi8vY2FjZXJ0cy5kaWdp # Y2VydC5jb20vRGlnaUNlcnRUcnVzdGVkRzRDb2RlU2lnbmluZ1JTQTQwOTZTSEEz # ODQyMDIxQ0ExLmNydDAJBgNVHRMEAjAAMA0GCSqGSIb3DQEBCwUAA4ICAQBn7/7q # LpImnfij/84k/7dFu7aFjKkqWIJ8VRvzPsJ1938MIGnvWyhdD6yzPCtFyDMFccP0 # Y33wG4GeOR1+mTTgexK5mQS1UyCFNAcUaeMgrJr6OJzYVSkdxxUtQXefbr2WwK65 # Nb6r2SOXS6L8iN+xKuXhAetNPYwcetxy8ojL4rffzNgeIqPG9Q9Lee7rADPjyAIC # JbmbCquafgQQxHkylx36yDkVLk7vJ0sRHHnE1/1AOHzIbRbAz5qH6AWbBa3DRCJD # E3BvryoyxpfGcOLq8Qoe7bsSs1xh/5V81ykukGuCz425/mF5CeSPJw/Xa2lekX++ # Jqr82BpX1aa9m1Biux2GO8eNeKYnT8uYxddMWaM9bCFsMuCXfXprRjdPdRSBGV8/ # e3EtWSCcvSa1KInur4aC7f+sRzyN3+hh/9QxgubIrb6GoOU05zsxKcYDPdcfPieX # j7VJ4uVoNNOGPVJh+akAyT6ZfLtUYH25VUSkWJ6m2nBNMaLNetOXORNauuGTRXCJ # /weQTXz988ISNK72u9yLUfrd+FMfT8Dy/0AeVrCXC+GRwjAl63XwSNIPCUB62pzC # W1u6FvqFFpagxRpMd3AePnbPx2kfRDMezIMbFB0W8PF22XSshj+BRQvqW4G7uLV/ # +bCmCOjHPsN9QINbviaLCn1sRDpS7BvzAlJrLTCCBrAwggSYoAMCAQICEAitQLJg # 0pxMn17Nqb2TrtkwDQYJKoZIhvcNAQEMBQAwYjELMAkGA1UEBhMCVVMxFTATBgNV # BAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8G # A1UEAxMYRGlnaUNlcnQgVHJ1c3RlZCBSb290IEc0MB4XDTIxMDQyOTAwMDAwMFoX # DTM2MDQyODIzNTk1OVowaTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0 # LCBJbmMuMUEwPwYDVQQDEzhEaWdpQ2VydCBUcnVzdGVkIEc0IENvZGUgU2lnbmlu # ZyBSU0E0MDk2IFNIQTM4NCAyMDIxIENBMTCCAiIwDQYJKoZIhvcNAQEBBQADggIP # ADCCAgoCggIBANW0L0LQKK14t13VOVkbsYhC9TOM6z2Bl3DFu8SFJjCfpI5o2Fz1 # 6zQkB+FLT9N4Q/QX1x7a+dLVZxpSTw6hV/yImcGRzIEDPk1wJGSzjeIIfTR9TIBX # EmtDmpnyxTsf8u/LR1oTpkyzASAl8xDTi7L7CPCK4J0JwGWn+piASTWHPVEZ6JAh # eEUuoZ8s4RjCGszF7pNJcEIyj/vG6hzzZWiRok1MghFIUmjeEL0UV13oGBNlxX+y # T4UsSKRWhDXW+S6cqgAV0Tf+GgaUwnzI6hsy5srC9KejAw50pa85tqtgEuPo1rn3 # MeHcreQYoNjBI0dHs6EPbqOrbZgGgxu3amct0r1EGpIQgY+wOwnXx5syWsL/amBU # i0nBk+3htFzgb+sm+YzVsvk4EObqzpH1vtP7b5NhNFy8k0UogzYqZihfsHPOiyYl # BrKD1Fz2FRlM7WLgXjPy6OjsCqewAyuRsjZ5vvetCB51pmXMu+NIUPN3kRr+21Ci # RshhWJj1fAIWPIMorTmG7NS3DVPQ+EfmdTCN7DCTdhSmW0tddGFNPxKRdt6/WMty # EClB8NXFbSZ2aBFBE1ia3CYrAfSJTVnbeM+BSj5AR1/JgVBzhRAjIVlgimRUwcwh # Gug4GXxmHM14OEUwmU//Y09Mu6oNCFNBfFg9R7P6tuyMMgkCzGw8DFYRAgMBAAGj # ggFZMIIBVTASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBRoN+Drtjv4XxGG # +/5hewiIZfROQjAfBgNVHSMEGDAWgBTs1+OC0nFdZEzfLmc/57qYrhwPTzAOBgNV # HQ8BAf8EBAMCAYYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwdwYIKwYBBQUHAQEEazBp # MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wQQYIKwYBBQUH # MAKGNWh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRS # b290RzQuY3J0MEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwzLmRpZ2ljZXJ0 # LmNvbS9EaWdpQ2VydFRydXN0ZWRSb290RzQuY3JsMBwGA1UdIAQVMBMwBwYFZ4EM # AQMwCAYGZ4EMAQQBMA0GCSqGSIb3DQEBDAUAA4ICAQA6I0Q9jQh27o+8OpnTVuAC # GqX4SDTzLLbmdGb3lHKxAMqvbDAnExKekESfS/2eo3wm1Te8Ol1IbZXVP0n0J7sW # gUVQ/Zy9toXgdn43ccsi91qqkM/1k2rj6yDR1VB5iJqKisG2vaFIGH7c2IAaERkY # zWGZgVb2yeN258TkG19D+D6U/3Y5PZ7Umc9K3SjrXyahlVhI1Rr+1yc//ZDRdobd # HLBgXPMNqO7giaG9OeE4Ttpuuzad++UhU1rDyulq8aI+20O4M8hPOBSSmfXdzlRt # 2V0CFB9AM3wD4pWywiF1c1LLRtjENByipUuNzW92NyyFPxrOJukYvpAHsEN/lYgg # gnDwzMrv/Sk1XB+JOFX3N4qLCaHLC+kxGv8uGVw5ceG+nKcKBtYmZ7eS5k5f3nqs # Sc8upHSSrds8pJyGH+PBVhsrI/+PteqIe3Br5qC6/To/RabE6BaRUotBwEiES5ZN # q0RA443wFSjO7fEYVgcqLxDEDAhkPDOPriiMPMuPiAsNvzv0zh57ju+168u38HcT # 5ucoP6wSrqUvImxB+YJcFWbMbA7KxYbD9iYzDAdLoNMHAmpqQDBISzSoUSC7rRuF # COJZDW3KBVAr6kocnqX9oKcfBnTn8tZSkP2vhUgh+Vc7tJwD7YZF9LRhbr9o4iZg # hurIr6n+lB3nYxs6hlZ4TjCCBY0wggR1oAMCAQICEA6bGI750C3n79tQ4ghAGFow # DQYJKoZIhvcNAQEMBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0 # IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMbRGlnaUNl # cnQgQXNzdXJlZCBJRCBSb290IENBMB4XDTIyMDgwMTAwMDAwMFoXDTMxMTEwOTIz # NTk1OVowYjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcG # A1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQgVHJ1c3Rl # ZCBSb290IEc0MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAv+aQc2je # u+RdSjwwIjBpM+zCpyUuySE98orYWcLhKac9WKt2ms2uexuEDcQwH/MbpDgW61bG # l20dq7J58soR0uRf1gU8Ug9SH8aeFaV+vp+pVxZZVXKvaJNwwrK6dZlqczKU0RBE # EC7fgvMHhOZ0O21x4i0MG+4g1ckgHWMpLc7sXk7Ik/ghYZs06wXGXuxbGrzryc/N # rDRAX7F6Zu53yEioZldXn1RYjgwrt0+nMNlW7sp7XeOtyU9e5TXnMcvak17cjo+A # 2raRmECQecN4x7axxLVqGDgDEI3Y1DekLgV9iPWCPhCRcKtVgkEy19sEcypukQF8 # IUzUvK4bA3VdeGbZOjFEmjNAvwjXWkmkwuapoGfdpCe8oU85tRFYF/ckXEaPZPfB # aYh2mHY9WV1CdoeJl2l6SPDgohIbZpp0yt5LHucOY67m1O+SkjqePdwA5EUlibaa # RBkrfsCUtNJhbesz2cXfSwQAzH0clcOP9yGyshG3u3/y1YxwLEFgqrFjGESVGnZi # fvaAsPvoZKYz0YkH4b235kOkGLimdwHhD5QMIR2yVCkliWzlDlJRR3S+Jqy2QXXe # eqxfjT/JvNNBERJb5RBQ6zHFynIWIgnffEx1P2PsIV/EIFFrb7GrhotPwtZFX50g # /KEexcCPorF+CiaZ9eRpL5gdLfXZqbId5RsCAwEAAaOCATowggE2MA8GA1UdEwEB # /wQFMAMBAf8wHQYDVR0OBBYEFOzX44LScV1kTN8uZz/nupiuHA9PMB8GA1UdIwQY # MBaAFEXroq/0ksuCMS1Ri6enIZ3zbcgPMA4GA1UdDwEB/wQEAwIBhjB5BggrBgEF # BQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBD # BggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0 # QXNzdXJlZElEUm9vdENBLmNydDBFBgNVHR8EPjA8MDqgOKA2hjRodHRwOi8vY3Js # My5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMBEGA1Ud # IAQKMAgwBgYEVR0gADANBgkqhkiG9w0BAQwFAAOCAQEAcKC/Q1xV5zhfoKN0Gz22 # Ftf3v1cHvZqsoYcs7IVeqRq7IviHGmlUIu2kiHdtvRoU9BNKei8ttzjv9P+Aufih # 9/Jy3iS8UgPITtAq3votVs/59PesMHqai7Je1M/RQ0SbQyHrlnKhSLSZy51PpwYD # E3cnRNTnf+hZqPC/Lwum6fI0POz3A8eHqNJMQBk1RmppVLC4oVaO7KTVPeix3P0c # 2PR3WlxUjG/voVA9/HYJaISfb8rbII01YBwCA8sgsKxYoA5AY8WYIsGyWfVVa88n # q2x2zm8jLfR+cWojayL/ErhULSd+2DrZ8LaHlv1b0VysGMNNn3O3AamfV6peKOK5 # lDGCGfkwghn1AgEBMH0waTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0 # LCBJbmMuMUEwPwYDVQQDEzhEaWdpQ2VydCBUcnVzdGVkIEc0IENvZGUgU2lnbmlu # ZyBSU0E0MDk2IFNIQTM4NCAyMDIxIENBMQIQBR7MBdhjQ9hm8MZHvZqkUTANBglg # hkgBZQMEAgEFAKB8MBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMBAGCisG # AQQBgjcCAQwxAjAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMC8GCSqGSIb3 # DQEJBDEiBCC5+B9a+NnoQOrFSEZhJuQHPZbsipnE2gra3UNzET6bIzANBgkqhkiG # 9w0BAQEFAASCAYAdTd7qj77RVC80GmWQxRry808XnlplUL8mI3OcVELC1zxmOyMp # ph3bGyYTNYobmojF5DQ6MSRB2N/0GcjtoFHprZI8xBR52TwlpXSPdXfBuwS2/iL5 # VTPnlqyvoWc+Vr1wu7EYr7lfYrxIqqxtCnQzQzA5Es56gQU7VfUUg58XCHdVszBM # hT1pTUknjYZ/Gl1J6sP3mpQbrJSXp+gwUgmqFqprcxSZiSbswI2EkX/Mil2U+LxU # ExdqY8ycNM0Wfe3JGz4f1UU3LxcLvaS6dmt9peJdrdS29eX+m1lGazTC8ijoQM1X # YmAeKp9J/tT9N7WUJPRW06wuauwTnF0VFA2y2SZFNM0XoF2VppcSPTV+9YGk3jUO # XiThjrxIfxr2luc5JHoSkks8VDyWEwiKgUMbefYp7TglhqD6u1konqCfRGCrMVz0 # GYMH+XLymIx/xXx4Qu5ICcN9Y375R0JaiE8K1N850BzsNNEHMaudnxi+LMnzPRkr # fsXDuOLTjucCL0KhghdPMIIXSwYKKwYBBAGCNwMDATGCFzswghc3BgkqhkiG9w0B # BwKgghcoMIIXJAIBAzEPMA0GCWCGSAFlAwQCAQUAMIGGBgsqhkiG9w0BCRABBKB3 # BHUwcwIBAQYJYIZIAYb9bAcBMDEwDQYJYIZIAWUDBAIBBQAEIB4BXS1A4Le9zimo # 07CXvzCocxGywXVZ8lZb//s/3UBbAhEA4jgbrtXRnkdcUlPd09EHSBgPMjAyNDAz # MTQxMjA3MzVaAgxkGRdA4ERQfXuxhdqgghMJMIIGwjCCBKqgAwIBAgIQBUSv85Sd # CDmmv9s/X+VhFjANBgkqhkiG9w0BAQsFADBjMQswCQYDVQQGEwJVUzEXMBUGA1UE # ChMORGlnaUNlcnQsIEluYy4xOzA5BgNVBAMTMkRpZ2lDZXJ0IFRydXN0ZWQgRzQg # UlNBNDA5NiBTSEEyNTYgVGltZVN0YW1waW5nIENBMB4XDTIzMDcxNDAwMDAwMFoX # DTM0MTAxMzIzNTk1OVowSDELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0 # LCBJbmMuMSAwHgYDVQQDExdEaWdpQ2VydCBUaW1lc3RhbXAgMjAyMzCCAiIwDQYJ # KoZIhvcNAQEBBQADggIPADCCAgoCggIBAKNTRYcdg45brD5UsyPgz5/X5dLnXaEO # CdwvSKOXejsqnGfcYhVYwamTEafNqrJq3RApih5iY2nTWJw1cb86l+uUUI8cIOrH # mjsvlmbjaedp/lvD1isgHMGXlLSlUIHyz8sHpjBoyoNC2vx/CSSUpIIa2mq62DvK # Xd4ZGIX7ReoNYWyd/nFexAaaPPDFLnkPG2ZS48jWPl/aQ9OE9dDH9kgtXkV1lnX+ # 3RChG4PBuOZSlbVH13gpOWvgeFmX40QrStWVzu8IF+qCZE3/I+PKhu60pCFkcOvV # 5aDaY7Mu6QXuqvYk9R28mxyyt1/f8O52fTGZZUdVnUokL6wrl76f5P17cz4y7lI0 # +9S769SgLDSb495uZBkHNwGRDxy1Uc2qTGaDiGhiu7xBG3gZbeTZD+BYQfvYsSzh # Ua+0rRUGFOpiCBPTaR58ZE2dD9/O0V6MqqtQFcmzyrzXxDtoRKOlO0L9c33u3Qr/ # eTQQfqZcClhMAD6FaXXHg2TWdc2PEnZWpST618RrIbroHzSYLzrqawGw9/sqhux7 # UjipmAmhcbJsca8+uG+W1eEQE/5hRwqM/vC2x9XH3mwk8L9CgsqgcT2ckpMEtGlw # Jw1Pt7U20clfCKRwo+wK8REuZODLIivK8SgTIUlRfgZm0zu++uuRONhRB8qUt+JQ # ofM604qDy0B7AgMBAAGjggGLMIIBhzAOBgNVHQ8BAf8EBAMCB4AwDAYDVR0TAQH/ # BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcDCDAgBgNVHSAEGTAXMAgGBmeBDAEE # AjALBglghkgBhv1sBwEwHwYDVR0jBBgwFoAUuhbZbU2FL3MpdpovdYxqII+eyG8w # HQYDVR0OBBYEFKW27xPn783QZKHVVqllMaPe1eNJMFoGA1UdHwRTMFEwT6BNoEuG # SWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRHNFJTQTQw # OTZTSEEyNTZUaW1lU3RhbXBpbmdDQS5jcmwwgZAGCCsGAQUFBwEBBIGDMIGAMCQG # CCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wWAYIKwYBBQUHMAKG # TGh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRHNFJT # QTQwOTZTSEEyNTZUaW1lU3RhbXBpbmdDQS5jcnQwDQYJKoZIhvcNAQELBQADggIB # AIEa1t6gqbWYF7xwjU+KPGic2CX/yyzkzepdIpLsjCICqbjPgKjZ5+PF7SaCinEv # GN1Ott5s1+FgnCvt7T1IjrhrunxdvcJhN2hJd6PrkKoS1yeF844ektrCQDifXcig # LiV4JZ0qBXqEKZi2V3mP2yZWK7Dzp703DNiYdk9WuVLCtp04qYHnbUFcjGnRuSvE # xnvPnPp44pMadqJpddNQ5EQSviANnqlE0PjlSXcIWiHFtM+YlRpUurm8wWkZus8W # 8oM3NG6wQSbd3lqXTzON1I13fXVFoaVYJmoDRd7ZULVQjK9WvUzF4UbFKNOt50MA # cN7MmJ4ZiQPq1JE3701S88lgIcRWR+3aEUuMMsOI5ljitts++V+wQtaP4xeR0arA # VeOGv6wnLEHQmjNKqDbUuXKWfpd5OEhfysLcPTLfddY2Z1qJ+Panx+VPNTwAvb6c # Kmx5AdzaROY63jg7B145WPR8czFVoIARyxQMfq68/qTreWWqaNYiyjvrmoI1VygW # y2nyMpqy0tg6uLFGhmu6F/3Ed2wVbK6rr3M66ElGt9V/zLY4wNjsHPW2obhDLN9O # TH0eaHDAdwrUAuBcYLso/zjlUlrWrBciI0707NMX+1Br/wd3H3GXREHJuEbTbDJ8 # WC9nR2XlG3O2mflrLAZG70Ee8PBf4NvZrZCARK+AEEGKMIIGrjCCBJagAwIBAgIQ # BzY3tyRUfNhHrP0oZipeWzANBgkqhkiG9w0BAQsFADBiMQswCQYDVQQGEwJVUzEV # MBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29t # MSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwHhcNMjIwMzIzMDAw # MDAwWhcNMzcwMzIyMjM1OTU5WjBjMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGln # aUNlcnQsIEluYy4xOzA5BgNVBAMTMkRpZ2lDZXJ0IFRydXN0ZWQgRzQgUlNBNDA5 # NiBTSEEyNTYgVGltZVN0YW1waW5nIENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A # MIICCgKCAgEAxoY1BkmzwT1ySVFVxyUDxPKRN6mXUaHW0oPRnkyibaCwzIP5WvYR # oUQVQl+kiPNo+n3znIkLf50fng8zH1ATCyZzlm34V6gCff1DtITaEfFzsbPuK4CE # iiIY3+vaPcQXf6sZKz5C3GeO6lE98NZW1OcoLevTsbV15x8GZY2UKdPZ7Gnf2ZCH # RgB720RBidx8ald68Dd5n12sy+iEZLRS8nZH92GDGd1ftFQLIWhuNyG7QKxfst5K # fc71ORJn7w6lY2zkpsUdzTYNXNXmG6jBZHRAp8ByxbpOH7G1WE15/tePc5OsLDni # pUjW8LAxE6lXKZYnLvWHpo9OdhVVJnCYJn+gGkcgQ+NDY4B7dW4nJZCYOjgRs/b2 # nuY7W+yB3iIU2YIqx5K/oN7jPqJz+ucfWmyU8lKVEStYdEAoq3NDzt9KoRxrOMUp # 88qqlnNCaJ+2RrOdOqPVA+C/8KI8ykLcGEh/FDTP0kyr75s9/g64ZCr6dSgkQe1C # vwWcZklSUPRR8zZJTYsg0ixXNXkrqPNFYLwjjVj33GHek/45wPmyMKVM1+mYSlg+ # 0wOI/rOP015LdhJRk8mMDDtbiiKowSYI+RQQEgN9XyO7ZONj4KbhPvbCdLI/Hgl2 # 7KtdRnXiYKNYCQEoAA6EVO7O6V3IXjASvUaetdN2udIOa5kM0jO0zbECAwEAAaOC # AV0wggFZMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFLoW2W1NhS9zKXaa # L3WMaiCPnshvMB8GA1UdIwQYMBaAFOzX44LScV1kTN8uZz/nupiuHA9PMA4GA1Ud # DwEB/wQEAwIBhjATBgNVHSUEDDAKBggrBgEFBQcDCDB3BggrBgEFBQcBAQRrMGkw # JAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBBBggrBgEFBQcw # AoY1aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0VHJ1c3RlZFJv # b3RHNC5jcnQwQwYDVR0fBDwwOjA4oDagNIYyaHR0cDovL2NybDMuZGlnaWNlcnQu # Y29tL0RpZ2lDZXJ0VHJ1c3RlZFJvb3RHNC5jcmwwIAYDVR0gBBkwFzAIBgZngQwB # BAIwCwYJYIZIAYb9bAcBMA0GCSqGSIb3DQEBCwUAA4ICAQB9WY7Ak7ZvmKlEIgF+ # ZtbYIULhsBguEE0TzzBTzr8Y+8dQXeJLKftwig2qKWn8acHPHQfpPmDI2AvlXFvX # bYf6hCAlNDFnzbYSlm/EUExiHQwIgqgWvalWzxVzjQEiJc6VaT9Hd/tydBTX/6tP # iix6q4XNQ1/tYLaqT5Fmniye4Iqs5f2MvGQmh2ySvZ180HAKfO+ovHVPulr3qRCy # Xen/KFSJ8NWKcXZl2szwcqMj+sAngkSumScbqyQeJsG33irr9p6xeZmBo1aGqwpF # yd/EjaDnmPv7pp1yr8THwcFqcdnGE4AJxLafzYeHJLtPo0m5d2aR8XKc6UsCUqc3 # fpNTrDsdCEkPlM05et3/JWOZJyw9P2un8WbDQc1PtkCbISFA0LcTJM3cHXg65J6t # 5TRxktcma+Q4c6umAU+9Pzt4rUyt+8SVe+0KXzM5h0F4ejjpnOHdI/0dKNPH+ejx # mF/7K9h+8kaddSweJywm228Vex4Ziza4k9Tm8heZWcpw8De/mADfIBZPJ/tgZxah # ZrrdVcA6KYawmKAr7ZVBtzrVFZgxtGIJDwq9gdkT/r+k0fNX2bwE+oLeMt8EifAA # zV3C+dAjfwAL5HYCJtnwZXZCpimHCUcr5n8apIUP/JiW9lVUKx+A+sDyDivl1vup # L0QVSucTDh3bNzgaoSv27dZ8/DCCBY0wggR1oAMCAQICEA6bGI750C3n79tQ4ghA # GFowDQYJKoZIhvcNAQEMBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lD # ZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMbRGln # aUNlcnQgQXNzdXJlZCBJRCBSb290IENBMB4XDTIyMDgwMTAwMDAwMFoXDTMxMTEw # OTIzNTk1OVowYjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ # MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQgVHJ1 # c3RlZCBSb290IEc0MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAv+aQ # c2jeu+RdSjwwIjBpM+zCpyUuySE98orYWcLhKac9WKt2ms2uexuEDcQwH/MbpDgW # 61bGl20dq7J58soR0uRf1gU8Ug9SH8aeFaV+vp+pVxZZVXKvaJNwwrK6dZlqczKU # 0RBEEC7fgvMHhOZ0O21x4i0MG+4g1ckgHWMpLc7sXk7Ik/ghYZs06wXGXuxbGrzr # yc/NrDRAX7F6Zu53yEioZldXn1RYjgwrt0+nMNlW7sp7XeOtyU9e5TXnMcvak17c # jo+A2raRmECQecN4x7axxLVqGDgDEI3Y1DekLgV9iPWCPhCRcKtVgkEy19sEcypu # kQF8IUzUvK4bA3VdeGbZOjFEmjNAvwjXWkmkwuapoGfdpCe8oU85tRFYF/ckXEaP # ZPfBaYh2mHY9WV1CdoeJl2l6SPDgohIbZpp0yt5LHucOY67m1O+SkjqePdwA5EUl # ibaaRBkrfsCUtNJhbesz2cXfSwQAzH0clcOP9yGyshG3u3/y1YxwLEFgqrFjGESV # GnZifvaAsPvoZKYz0YkH4b235kOkGLimdwHhD5QMIR2yVCkliWzlDlJRR3S+Jqy2 # QXXeeqxfjT/JvNNBERJb5RBQ6zHFynIWIgnffEx1P2PsIV/EIFFrb7GrhotPwtZF # X50g/KEexcCPorF+CiaZ9eRpL5gdLfXZqbId5RsCAwEAAaOCATowggE2MA8GA1Ud # EwEB/wQFMAMBAf8wHQYDVR0OBBYEFOzX44LScV1kTN8uZz/nupiuHA9PMB8GA1Ud # IwQYMBaAFEXroq/0ksuCMS1Ri6enIZ3zbcgPMA4GA1UdDwEB/wQEAwIBhjB5Bggr # BgEFBQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNv # bTBDBggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lD # ZXJ0QXNzdXJlZElEUm9vdENBLmNydDBFBgNVHR8EPjA8MDqgOKA2hjRodHRwOi8v # Y3JsMy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMBEG # A1UdIAQKMAgwBgYEVR0gADANBgkqhkiG9w0BAQwFAAOCAQEAcKC/Q1xV5zhfoKN0 # Gz22Ftf3v1cHvZqsoYcs7IVeqRq7IviHGmlUIu2kiHdtvRoU9BNKei8ttzjv9P+A # ufih9/Jy3iS8UgPITtAq3votVs/59PesMHqai7Je1M/RQ0SbQyHrlnKhSLSZy51P # pwYDE3cnRNTnf+hZqPC/Lwum6fI0POz3A8eHqNJMQBk1RmppVLC4oVaO7KTVPeix # 3P0c2PR3WlxUjG/voVA9/HYJaISfb8rbII01YBwCA8sgsKxYoA5AY8WYIsGyWfVV # a88nq2x2zm8jLfR+cWojayL/ErhULSd+2DrZ8LaHlv1b0VysGMNNn3O3AamfV6pe # KOK5lDGCA3YwggNyAgEBMHcwYzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lD # ZXJ0LCBJbmMuMTswOQYDVQQDEzJEaWdpQ2VydCBUcnVzdGVkIEc0IFJTQTQwOTYg # U0hBMjU2IFRpbWVTdGFtcGluZyBDQQIQBUSv85SdCDmmv9s/X+VhFjANBglghkgB # ZQMEAgEFAKCB0TAaBgkqhkiG9w0BCQMxDQYLKoZIhvcNAQkQAQQwHAYJKoZIhvcN # AQkFMQ8XDTI0MDMxNDEyMDczNVowKwYLKoZIhvcNAQkQAgwxHDAaMBgwFgQUZvAr # MsLCyQ+CXc6qisnGTxmcz0AwLwYJKoZIhvcNAQkEMSIEIMm2MwTtt/C02XFFDeFI # Nxt/9L0K51G2zQ6JLAU42halMDcGCyqGSIb3DQEJEAIvMSgwJjAkMCIEINL25G3t # dCLM0dRAV2hBNm+CitpVmq4zFq9NGprUDHgoMA0GCSqGSIb3DQEBAQUABIICAGCq # UJM5+Mq1l1yPZMCmHSom08skeSTA0fHwYm069JqLmKOQNziYIkQc5St/62M1fb0t # edSXGaVzHPetqFfzoLesvHo3T1NlRRgtPx6xAhu3ne6qsCFclvqXpF3DAbEV67N3 # 1znX+PhdiB18Tt2UUNwnlWl8wi71v1Suv0wR+gW0IBquATSIrjilp8YEKZKN8bxX # X4bSs27lNUirRSafN3GEcgKDYYJrzNueQNrTHZhmwtbFUtIf7Ihg+CL3dyjtsdCl # buU42wJRBIcn+4qzQ9l/RQzQFnu4NnZzPSWfclZZbv3LEmiXoFx2Do6ZyO8e26Nu # 4z2M+CGaky8b3NMB9KvV3h72o0So2a86CWmSyCr+vftcBXvumNloNQ9dQe+bejT7 # 8S1/7RpKwxUckFQxmc1H5JOS39anppB7deCG6IcyESoeMJglFCg3gvvqZ8ZXNa3t # W1hMAzzxQDSfZQvfI4RwJy2hjZAum9tAbrpTOBG47+liQe9PpzPltY7G0qUNNEiW # xlHZ8tJl4PEIxEpva3A5VV11ygdn1bH2o3Ogm2cZV3Ol+xHSDL668QnkP3KIkHKn # 68ZWrldMEWFFao25LpHaxQQ8WMNnbIrq+84rbeOGW9mHz0w6SUFObOTEt+zcBl+S # wyGeY1vwBsrGYkJCgNF7kDJW9cxSfxRGlUGNCaAn # SIG # End signature block
ADLSCmdlets.psd1
ADLSCmdlets-23.0.8839.1
@{ GUID = '1804941f-f818-4744-b800-14a244343b6d' Author = 'CData Software, Inc.' CompanyName = 'CData Software, Inc.' Copyright = 'Copyright (c) 2024 CData Software, Inc. - All rights reserved.' ModuleVersion = '23.0.8839.1' Description = 'CData Cmdlets for Azure Data Lake Storage' PowerShellVersion = '3.0' CLRVersion = '4.0' CmdletsToExport = '*' RequiredModules = @() ModuleToProcess = 'ADLSCmdlets.psm1' ScriptsToProcess = @() TypesToProcess = @() PrivateData = @{ PSData = @{ Tags = @("CData", "Cmdlets", "Azure","Data","Lake","Storage") LicenseUri = "http://www.cdata.com/company/legal/terms.aspx" ProjectUri = "http://www.cdata.com/powershell/" IconUri = "http://www.cdata.com/powershell/img/psgallery_icon.png" SKU = "HDMJA" } } }
scriptblocks.ps1
ADMF-1.13.100
<# 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 'ADMF.ScriptBlockName' -Scriptblock { } #> Set-PSFScriptblock -Name 'ADMF.Validate.Type.Gpo' -Scriptblock { foreach ($item in $_) { if ($item.PSObject.TypeNames -notcontains 'Microsoft.GroupPolicy.Gpo') { return $false } } $true } Set-PSFScriptblock -Name 'ADMF.Validate.Path' -Scriptblock { Test-Path -Path $_ } Set-PSFScriptblock -Name 'ADMF.Validate.Path.Folder' -Scriptblock { $resolvedPath = Resolve-PSFPath -Provider FileSystem -Path $_ -SingleItem Test-Path -Path $resolvedPath -PathType Container } Set-PSFScriptblock -Name 'ADMF.Validate.ContextStore.ExistsNot' -Scriptblock { $_ -notin (Get-AdmfContextStore).Name }
addefault_domainControllers.psd1
ADMF-1.13.100
@{ Name = 'DomainController' ObjectClass = 'computer' Property = @('PrimaryGroupID') TestScript = { $args[0].PrimaryGroupID -eq 516 } LDAPFilter = '(&(objectCategory=computer)(primaryGroupID=516))' }
context.Tepp.ps1
ADMF-1.13.100
<# # Example: Register-PSFTeppScriptblock -Name "ADMF.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #> Register-PSFTeppScriptblock -Name 'ADMF.Context.Store' -ScriptBlock { (Get-AdmfContextStore).Name }
preimport.ps1
ADMF-1.13.100
# Add all things you want to run before importing the main code # Load the strings used in messages . Import-ModuleFile -Path "$($script:ModuleRoot)\internal\scripts\strings.ps1"
pester.ps1
ADMF-1.13.100
param ( $TestGeneral = $true, $TestFunctions = $true, [ValidateSet('None', 'Normal', 'Detailed', 'Diagnostic')] [Alias('Show')] $Output = "None", $Include = "*", $Exclude = "" ) Write-PSFMessage -Level Important -Message "Starting Tests" Write-PSFMessage -Level Important -Message "Importing Module" $global:testroot = $PSScriptRoot $global:__pester_data = @{ } Remove-Module ADMF -ErrorAction Ignore Import-Module "$PSScriptRoot\..\ADMF.psd1" Import-Module "$PSScriptRoot\..\ADMF.psm1" -Force # Need to import explicitly so we can use the configuration class Import-Module Pester Write-PSFMessage -Level Important -Message "Creating test result folder" $null = New-Item -Path "$PSScriptRoot\..\.." -Name TestResults -ItemType Directory -Force $totalFailed = 0 $totalRun = 0 $testresults = @() $config = [PesterConfiguration]::Default $config.TestResult.Enabled = $true #region Run General Tests if ($TestGeneral) { Write-PSFMessage -Level Important -Message "Modules imported, proceeding with general tests" foreach ($file in (Get-ChildItem "$PSScriptRoot\general" | Where-Object Name -like "*.Tests.ps1")) { if ($file.Name -notlike $Include) { continue } if ($file.Name -like $Exclude) { continue } Write-PSFMessage -Level Significant -Message " Executing <c='em'>$($file.Name)</c>" $config.TestResult.OutputPath = Join-Path "$PSScriptRoot\..\..\TestResults" "TEST-$($file.BaseName).xml" $config.Run.Path = $file.FullName $config.Run.PassThru = $true $config.Output.Verbosity = $Output $results = Invoke-Pester -Configuration $config foreach ($result in $results) { $totalRun += $result.TotalCount $totalFailed += $result.FailedCount $result.Tests | Where-Object Result -ne 'Passed' | ForEach-Object { $testresults += [pscustomobject]@{ Block = $_.Block Name = "It $($_.Name)" Result = $_.Result Message = $_.ErrorRecord.DisplayErrorMessage } } } } } #endregion Run General Tests $global:__pester_data.ScriptAnalyzer | Out-Host #region Test Commands if ($TestFunctions) { Write-PSFMessage -Level Important -Message "Proceeding with individual tests" foreach ($file in (Get-ChildItem "$PSScriptRoot\functions" -Recurse -File | Where-Object Name -like "*Tests.ps1")) { if ($file.Name -notlike $Include) { continue } if ($file.Name -like $Exclude) { continue } Write-PSFMessage -Level Significant -Message " Executing $($file.Name)" $config.TestResult.OutputPath = Join-Path "$PSScriptRoot\..\..\TestResults" "TEST-$($file.BaseName).xml" $config.Run.Path = $file.FullName $config.Run.PassThru = $true $config.Output.Verbosity = $Output $results = Invoke-Pester -Configuration $config foreach ($result in $results) { $totalRun += $result.TotalCount $totalFailed += $result.FailedCount $result.Tests | Where-Object Result -ne 'Passed' | ForEach-Object { $testresults += [pscustomobject]@{ Block = $_.Block Name = "It $($_.Name)" Result = $_.Result Message = $_.ErrorRecord.DisplayErrorMessage } } } } } #endregion Test Commands $testresults | Sort-Object Describe, Context, Name, Result, Message | Format-List if ($totalFailed -eq 0) { Write-PSFMessage -Level Critical -Message "All <c='em'>$totalRun</c> tests executed without a single failure!" } else { Write-PSFMessage -Level Critical -Message "<c='em'>$totalFailed tests</c> out of <c='sub'>$totalRun</c> tests failed!" } if ($totalFailed -gt 0) { throw "$totalFailed / $totalRun tests failed!" }
DCSelectionMode.ps1
ADMF-1.13.100
Register-PSFConfigValidation -Name "DCSelectionMode" -ScriptBlock { Param ( $Value ) $Result = New-Object PSObject -Property @{ Success = $True Value = $null Message = "" } $legalModes = @( 'Random' 'PDCEmulator' 'Site' ) if ($Value -notin $legalModes) { $Result.Message = "Bad value: $Value is not any of '$($legalModes -join ",")'" $Result.Success = $False return $Result } $Result.Value = $Value -as [string] return $Result }
addefault_msDFSR-LocalSettings.psd1
ADMF-1.13.100
@{ Name = 'msDFSR-LocalSettings' ObjectClass = 'msDFSR-LocalSettings' Property = @('Name') TestScript = { $args[0].ObjectClass -eq 'msDFSR-LocalSettings' } LDAPFilter = '(objectCategory=msDFSR-LocalSettings)' }
New-AdmfContextStore.ps1
ADMF-1.13.100
function New-AdmfContextStore { <# .SYNOPSIS Creates a new Context Store. .DESCRIPTION Creates a new Context Store. Context Stores are locations where configuration contexts are stored and retrieved from. These contexts are stored using the PSFramework configuration system: https://psframework.org/documentation/documents/psframework/configuration.html Making it possible to deploy them using GPO, SCCM or other computer or profile management solutions. .PARAMETER Name The name of the store to create. Must not exist yet. .PARAMETER Path The path where the context is pointing at. Must be an existing folder. .PARAMETER Scope Where to persist the store. by default, this is stored in HKCU, making the store persistently available to the user. For more information on scopes, and what location they corespond with, see: https://psframework.org/documentation/documents/psframework/configuration/persistence-location.html .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> New-AdmfContextStore -Name 'company' -Path '\\contoso\system\ad\contexts' Creates a new context named 'company', pointing at '\\contoso\system\ad\contexts' #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [PsfValidateScript('ADMF.Validate.ContextStore.ExistsNot', ErrorString = 'ADMF.Validate.ContextStore.ExistsNot')] [PsfValidatePattern('^[\w\d_\-\.]+$', ErrorString = 'ADMF.Validate.Pattern.ContextStoreName')] [string] $Name, [Parameter(Mandatory = $true)] [PsfValidateScript('ADMF.Validate.Path.Folder', ErrorString = 'ADMF.Validate.Path.Folder')] [string] $Path, [PSFramework.Configuration.ConfigScope] $Scope = "UserDefault", [switch] $EnableException ) process { $resolvedPath = Resolve-PSFPath -Path $Path -Provider FileSystem -SingleItem Set-PSFConfig -FullName "ADMF.Context.Store.$Name" -Value $resolvedPath Register-PSFConfig -FullName "ADMF.Context.Store.$Name" -Scope $Scope -EnableException:$EnableException } }
strings.ps1
ADMF-1.13.100
<# 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 'ADMF' -Language 'en-US'
Get-AdmfContextStore.ps1
ADMF-1.13.100
function Get-AdmfContextStore { <# .SYNOPSIS Returns the list of available context stores. .DESCRIPTION Returns the list of available context stores. .PARAMETER Name The name to filter by. .EXAMPLE PS C:\> Get-AdmfContextStore Returns all available context stores. #> [CmdletBinding()] param ( [string] $Name = '*' ) process { foreach ($config in (Get-PSFConfig -FullName "ADMF.Context.Store.$Name")) { [PSCustomObject]@{ PSTypeName = 'ADMF.Context.Store' Name = $config.Name -replace '^Context\.Store\.' Path = $config.Value PathExists = (Test-Path $config.Value) } } } }
Manifest.Tests.ps1
ADMF-1.13.100
Describe "Validating the module manifest" { $moduleRoot = (Resolve-Path "$global:testroot\..").Path $manifest = ((Get-Content "$moduleRoot\ADMF.psd1") -join "`n") | Invoke-Expression Context "Basic resources validation" { $files = Get-ChildItem "$moduleRoot\functions" -Recurse -File | Where-Object Name -like "*.ps1" It "Exports all functions in the public folder" -TestCases @{ files = $files; manifest = $manifest } { $functions = (Compare-Object -ReferenceObject $files.BaseName -DifferenceObject $manifest.FunctionsToExport | Where-Object SideIndicator -Like '<=').InputObject $functions | Should -BeNullOrEmpty } It "Exports no function that isn't also present in the public folder" -TestCases @{ files = $files; manifest = $manifest } { $functions = (Compare-Object -ReferenceObject $files.BaseName -DifferenceObject $manifest.FunctionsToExport | Where-Object SideIndicator -Like '=>').InputObject $functions | Should -BeNullOrEmpty } It "Exports none of its internal functions" -TestCases @{ moduleRoot = $moduleRoot; manifest = $manifest } { $files = Get-ChildItem "$moduleRoot\internal\functions" -Recurse -File -Filter "*.ps1" $files | Where-Object BaseName -In $manifest.FunctionsToExport | Should -BeNullOrEmpty } } Context "Individual file validation" { It "The root module file exists" -TestCases @{ moduleRoot = $moduleRoot; manifest = $manifest } { Test-Path "$moduleRoot\$($manifest.RootModule)" | Should -Be $true } foreach ($format in $manifest.FormatsToProcess) { It "The file $format should exist" -TestCases @{ moduleRoot = $moduleRoot; format = $format } { Test-Path "$moduleRoot\$format" | Should -Be $true } } foreach ($type in $manifest.TypesToProcess) { It "The file $type should exist" -TestCases @{ moduleRoot = $moduleRoot; type = $type } { Test-Path "$moduleRoot\$type" | Should -Be $true } } foreach ($assembly in $manifest.RequiredAssemblies) { if ($assembly -like "*.dll") { It "The file $assembly should exist" -TestCases @{ moduleRoot = $moduleRoot; assembly = $assembly } { Test-Path "$moduleRoot\$assembly" | Should -Be $true } } else { It "The file $assembly should load from the GAC" -TestCases @{ moduleRoot = $moduleRoot; assembly = $assembly } { { Add-Type -AssemblyName $assembly } | Should -Not -Throw } } } foreach ($tag in $manifest.PrivateData.PSData.Tags) { It "Tags should have no spaces in name" -TestCases @{ tag = $tag } { $tag -match " " | Should -Be $false } } } }
Help.Tests.ps1
ADMF-1.13.100
<# .NOTES The original test this is based upon was written by June Blender. After several rounds of modifications it stands now as it is, but the honor remains hers. Thank you June, for all you have done! .DESCRIPTION This test evaluates the help for all commands in a module. .PARAMETER SkipTest Disables this test. .PARAMETER CommandPath List of paths under which the script files are stored. This test assumes that all functions have their own file that is named after themselves. These paths are used to search for commands that should exist and be tested. Will search recursively and accepts wildcards, make sure only functions are found .PARAMETER ModuleName Name of the module to be tested. The module must already be imported .PARAMETER ExceptionsFile File in which exceptions and adjustments are configured. In it there should be two arrays and a hashtable defined: $global:FunctionHelpTestExceptions $global:HelpTestEnumeratedArrays $global:HelpTestSkipParameterType These can be used to tweak the tests slightly in cases of need. See the example file for explanations on each of these usage and effect. #> [CmdletBinding()] Param ( [switch] $SkipTest, [string[]] $CommandPath = @("$global:testroot\..\functions", "$global:testroot\..\internal\functions"), [string] $ModuleName = "ADMF", [string] $ExceptionsFile = "$global:testroot\general\Help.Exceptions.ps1" ) if ($SkipTest) { return } . $ExceptionsFile $includedNames = (Get-ChildItem $CommandPath -Recurse -File | Where-Object Name -like "*.ps1").BaseName $commands = Get-Command -Module (Get-Module $ModuleName) -CommandType Cmdlet, Function, Workflow | Where-Object Name -in $includedNames ## When testing help, remember that help is cached at the beginning of each session. ## To test, restart session. foreach ($command in $commands) { $commandName = $command.Name # Skip all functions that are on the exclusions list if ($global:FunctionHelpTestExceptions -contains $commandName) { continue } # The module-qualified command fails on Microsoft.PowerShell.Archive cmdlets $Help = Get-Help $commandName -ErrorAction SilentlyContinue Describe "Test help for $commandName" { # If help is not found, synopsis in auto-generated help is the syntax diagram It "should not be auto-generated" -TestCases @{ Help = $Help } { $Help.Synopsis | Should -Not -BeLike '*`[`<CommonParameters`>`]*' } # Should be a description for every function It "gets description for $commandName" -TestCases @{ Help = $Help } { $Help.Description | Should -Not -BeNullOrEmpty } # Should be at least one example It "gets example code from $commandName" -TestCases @{ Help = $Help } { ($Help.Examples.Example | Select-Object -First 1).Code | Should -Not -BeNullOrEmpty } # Should be at least one example description It "gets example help from $commandName" -TestCases @{ Help = $Help } { ($Help.Examples.Example.Remarks | Select-Object -First 1).Text | Should -Not -BeNullOrEmpty } Context "Test parameter help for $commandName" { $common = 'Debug', 'ErrorAction', 'ErrorVariable', 'InformationAction', 'InformationVariable', 'OutBuffer', 'OutVariable', 'PipelineVariable', 'Verbose', 'WarningAction', 'WarningVariable' $parameters = $command.ParameterSets.Parameters | Sort-Object -Property Name -Unique | Where-Object Name -notin $common $parameterNames = $parameters.Name $HelpParameterNames = $Help.Parameters.Parameter.Name | Sort-Object -Unique foreach ($parameter in $parameters) { $parameterName = $parameter.Name $parameterHelp = $Help.parameters.parameter | Where-Object Name -EQ $parameterName # Should be a description for every parameter It "gets help for parameter: $parameterName : in $commandName" -TestCases @{ parameterHelp = $parameterHelp } { $parameterHelp.Description.Text | Should -Not -BeNullOrEmpty } $codeMandatory = $parameter.IsMandatory.toString() It "help for $parameterName parameter in $commandName has correct Mandatory value" -TestCases @{ parameterHelp = $parameterHelp; codeMandatory = $codeMandatory } { $parameterHelp.Required | Should -Be $codeMandatory } if ($HelpTestSkipParameterType[$commandName] -contains $parameterName) { continue } $codeType = $parameter.ParameterType.Name if ($parameter.ParameterType.IsEnum) { # Enumerations often have issues with the typename not being reliably available $names = $parameter.ParameterType::GetNames($parameter.ParameterType) # Parameter type in Help should match code It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ parameterHelp = $parameterHelp; names = $names } { $parameterHelp.parameterValueGroup.parameterValue | Should -be $names } } elseif ($parameter.ParameterType.FullName -in $HelpTestEnumeratedArrays) { # Enumerations often have issues with the typename not being reliably available $names = [Enum]::GetNames($parameter.ParameterType.DeclaredMembers[0].ReturnType) It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ parameterHelp = $parameterHelp; names = $names } { $parameterHelp.parameterValueGroup.parameterValue | Should -be $names } } else { # To avoid calling Trim method on a null object. $helpType = if ($parameterHelp.parameterValue) { $parameterHelp.parameterValue.Trim() } # Parameter type in Help should match code It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ helpType = $helpType; codeType = $codeType } { $helpType | Should -be $codeType } } } foreach ($helpParm in $HelpParameterNames) { # Shouldn't find extra parameters in help. It "finds help parameter in code: $helpParm" -TestCases @{ helpParm = $helpParm; parameterNames = $parameterNames } { $helpParm -in $parameterNames | Should -Be $true } } } } }
Test-AdmfForest.ps1
ADMF-1.13.100
function Test-AdmfForest { <# .SYNOPSIS Tests whether a forest is configured according to baseline configuration .DESCRIPTION Tests whether a forest is configured according to baseline configuration .PARAMETER Server The server / domain to work with. .PARAMETER Credential The credentials to use for this operation. .PARAMETER Options What tests to execute. Defaults to all tests. .PARAMETER CredentialProvider The credential provider to use to resolve the input credentials. See help on Register-AdmfCredentialProvider for details. .PARAMETER ContextPrompt Force displaying the Context selection User Interface. .EXAMPLE PS C:\> Test-AdmfForest Test the current forest for baseline compliance. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '')] [CmdletBinding()] Param ( [PSFComputer[]] $Server, [PSCredential] $Credential, [UpdateForestOptions[]] $Options = 'All', [string] $CredentialProvider = 'default', [Alias('Ctx')] [switch] $ContextPrompt ) begin { [UpdateForestOptions]$newOptions = $Options } process { foreach ($computer in $Server) { Reset-DomainControllerCache $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential $parameters.Server = $computer $originalArgument = Invoke-PreCredentialProvider @parameters -ProviderName $CredentialProvider -Parameter $parameters -Cmdlet $PSCmdlet try { $parameters.Server = Resolve-DomainController @parameters -ErrorAction Stop -Confirm:$false } catch { Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential -Cmdlet $PSCmdlet Write-Error $_ continue } Invoke-PSFCallback -Data $parameters -EnableException $true -PSCmdlet $PSCmdlet Set-AdmfContext @parameters -Interactive -ReUse:$(-not $ContextPrompt) -EnableException try { if ($newOptions -band [UpdateForestOptions]::Sites) { if (Get-FMSite) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'Sites', $parameters.Server Test-FMSite @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'Sites' } } if ($newOptions -band [UpdateForestOptions]::SiteLinks) { if (Get-FMSiteLink) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'Sitelinks', $parameters.Server Test-FMSiteLink @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'Sitelinks' } } if ($newOptions -band [UpdateForestOptions]::Subnets) { if (Get-FMSubnet) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'Subnets', $parameters.Server Test-FMSubnet @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'Subnets' } } if ($newOptions -band [UpdateForestOptions]::ServerRelocate) { # Requires no configuration, so no check for configuration existence required Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'Server Site Assignment', $parameters.Server Test-FMServer @parameters } if ($newOptions -band [UpdateForestOptions]::Schema) { if (Get-FMSchema) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'Schema (Custom)', $parameters.Server Test-FMSchema @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'Schema (Custom)' } } if ($newOptions -band [UpdateForestOptions]::SchemaDefaultPermissions) { if (Get-FMSchemaDefaultPermission) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'Schema Default Permissions', $parameters.Server Test-FMSchemaDefaultPermission @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'Schema Default Permissions' } } if ($newOptions -band [UpdateForestOptions]::SchemaLdif) { if (Get-FMSchemaLdif) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'Schema (Ldif)', $parameters.Server Test-FMSchemaLdif @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'Schema (Ldif)' } } if ($newOptions -band [UpdateForestOptions]::NTAuthStore) { if (Get-FMNTAuthStore) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'NTAuthStore', $parameters.Server Test-FMNTAuthStore @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'NTAuthStore' } } if ($newOptions -band [UpdateForestOptions]::Certificates) { if (Get-FMCertificate) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'Certificate', $parameters.Server Test-FMCertificate @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'Certificate' } } if ($newOptions -band [UpdateForestOptions]::ForestLevel) { if (Get-FMForestLevel) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'ForestLevel', $parameters.Server Test-FMForestLevel @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'ForestLevel' } } if ($newOptions -band [UpdateForestOptions]::ExchangeSchema) { if (Get-FMExchangeSchema) { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Executing.Test' -StringValues 'ExchangeSchema', $parameters.Server Test-FMExchangeSchema @parameters } else { Write-PSFMessage -Level Host -String 'Test-AdmfForest.Skipping.Test.NoConfiguration' -StringValues 'ExchangeSchema' } } } catch { Write-Error $_ continue } finally { Disable-PSFConsoleInterrupt try { Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential -Cmdlet $PSCmdlet } finally { Enable-PSFConsoleInterrupt } } } } }
Invoke-PostCredentialProvider.ps1
ADMF-1.13.100
function Invoke-PostCredentialProvider { <# .SYNOPSIS Executes the PostScript action of a credential provider. .DESCRIPTION Executes the PostScript action of a credential provider. .PARAMETER ProviderName Name of the credential provider to use. .PARAMETER Server The original server targeted. .PARAMETER Credential The original credentials specified by the user. .PARAMETER Cmdlet The $PSCmdlet object of the calling command. Used to kill it with maximum prejudice in case of error. .EXAMPLE PS C:\> Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential Performs any post-execution action registered for the $CredentialProvider (if any) #> [CmdletBinding()] param ( [string] $ProviderName, [PSFComputer] $Server, [AllowNull()] [PSCredential] $Credential, [System.Management.Automation.PSCmdlet] $Cmdlet = $PSCmdlet ) if (-not $script:credentialProviders[$ProviderName]) { Stop-PSFFunction -String 'Invoke-PostCredentialProvider.Provider.NotFound' -StringValues $ProviderName -EnableException $true -Cmdlet $Cmdlet } if (-not $script:credentialProviders[$ProviderName].PostScript) { return } $argument = [PSCustomObject]@{ Server = $Server Credential = $Credential } try { $null = $script:credentialProviders[$ProviderName].PostScript.Invoke($argument) } catch { Stop-PSFFunction -String 'Invoke-PostCredentialProvider.Provider.ExecutionError' -StringValues $ProviderName -EnableException $true -ErrorRecord $_ -Cmdlet $Cmdlet } }
Invoke-AdmfDomain.ps1
ADMF-1.13.100
function Invoke-AdmfDomain { <# .SYNOPSIS Brings a domain into compliance with the desired state. .DESCRIPTION Brings a domain into compliance with the desired state. It implements a wide variety of settings against the targeed domain, whether it be OUs, groups, users, gpos, acls or many more items. Note on order: - OU Creation and Updating should be done first, but DELETING ous (OUHard) should be one of the last operations performed. - Acl & Access operations should be performed last - Managing group policy yields best results in this order: 1. Create new GPO 2. Create Links, only disabling undesired links 3. Delete unneeded GPO 4. Delete undesired links This is due to the fact that "unneeded GPO" are detected by being linked into managed GPOs. .PARAMETER Server The server / domain to work with. .PARAMETER Credential The credentials to use for this operation. .PARAMETER Options The various operations that are supported. By default "default" operations are executed against the targeted domain. - Acl : The basic permission behavior of an object (e.g.: Owner, Inheritance) - GPLink : Manages the linking of group policies. - GPPermission : Managing permissions on group policy objects. - GroupPolicy : Deploying and updating GPOs. - GroupMembership : Assigning group membership - Group : Creating groups - OUSoft : Creating & modifying OUs, but not deleting them - OUHard : Creating, Modifying & Deleting OUs. This exists in order to be able to create new OUs, then move all objects over and only when done deleting undesired OUs. Will NOT delete OUs that contain objects.! - PSO : Implementing Finegrained Password Policies - Object : Custom AD object - User : Managing User objects - GPLinkDisable : Creating GP Links, but only disabling undesired links. This is needed in order to detect undesired GPOs to delete: Those linked when they shouldn't be! - GroupPolicyDelete : Deploy, update and delete Group Policy objects. .PARAMETER CredentialProvider The credential provider to use to resolve the input credentials. See help on Register-AdmfCredentialProvider for details. .PARAMETER ContextPrompt Force displaying the Context selection User Interface. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .EXAMPLE PS C:\> Invoke-AdmfDomain Brings the current domain into compliance with the desired state. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '')] [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] Param ( [PSFComputer[]] $Server, [PSCredential] $Credential, [ADMF.UpdateDomainOptions[]] $Options = 'Default', [string] $CredentialProvider = 'default', [Alias('Ctx')] [switch] $ContextPrompt ) begin { [ADMF.UpdateDomainOptions]$newOptions = $Options } process { foreach ($computer in $Server) { Reset-DomainControllerCache $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential $parameters.Server = $computer $originalArgument = Invoke-PreCredentialProvider @parameters -ProviderName $CredentialProvider -Parameter $parameters -Cmdlet $PSCmdlet try { $dcServer = Resolve-DomainController @parameters -Confirm:$false } catch { Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential -Cmdlet $PSCmdlet Write-Error $_ continue } $parameters.Server = $dcServer Invoke-PSFCallback -Data $parameters -EnableException $true -PSCmdlet $PSCmdlet Set-AdmfContext @parameters -Interactive -ReUse:$(-not $ContextPrompt) -EnableException $parameters += $PSBoundParameters | ConvertTo-PSFHashtable -Include WhatIf, Confirm, Verbose, Debug $parameters.Server = $dcServer try { if ($newOptions -band [UpdateDomainOptions]::OUSoft) { if (Get-DMOrganizationalUnit) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'OrganizationalUnits - Create & Modify', $parameters.Server Invoke-DMOrganizationalUnit @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'OrganizationalUnits - Create & Modify' } } if ($newOptions -band [UpdateDomainOptions]::Group) { if (Get-DMGroup) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'Groups', $parameters.Server Invoke-DMGroup @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'Groups' } } if ($newOptions -band [UpdateDomainOptions]::User) { if (Get-DMUser) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'Users', $parameters.Server Invoke-DMUser @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'Users' } } if ($newOptions -band [UpdateDomainOptions]::ServiceAccount) { if (Get-DMServiceAccount) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'ServiceAccounts', $parameters.Server Invoke-DMServiceAccount @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'ServiceAccounts' } } if ($newOptions -band [UpdateDomainOptions]::GroupMembership) { if (Get-DMGroupMembership) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'GroupMembership', $parameters.Server Invoke-DMGroupMembership @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'GroupMembership' } } if ($newOptions -band [UpdateDomainOptions]::PSO) { if (Get-DMPasswordPolicy) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'PasswordPolicies', $parameters.Server Invoke-DMPasswordPolicy @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'PasswordPolicies' } } if ($newOptions -band [UpdateDomainOptions]::WmiFilter) { if (Get-DMWmiFilter) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'WmiFilter', $parameters.Server Invoke-DMWmiFilter @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'WmiFilter' } } if ($newOptions -band [UpdateDomainOptions]::GroupPolicy) { if (Get-DMGroupPolicy) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'GroupPolicies - Create & Modify', $parameters.Server Invoke-DMGroupPolicy @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'GroupPolicies - Create & Modify' } } if ($newOptions -band [UpdateDomainOptions]::GPPermission) { if (Get-DMGPPermission) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'GroupPolicyPermissions', $parameters.Server Invoke-DMGPPermission @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'GroupPolicyPermissions' } } if ($newOptions -band [UpdateDomainOptions]::GPOwner) { if (Get-DMGPOwner) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'GroupPolicyOwners', $parameters.Server Invoke-DMGPOwner @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'GroupPolicyOwners' } } if ($newOptions -band [UpdateDomainOptions]::GPLinkDisable) { if (Get-DMGPLink) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'GroupPolicyLinks - Create, Update & Disable unwanted Links', $parameters.Server Invoke-DMGPLink @parameters -Disable } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'GroupPolicyLinks - Create, Update & Disable unwanted Links' } } if ($newOptions -band [UpdateDomainOptions]::GroupPolicyDelete) { if (Get-DMGroupPolicy) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'GroupPolicies - Delete', $parameters.Server Invoke-DMGroupPolicy @parameters -Delete } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'GroupPolicies - Delete' } } if ($newOptions -band [UpdateDomainOptions]::GPLink) { if (Get-DMGPLink) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'GroupPolicyLinks - Delete unwanted Links', $parameters.Server Invoke-DMGPLink @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'GroupPolicyLinks - Delete unwanted Links' } } if ($newOptions -band [UpdateDomainOptions]::OUHard) { if (Get-DMOrganizationalUnit) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'OrganizationalUnits - Delete', $parameters.Server Invoke-DMOrganizationalUnit @parameters -Delete } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'OrganizationalUnits - Delete' } } if ($newOptions -band [UpdateDomainOptions]::Object) { if (Get-DMObject) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'Objects', $parameters.Server Invoke-DMObject @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'Objects' } } if ($newOptions -band [UpdateDomainOptions]::Acl) { if (Get-DMAcl | Remove-PSFNull) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'Acls', $parameters.Server Invoke-DMAcl @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'Acls' } } if ($newOptions -band [UpdateDomainOptions]::AccessRule) { if (Get-DMAccessRule) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'AccessRules', $parameters.Server Invoke-DMAccessRule @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'AccessRules' } } if ($newOptions -band [UpdateDomainOptions]::DomainLevel) { if (Get-DMDomainLevel) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'DomainLevel', $parameters.Server Invoke-DMDomainLevel @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'DomainLevel' } } if ($newOptions -band [UpdateDomainOptions]::Exchange) { if (Get-DMExchange) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Executing.Invoke' -StringValues 'Exchange System Objects', $parameters.Server Invoke-DMExchange @parameters } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' -StringValues 'Exchange System Objects' } } } catch { Write-Error $_ continue } finally { Disable-PSFConsoleInterrupt try { Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential -Cmdlet $PSCmdlet } finally { Enable-PSFConsoleInterrupt } } } } }
license.ps1
ADMF-1.13.100
New-PSFLicense -Product 'ADMF' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-12-20") -Text @" Copyright (c) 2019 Friedrich Weinmann 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. "@
Reset-DomainControllerCache.ps1
ADMF-1.13.100
function Reset-DomainControllerCache { <# .SYNOPSIS Resets the cached domain controller resolution. .DESCRIPTION Resets the cached domain controller resolution. The targeted domain controller is being cached throughout the execution of a single test or invoke to avoid targeting issues between credential providers and the actual execution. .EXAMPLE PS C:\> Reset-DomainControllerCache Resets the cached domain controller resolution. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [CmdletBinding()] param ( ) $script:resolvedDomainController = $null }
Register-AdmfCredentialProvider.ps1
ADMF-1.13.100
function Register-AdmfCredentialProvider { <# .SYNOPSIS Registers a credential provider used by the ADMF. .DESCRIPTION Registers a credential provider used by the ADMF. Credential providers are used for translating the credentials to use for all actions performed against active directory. For example, the ADMF could be extended to support a password safe solution: When connecting to a target domain, this provider scriptblock would retrieve the required credentials from a password safe solution. A credential provider consists of two scriptblocks: - A PreScript that is executed before running any commands. It must return either a PSCredential object (if applicable) or $null (if default windows credentials should be used instead). - A PostScript that is executed after all component commands have been executed. It need not return anything. Both scriptblocks receive a single input object, with two properties: - Server: The computer / domain targeted - Credential: The credentials originally provided (if any - this may be $null instead!) .PARAMETER Name The name of the credential provider. Each name must be unique, registering a provider using an existing name overwrites the previous provider. The provider "default" exists as part of ADMF and will be used if no other is specified. Overriding it allows you to change the default provider intentionally, but may remove your ability to NOT use any credential transformations, so use with care. .PARAMETER PreScript The script to execute before performing actions, in order to resolve the correct credentials to use. - If it returns a credential object, this object will be used for authenticating all AD operations (including WinRM against domain controllers!). - If it returns nothing / only non-credential objects, instead the default windows identity of the user is used. .PARAMETER PostScript This script is executed after performing all actions. You can use this optional script to perform any cleanup actions if necessary. .EXAMPLE PS C:\> Register-AdmfCredentialProvider -Name AZKeyVault -PreScript $keyVaultScript Registers the scriptblock defined in $keyVaultScript as "AZKeyVault" provider. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Name, [Parameter(Mandatory = $true)] [Scriptblock] $PreScript, [Scriptblock] $PostScript ) $script:credentialProviders[$Name] = [PSCustomObject]@{ PSTypeName = 'Admf.CredentialProvider' Name = $Name PreScript = $PreScript PostScript = $PostScript } }
ADMF.psd1
ADMF-1.13.100
@{ # Script module or binary module file associated with this manifest RootModule = 'ADMF.psm1' # Version number of this module. ModuleVersion = '1.13.100' # ID used to uniquely identify this module GUID = '43f2a890-942f-4dd7-bad0-b774b44ea849' # Author of this module Author = 'Friedrich Weinmann' # Company or vendor of this module CompanyName = 'Microsoft' # Copyright statement for this module Copyright = 'Copyright (c) 2019 Friedrich Weinmann' # Description of the functionality provided by this module Description = 'Central Management Component of the Active Directory Management Framework' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '5.1' # Modules that must be imported into the global environment prior to importing # this module RequiredModules = @( @{ ModuleName = 'PSFramework'; ModuleVersion = '1.10.318' } @{ ModuleName = 'ADSec'; ModuleVersion = '1.0.1' } @{ ModuleName = 'string'; ModuleVersion = '1.1.3' } @{ ModuleName = 'ResolveString'; ModuleVersion = '1.0.0' } @{ ModuleName = 'Principal'; ModuleVersion = '1.0.0' } @{ ModuleName = 'ADMF.Core'; ModuleVersion = '1.1.9' } @{ ModuleName = 'DCManagement'; ModuleVersion = '1.2.25' } @{ ModuleName = 'DomainManagement'; ModuleVersion = '1.8.202' } @{ ModuleName = 'ForestManagement'; ModuleVersion = '1.5.73' } ) # Assemblies that must be loaded prior to importing this module RequiredAssemblies = @( 'bin\ADMF.dll' 'System.Windows.Forms' ) # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @('xml\ADMF.Types.ps1xml') # Format files (.ps1xml) to be loaded when importing this module FormatsToProcess = @('xml\ADMF.Format.ps1xml') # Functions to export from this module FunctionsToExport = @( 'Export-AdmfGpo' 'Get-AdmfContext' 'Get-AdmfContextStore' 'Invoke-AdmfDC' 'Invoke-AdmfDomain' 'Invoke-AdmfForest' 'Invoke-AdmfItem' 'New-AdmfContext' 'New-AdmfContextModule' 'New-AdmfContextStore' 'Publish-AdmfContext' 'Register-AdmfCredentialProvider' 'Set-AdmfContext' 'Test-AdmfDC' 'Test-AdmfDomain' 'Test-AdmfForest' ) # Cmdlets to export from this module # CmdletsToExport = '' # Variables to export from this module # VariablesToExport = '' # Aliases to export from this module AliasesToExport = @( 'iai' ) # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ #Support for PowerShellGet galleries. PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @('activedirectory','configuration','admf', 'management') # A URL to the license for this module. LicenseUri = 'https://github.com/ActiveDirectoryManagementFramework/ADMF/blob/master/LICENSE' # A URL to the main website for this project. ProjectUri = 'https://admf.one' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module ReleaseNotes = 'https://github.com/ActiveDirectoryManagementFramework/ADMF/blob/master/ADMF/changelog.md' } # End of PSData hashtable } # End of PrivateData hashtable }
FileIntegrity.Exceptions.ps1
ADMF-1.13.100
# List of forbidden commands $global:BannedCommands = @( 'Write-Host', 'Write-Verbose', 'Write-Warning', 'Write-Error', 'Write-Output', 'Write-Information', 'Write-Debug', # Use CIM instead where possible 'Get-WmiObject', 'Invoke-WmiMethod', 'Register-WmiEvent', 'Remove-WmiObject', 'Set-WmiInstance' ) <# Contains list of exceptions for banned cmdlets. Insert the file names of files that may contain them. Example: "Write-Host" = @('Write-PSFHostColor.ps1','Write-PSFMessage.ps1') #> $global:MayContainCommand = @{ "Write-Host" = @() "Write-Verbose" = @() "Write-Warning" = @() "Write-Error" = @('Test-AdmfDomain.ps1', 'Invoke-AdmfDomain.ps1', 'Test-AdmfForest.ps1', 'Invoke-AdmfForest.ps1') "Write-Output" = @('Set-AdmfContext.ps1') "Write-Information" = @() "Write-Debug" = @() }
New-AdmfContextModule.ps1
ADMF-1.13.100
function New-AdmfContextModule { <# .SYNOPSIS Create an ADMF Client PowerShell module. .DESCRIPTION Create an ADMF Client PowerShell module. Specify which contexts to use from a repository to which they have previously been published. It will then dynamically create a PowerShell module containing all contexts and their dependencies and publish them under its own Context store once imported. .PARAMETER Name Name of the contexts to include. Supports plain "Name" or the PowerShell module notation. Examples: "Default" @{ ModuleName = 'SecBaseline' } @{ ModuleName = 'SecBaseline'; ModuleVersion = '2.0.0' } @{ ModuleName = 'SecBaseline'; RequiredVersion = '2.3.1' } .PARAMETER Repository Name of the repository to download from. .PARAMETER Path Path where to write the finished module to. .PARAMETER ModuleName Name of the module to generate. .PARAMETER ModuleOption Additional options to include in the module code when generating the module. Confirm: Injects all ADMF component modules with the requirement to confirm all changes. .PARAMETER AliasPrefix Create aliases for the common ADMF commands. This simplifies guiding users into loading the module containing their configuration settings. Rather than having them run Test-ADMFDomain, you could have them run Test-ConDomain, which would then implicitly load the generated module and make the contexts available, without having to first manually import the module generated. .PARAMETER ModuleVersion The version of the module to generate. Defaults to 1.0.0 .PARAMETER Credential Credentials to use for accessing the powershell repository. .PARAMETER ModuleCode Additional code to iunclude in the module generated .PARAMETER GetV3 Use PowerShellGet V3 or later. Defaults to the configuration setting of ADMF.PowerShellGet.UseV3. .EXAMPLE PS C:\> New-AdmfContextModule -Name Default -Repository Contoso -Path . -ModuleName Whatever -ModuleOption Confirm -AliasPrefix WE Retrieves the "Default" context from the "Contoso" repository. It will then wrap it into a module named "Whatever", injecting a requirement to confirm all changes and include aliases for the common ADMF commands with the WE prefix (e.g. Test-WEDomain) #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] $Name, [Parameter(Mandatory = $true)] [string] $Repository, [Parameter(Mandatory = $true)] [string] $Path, [Parameter(Mandatory = $true)] [string] $ModuleName, [ValidateSet('Confirm')] [string[]] $ModuleOption = 'Confirm', [string] $AliasPrefix, [version] $ModuleVersion = '1.0.0', [PSCredential] $Credential, [ScriptBlock] $ModuleCode, [switch] $GetV3 ) trap { Remove-PSFTempItem -ModuleName ADMF -Name * throw $_ } # Resolve Target Module Names / Versions $modules = foreach ($entry in $Name) { if ($entry -is [string]) { @{ Name = $entry } } else { $entry | ConvertTo-PSFHashtable Name, ModuleVersion, RequiredVersion } } foreach ($module in $modules) { if ($module.Name -notlike 'ADMF.Context.*') { $module.Name = "ADMF.Context.$($module.Name)" } if ($GetV3) { $module.Remove('ModuleVersion') if ($module.RequiredVersion) { $module.Version = $module.RequiredVersion $module.Remove('RequiredVersion') } } else { if ($module.ModuleVersion) { $module.MinimumVersion = $module.ModuleVersion $module.Remove('ModuleVersion') } } } # Create TEMP folder and deploy them from repository $folder = New-PSFTempDirectory -Name contextpath -ModuleName ADMF $moduleParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Repository, Credential foreach ($module in $modules) { if ($GetV3) { Save-PSResource @moduleParam @module -Path $folder } else { Save-Module @moduleParam @module -Path $folder } } # Create Module & Copy Contexts $moduleRoot = New-PSFTempDirectory -Name moduleroot -ModuleName ADMF -DirectoryName $ModuleName $manifest = @{ Path = "$moduleRoot\$ModuleName.psd1" ModuleVersion = $ModuleVersion RootModule = "$ModuleName.psm1" FunctionsToExport = @() CmdletsToExport = @() AliasesToExport = @() VariablesToExport = @() } if ($AliasPrefix) { $manifest.AliasesToExport = "Invoke-$($aliasPrefix)Forest", "Invoke-$($aliasPrefix)Domain", "Invoke-$($aliasPrefix)DC", "Invoke-$($aliasPrefix)Item", "Test-$($aliasPrefix)Domain", "Test-$($aliasPrefix)DC", "Test-$($aliasPrefix)Forest" } New-ModuleManifest @manifest $null = New-Item -Path $moduleRoot -Name "$ModuleName.psm1" -ItemType File $contextRoot = New-Item -Path $moduleRoot -Name Contexts -ItemType Directory $contextConfig = Get-Item -Path "$folder/*/*/*/*/context.json" $contextPaths = $contextConfig.FullName | Split-Path | Split-Path | Sort-Object -Unique foreach ($contextPath in $contextPaths) { Copy-Item -Path $contextPath -Destination $contextRoot.FullName -Recurse -Force } # Add module content $content = @() ## Register Context Store $content += "Set-PSFConfig -FullName 'ADMF.Context.Store.$ModuleName' -Value `"`$PSScriptRoot\Contexts`"" ## Confirm Preference if ($ModuleOption -contains 'Confirm') { $content += @' # Confirm by default & (Get-Module DCManagement) { $script:ConfirmPreference = 'Low' } & (Get-Module DomainManagement) { $script:ConfirmPreference = 'Low' } & (Get-Module ForestManagement) { $script:ConfirmPreference = 'Low' } '@ } ## Add Alias for the ADMF Commands if ($AliasPrefix) { $content += "`$aliasPrefix = '$aliasPrefix'" $content += @' # Set Aliases for module $aliases = @{ 'Invoke-AdmfDC' = "Invoke-$($aliasPrefix)DC" 'Invoke-AdmfDomain' = "Invoke-$($aliasPrefix)Domain" 'Invoke-AdmfForest' = "Invoke-$($aliasPrefix)Forest" 'Invoke-AdmfItem' = "Invoke-$($aliasPrefix)Item" 'Test-AdmfDC' = "Test-$($aliasPrefix)DC" 'Test-AdmfDomain' = "Test-$($aliasPrefix)Domain" 'Test-AdmfForest' = "Test-$($aliasPrefix)Forest" } foreach ($pair in $aliases.GetEnumerator()) { Set-Alias -Name $pair.Value -Value $pair.Key } '@ } ## Add Custom Code if ($ModuleCode) { $content += $ModuleCode.ToString() } $content | Set-Content -Path "$moduleRoot\$ModuleName.psm1" # Copy to destination Copy-Item -Path $moduleRoot -Destination $Path -Recurse Remove-PSFTempItem -ModuleName ADMF -Name * }
Invoke-CallbackMenu.ps1
ADMF-1.13.100
function Invoke-CallbackMenu { <# .SYNOPSIS Calls a GUI window to pick the contexts for a specific server. .DESCRIPTION Calls a GUI window to pick the contexts for a specific server. This is used when invoking Set-AdmfContext with the (hidden) -Callback parameter. It is designed to be triggered automatically when trying to manage a forest / domain that has not yet had its context defined. Note: This makes it critical to define a context first when doing unattended automation. .PARAMETER Server The server / domain being connected to. Used for documentation purposes, as well as to potentially determine initial checkbox state. .PARAMETER Credential The credentials to use for this operation. .EXAMPLE PS C:\> Invoke-CallbackMenu -Server contoso.com Shows the context selection menu for the domain contoso.com #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Server, [pscredential] $Credential ) begin { #region Utility Functions function New-CheckBox { [CmdletBinding()] param ( $ContextObject, $Parent ) $column = $Parent.Controls.Count % 2 $row = [math]::Truncate(($Parent.Controls.Count / 2)) $checkbox = [System.Windows.Forms.CheckBox]::new() $checkbox.Width = 200 $checkbox.Height = 20 $checkbox.AutoSize = $false $checkbox.Location = [System.Drawing.Point]::new((210 * $column + 15), (25 * $row + 15)) $checkbox.Text = $ContextObject.Name $checkbox.Font = 'Microsoft Sans Serif,10' $null = $Parent.Controls.Add($checkbox) $tooltip = [System.Windows.Forms.ToolTip]::new() $tooltip.ToolTipTitle = $ContextObject.Name $tooltipText = $ContextObject.Description if ($ContextObject.Prerequisites.Count -gt 0) { $tooltipText += "`nPrerequisites: $($ContextObject.Prerequisites -join ', ')" } if ($ContextObject.MutuallyExclusive.Count -gt 0) { $tooltipText += "`nMutually exclusive with: $($ContextObject.MutuallyExclusive -join ', ')" } $tooltip.SetToolTip($checkbox, $tooltipText) $checkbox.Add_CheckedChanged({ Update-Checkbox }) $checkbox } function Update-Checkbox { [CmdletBinding()] param () # Exemption: Accessing superscope variables directly. Forms and their events are screwey enough. foreach ($checkbox in $contextCheckboxes.Values) { $checkbox.Enabled = $true } foreach ($contextObject in $allContexts) { foreach ($prerequisite in $contextObject.Prerequisites) { if (-not $contextCheckboxes[$prerequisite].Checked) { $contextCheckboxes[$contextObject.Name].Enabled = $false $contextCheckboxes[$contextObject.Name].Checked = $false break } } foreach ($exclusion in $contextObject.MutuallyExclusive) { if (-not $contextCheckboxes[$contextObject.Name].Checked) { break } if (-not $contextCheckboxes[$exclusion]) { continue } $contextCheckboxes[$exclusion].Enabled = $false $contextCheckboxes[$exclusion].Checked = $false } } } function New-Form { [OutputType([System.Windows.Forms.Form])] [CmdletBinding()] param () New-Object System.Windows.Forms.Form -Property @{ ClientSize = '500,500' Text = "Context Selection" TopMost = $false AutoSize = $false } } function New-GroupBox { [OutputType([System.Windows.Forms.Groupbox])] [CmdletBinding()] param ( [string] $Text, [int] $Height, $Form ) $newHeight = 10 if ($Form.Controls.Count -gt 0) { $last = $Form.Controls | Sort-Object { $_.Location.Y } -Descending | Select-Object -First 1 $newHeight = 10 + $last.Height + $last.Location.Y } $groupBox = New-Object System.Windows.Forms.Groupbox -Property @{ Height = $Height Width = 480 Text = $Text AutoSize = $false Location = (New-Object System.Drawing.Point(10, $newHeight)) } $Form.Controls.Add($groupBox) $groupBox } function New-Label { [CmdletBinding()] param ( [string] $Text, $Parent ) $label = New-Object system.Windows.Forms.Label -Property @{ Text = $Text AutoSize = $false Font = 'Microsoft Sans Serif,10' Location = (New-Object System.Drawing.Point(10, 15)) Width = 460 TextAlign = 'MiddleCenter' } $Parent.Controls.Add($label) } #endregion Utility Functions $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential #region Form [System.Windows.Forms.Application]::EnableVisualStyles() $form = New-Form $group_Server = New-GroupBox -Text "Selected Domain / Server" -Height 50 -Form $form try { $domain = Get-ADDomain @parameters -ErrorAction Stop New-Label -Text $domain.DNSRoot -Parent $group_Server } catch { New-Label -Text $Server -Parent $group_Server } #region Contexts $allContexts = Get-AdmfContext $groupedContexts = $allContexts | Group-Object Group $contextCheckboxes = @{ } foreach ($groupedContext in $groupedContexts) { $rows = [math]::Round(($groupedContext.Group.Count / 2), [System.MidpointRounding]::AwayFromZero) $group_Context = New-GroupBox -Text $groupedContext.Name -Height ($rows * 25 + 15) -Form $form foreach ($contextObject in ($groupedContext.Group | Sort-Object Name)) { $contextCheckboxes[$contextObject.Name] = New-CheckBox -ContextObject $contextObject -Parent $group_Context } } if ($parameters.Server -eq '<Default Domain>') { $parameters.Server = $env:USERDNSDOMAIN } foreach ($context in $allContexts | Sort-Object Weight) { $path = Join-Path $context.Path 'contextPromptChecked.ps1' if (Test-Path $path) { try { $result = & $path @parameters if ($result) { $contextCheckboxes[$context.Name].Checked = $true } } catch { Write-PSFMessage -Level Warning -String 'Invoke-CallbackMenu.Context.Checked.Error' -StringValues $context.Name -ErrorRecord $_ } } } Update-Checkbox #endregion Contexts #region Buttons $button_Cancel = New-Object system.Windows.Forms.Button -Property @{ Text = 'Cancel' Width = 60 Height = 30 Anchor = 'right,bottom' Location = (New-Object System.Drawing.Point(426, 460)) Font = 'Microsoft Sans Serif,10' } $form.Controls.Add($button_Cancel) $button_OK = New-Object system.Windows.Forms.Button -Property @{ Text = 'OK' Width = 38 Height = 30 Anchor = 'right,bottom' Location = (New-Object System.Drawing.Point(378, 460)) Font = 'Microsoft Sans Serif,10' } $form.Controls.Add($button_OK) #endregion Buttons #region Other Stuff $okbox = [System.Windows.Forms.CheckBox]::new() $okbox.Visible = $false $form.Controls.Add($okbox) $button_OK.Add_Click({ $okbox.Checked = $true $this.Parent.Close() }) $form.ShowIcon = $false $form.CancelButton = $button_Cancel $form.AcceptButton = $button_OK $last = $form.Controls | Where-Object { $_ -is [System.Windows.Forms.Groupbox] } | Sort-Object { $_.Location.Y } -Descending | Select-Object -First 1 $newHeight = 90 + $last.Height + $last.Location.Y $form.Height = $newHeight #endregion Other Stuff #endregion Form } process { $null = $form.ShowDialog() if (-not $okbox.Checked) { throw "Interrupting: User cancelled operation" } $selectedNames = @(($contextCheckboxes.Values | Where-Object Checked).Text) $allContexts | Where-Object Name -In $selectedNames } }
Publish-AdmfContext.ps1
ADMF-1.13.100
function Publish-AdmfContext { <# .SYNOPSIS Publishes a Context as a PowerShell Package. .DESCRIPTION Publishes a Context as a PowerShell Package. This wraps a Context as its own PowerShell module named "ADMF.Context.<ContextName>". It uses the version number in the context.json for the module version. All dependent contexts are declared as a module dependency following the same naming scheme. .PARAMETER Path Path to the Context to publish. .PARAMETER Name Name of the Context to publish. Will search known Context stores for available Contexts. .PARAMETER Store Store to search for the Context to publish. Will search all stores if not otherwise specified. .PARAMETER Version Version of the Context to publish. Will publish the latest version if not specified. .PARAMETER Repository Repository to publish the Context to. .PARAMETER ApiKey API Key of the repository to publish to. Defaults to "Whatever" .PARAMETER GetV3 Use PowerShellGet V3 or later. Defaults to the configuration setting of ADMF.PowerShellGet.UseV3. .EXAMPLE PS C:\> Publish-AdmfContext -Path 'C:\ADMF\Default\1.0.0' -Repository Contoso Publishes the "Default" Context to the Contoso repository #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ParameterSetName = 'Path')] [string] $Path, [Parameter(Mandatory = $true, ParameterSetName = 'Store')] [string] $Name, [Parameter(ParameterSetName = 'Store')] [string] $Store, [Parameter(ParameterSetName = 'Store')] [version] $Version, [Parameter(Mandatory = $true)] [string] $Repository, [string] $ApiKey = 'whatever', [switch] $GetV3 = (Get-PSFConfigValue -FullName ADMF.PowerShellGet.UseV3 -Fallback $false) ) begin { function ConvertTo-Prerequisite { [OutputType([hashtable])] [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] $InputObject ) process { if ($InputObject -is [string]) { return @{ ModuleName = $InputObject } } $InputObject | ConvertTo-PSFHashtable -Include ModuleName, ModuleVersion, RequiredVersion } } } process { trap { Remove-PSFTempItem -ModuleName ADMF -Name * if ($originalPath) { $env:PSModulePath = $originalPath } throw $_ } # Determine Path switch ($PSCmdlet.ParameterSetName) { Path { $contextRoot = $Path } Store { $param = @{ Name = $Name All = $true } if ($Store) { $param.Store = $Store } $context = Get-AdmfContext @param | Where-Object Name -EQ $Name if ($Version) { $context = $context | Where-Object Version -EQ $Version } $context = $context | Sort-Object Version -Descending | Select-Object -First 1 $contextRoot = $context.Path } } # Determine Name, Author, Description, Version & Dependencies $ctxName = Split-Path (Split-Path $contextRoot) -Leaf $configFile = Join-Path $contextRoot 'context.json' $config = Import-PSFPowerShellDataFile -Path $configFile if ($config.Name) { $ctxName = $config.Name } $ctxDescription = $config.Description $ctxAuthor = $config.Author $ctxVersion = $config.Version $requirements = $config.Prerequisites | ForEach-Object { @{ ModuleName = "ADMF.Context.$_" ModuleVersion = '1.0.0' # RequiredVersion = $null } } if ($config.Requirements) { $requirements = $config.Requirements } # Build Dynamic Module $moduleName = "ADMF.Context.$ctxName" $folder = New-PSFTempDirectory -Name context -ModuleName ADMF -DirectoryName $moduleName $null = New-Item -Path $folder -Name "$moduleName.psm1" -ItemType File $param = @{ Path = "$folder\$moduleName.psd1" RootModule = "$moduleName.psm1" Author = $ctxAuthor Description = $ctxDescription ModuleVersion = $ctxVersion FunctionsToExport = @() CmdletsToExport = @() AliasesToExport = @() VariablesToExport = @() } if ($requirements) { $param.RequiredModules = $requirements | ConvertTo-Prerequisite } New-ModuleManifest @param $null = New-Item -Path "$folder\$ctxName\$ctxVersion" -ItemType Directory Copy-Item -Path "$($contextRoot -replace '\\$')\*" -Destination "$folder\$ctxName\$ctxVersion\" -Recurse # Create Temporary Modulepath and prepare dependencies $modulePath = New-PSFTempDirectory -Name modulepath -ModuleName ADMF $originalPath = $env:PSModulePath $env:PSModulePath = '{0};{1}' -f $modulePath, $env:PSModulePath foreach ($requirement in $requirements) { Save-Module -Repository $Repository -Path $modulePath @requirement } # Publish if ($GetV3) { $publish = @{ Repository = $Repository Path = $folder } if ($PSBoundParameters.Keys -contains 'ApiKey') { $publish.APiKey = $ApiKey } Publish-PSResource @publish } else { Publish-Module -Path $folder -Repository $Repository -NuGetApiKey $ApiKey } Remove-PSFTempItem -ModuleName ADMF -Name * $env:PSModulePath = $originalPath } }
initialize.ps1
ADMF-1.13.100
$callbackScript = { [CmdletBinding()] param ( [AllowNull()] $Server, [AllowNull()] $Credential, [AllowNull()] $ForestObject, [AllowNull()] $DomainObject ) $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential if ($parameters.Server -eq '<Default Domain>') { $parameters.Server = $env:USERDNSDOMAIN } Set-AdmfContext @parameters -Interactive -ReUse -EnableException } Register-DMCallback -Name ADMF -ScriptBlock $callbackScript Register-FMCallback -Name ADMF -ScriptBlock $callbackScript $callbackScript2 = { [CmdletBinding()] param ( [Hashtable] $Data ) # If this is a DC Installation command from DC Management and we disabled the prompt in configuration, stop if ($Data.Data.IsDCInstall -and -not (Get-PSFConfigValue -FullName 'ADMF.DCInstall.Context.Prompt.Enable')) { return } $parameters = $Data.Data | ConvertTo-PSFHashtable -Include Server, Credential if ($parameters.Server -eq '<Default Domain>') { $parameters.Server = $env:USERDNSDOMAIN } if (-not $parameters.Server) { $parameters.Server = $env:USERDNSDOMAIN } Set-AdmfContext @parameters -Interactive -ReUse -EnableException -NoDomain:($Data.Data.IsDCInstall -as [bool]) } Register-PSFCallback -Name 'ADMF.ContextPrompt' -ModuleName DCManagement -CommandName '*' -ScriptBlock $callbackScript2 Set-PSFTypeAlias -Mapping @{ 'UpdateDCOptions' = 'ADMF.UpdateDCOptions' 'UpdateDomainOptions' = 'ADMF.UpdateDomainOptions' 'UpdateForestOptions' = 'ADMF.UpdateForestOptions' } Register-AdmfCredentialProvider -Name default -PreScript { param ( $Data ) $Data.Credential } Set-PSFFeature -Name PSFramework.Stop-PSFFunction.ShowWarning -Value $true -ModuleName ADMF $null = Get-Acl -Path $HOME -ErrorAction Ignore
addefault_virtualMachines.psd1
ADMF-1.13.100
@{ Name = 'VirtualMachineObject' ObjectClass = 'serviceConnectionPoint' Property = @('Name') TestScript = { $args[0].Name -eq 'Windows Virtual Machine' } LDAPFilter = '(&(objectCategory=serviceConnectionPoint)(name=Windows Virtual Machine))' }
Export-AdmfGpo.ps1
ADMF-1.13.100
function Export-AdmfGpo { <# .SYNOPSIS Creates an export of GPO objects for use in the Domain Management module. .DESCRIPTION Creates an export of GPO objects for use in the Domain Management module. Use this command to record new GPO data for the module. .PARAMETER Path The path to which to export the GPOs. .PARAMETER GpoObject The GPO objects to export. Only accepts output of Get-GPO .PARAMETER Domain The domain to export from. .PARAMETER ExcludeWmiFilter Do not export WmiFilter assignments of GPOs By default, when exporting GPOs, the associated WMi Filter-Name is also exported .PARAMETER OldExportMode How should this command deal with the folders of previous GPO backups? By default, when detecting the folders of previous GPO backups, this command will prompt the user, whether to continue, stop or delete & continue. Options: + Interactive (default): Ask the user for a choice, defaulting to keep the folders. + Delete: Previous backup folders will be deleted without prompting + Ignore: Previous backup folders will be kept .EXAMPLE PS C:\> Get-GPO -All | Where-Object DisplayName -like 'AD-D-SEC-T0*' | Export-AdmfGpo -Path . Exports all GPOs named like 'AD-D-SEC-T0*' to the current path #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "")] [CmdletBinding()] Param ( [PsfValidateScript('ADMF.Validate.Path', ErrorString = 'ADMF.Validate.Path')] [Parameter(Mandatory = $true)] [string] $Path, [PsfValidateScript('ADMF.Validate.Type.Gpo', ErrorString = 'ADMF.Validate.Type.Gpo')] [Parameter(Mandatory = $true, ValueFromPipeline = $true)] $GpoObject, [string] $Domain = $env:USERDNSDOMAIN, [switch] $ExcludeWmiFilter, [ValidateSet('Interactive', 'Delete', 'Ignore')] [string] $OldExportMode = 'Interactive' ) begin { $resolvedPath = Resolve-PSFPath -Path $Path -Provider FileSystem -SingleItem #region Catch Existing GPO Folders $stop = $false $gpoFolders = Get-ChildItem -LiteralPath $resolvedPath -Directory | Where-Object Name -Match ([psfrgx]::Guid) if ($gpoFolders) { $doDelete = $OldExportMode -eq 'Delete' if ($OldExportMode -eq 'Interactive') { $choice = Get-PSFUserChoice -Caption 'Old GPO Backups Found' -Message "#$(@($gpoFolders).Count) probable GPO Backups have been found in the export path - these could create confusion when trying to add the exported data to the Context, potentially including unneeded folders and their content. What should be done with those folders?" -Options @( 'Ignore' 'Delete' 'Stop' ) if (2 -eq $choice) { $stop = $true return } if (1 -eq $choice) { $doDelete = $true } } if ($doDelete) { $gpoFolders | Remove-Item -Recurse -Force } } #endregion Catch Existing GPO Folders $backupCmd = { Backup-GPO -Path $resolvedPath -Domain $Domain } $backupGPO = $backupCmd.GetSteppablePipeline() $backupGPO.Begin($true) [System.Collections.ArrayList]$gpoData = @() $exportID = [guid]::NewGuid().ToString() } process { if ($stop) { return } foreach ($gpoItem in $GpoObject) { $exportData = $backupGPO.Process(($gpoItem | Select-PSFObject 'ID as GUID')) $data = @{ DisplayName = $gpoItem.DisplayName Description = $gpoItem.Description ID = "{$($exportData.ID.ToString().ToUpper())}" ExportID = $exportID } if (-not $ExcludeWmiFilter -and $gpoItem.WmiFilter.Name) { $data.WmiFilter = $gpoItem.WmiFilter.Name } $null = $gpoData.Add([PSCustomObject]$data) } } end { if ($stop) { return } $backupGPO.End() $gpoData | ConvertTo-Json | Set-Content "$resolvedPath\exportData.json" # Remove hidden attribute, to prevent issues with copy over WinRM foreach ($fsItem in (Get-ChildItem -Path $resolvedPath -Recurse -Force)) { $fsItem.Attributes = $fsItem.Attributes -band [System.IO.FileAttributes]::Directory } } }
configuration.ps1
ADMF-1.13.100
<# 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 'ADMF' -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 'ADMF' -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 'ADMF' -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." Set-PSFConfig -Module 'ADMF' -Name 'DCSelectionMode' -Value 'PDCEmulator' -Initialize -Validation 'DCSelectionMode' -Description 'When executing commands, specifying the domain name will cause the module to resolve to a single DC to work against. This setting governs the algorythm that determines the DC to work against. Either "PDCEmulator", "Site" or "Random" are valid choices. When using site, specify the "ADMF.DCSelection.Site" setting as well to select the site to prefer.' Set-PSFConfig -Module 'ADMF' -Name 'DCSelection.Site' -Value '' -Initialize -Validation 'stringarray' -Description 'When using the "ADMF.DCSelectionMode" in "Site" mode, specifying this setting will pick the site to chose. If there are multiple DCs in the target site, the PDCEmulator will be preferred if present.' Set-PSFConfig -Module 'ADMF' -Name 'DCSelection.Site.Prioritize' -Value $true -Initialize -Validation bool -Description 'When using the "ADMF.DCSelectionMode" in "Site" mode, this setting governs whether all sites are pooled ($false) or whether processed one after the other until a valid DC has been found ($true).' Set-PSFConfig -Module 'ADMF' -Name 'VerboseExecution' -Value $true -Initialize -Validation bool -Handler { if ($args[0]) { $null = New-PSFMessageLevelModifier -Name ADMF_Verbose -Modifier 0 -IncludeModuleName ADMF } else { $null = New-PSFMessageLevelModifier -Name ADMF_Verbose -Modifier 3 -IncludeModuleName ADMF } } -Description 'Enabling this will cause the ADMF module to be more verbose by default' Set-PSFConfig -Module 'ADMF' -Name 'Context.Store.Default' -Value "$(Get-PSFPath -Name AppData)\ADMF\Contexts" -Initialize -Validation string -Description 'The default path in which ADMF will look for configuration contexts. Add additional such paths by declaring additional settings labeled "ADMF.Context.Store.*"' Set-PSFConfig -Module 'ADMF' -Name 'DCInstall.Context.Prompt.Enable' -Value $true -Initialize -Validation 'bool' -Description "Whether the DC installation commands should generate Context selection prompts." Set-PSFConfig -Module 'ADMF' -Name 'PowerShellGet.UseV3' -Value $false -Initialize -Validation bool -Description 'Whether to use PowerShellGet V3 by default or not.'
strings.psd1
ADMF-1.13.100
# This is where the strings go, that are written by # Write-PSFMessage, Stop-PSFFunction or the PSFramework validation scriptblocks @{ 'Invoke-AdmfDC.Executing.Invoke' = 'Performing updates to <c="em">{0}</c> against <c="sub">{1}</c>' # 'Shares', $parameters.Server 'Invoke-AdmfDC.Skipping.Test.NoConfiguration' = 'Skipping updates to <c="em">{0}</c> as there is no configuration data available' # 'Shares' 'Invoke-AdmfDomain.Executing.Invoke' = 'Performing updates to <c="em">{0}</c> against <c="sub">{1}</c>' # 'OrganizationalUnits - Create & Modify', $parameters.Server 'Invoke-AdmfDomain.Skipping.Test.NoConfiguration' = 'Skipping updates to <c="em">{0}</c> as there is no configuration data available' # 'OrganizationalUnits - Create & Modify' 'Invoke-AdmfForest.Executing.Invoke' = 'Performing updates to <c="em">{0}</c> against <c="sub">{1}</c>' # 'Sites', $parameters.Server 'Invoke-AdmfForest.Skipping.Test.NoConfiguration' = 'Skipping updates to <c="em">{0}</c> as there is no configuration data available' # 'Sites' 'Invoke-AdmfItem.Error.BadInput' = 'Invalid input: {0} - Provide objects generated from Test-Admf* commands.' # $result 'Invoke-AdmfItem.Error.Execute' = 'Error processing test results against {0} ({1} total items)' # $resultGroup.Name, $resultGroup.Count 'Invoke-AdmfItem.Error.PostCredentialProvider' = 'Error executing the post script of the credential provider {0} against {1} ({2} total items)' # $CredentialProvider, $resultGroup.Name, $resultGroup.Count 'Invoke-AdmfItem.Error.PrepareContext' = 'Error preparing context for {0} ({1} total items)' # $resultGroup.Name, $resultGroup.Count 'Invoke-AdmfItem.Processing' = '[{0}] Processing {1}, performing "{2}" against "{3}"' # $resultItem.Server, $resultItem.ObjectType, $resultItem.Type, $resultItem.Identity 'Invoke-AdmfItem.Processing.ShouldProcess' = '[{0}] Processing {1}, performing "{2}" against "{3}"' # $resultItem.Server, $resultItem.ObjectType, $resultItem.Type, $resultItem.Identity 'Invoke-CallbackMenu.Context.Checked.Error' = 'Unexpected error when checking whether context {0} should be checked by default' # $context.Name 'Invoke-PostCredentialProvider.Provider.ExecutionError' = 'An error happened when executing the post-script of credential provider {0}' # $ProviderName 'Invoke-PostCredentialProvider.Provider.NotFound' = 'Credential Provider {0} could not be found!' # $ProviderName 'Invoke-PreCredentialProvider.Provider.ExecutionError' = 'An error happened when executing the pre-script of credential provider {0}' # $ProviderName 'Invoke-PreCredentialProvider.Provider.NotFound' = 'Credential Provider {0} could not be found!' # $ProviderName 'New-AdmfContext.Context.AlreadyExists' = 'The context {1} already exists in the desginated path {0}. Use -Force to overwrite it, deleting all previous content.' # $resolvedPath, $Name 'New-AdmfContext.Context.AlreadyExists2' = 'The context {1} already exists in the desginated context store "{0}". Use -Force to overwrite it, deleting all previous content.' # $Store, $Name 'Resolve-DomainController.Connecting' = 'Resolving domain controller to use for connecting to {0}' # $targetString 'Resolve-DomainController.Resolved' = 'Resolved domain controller to use. Operating against {0}' # $domainController.HostName 'Set-AdmfContext.Context.Ambiguous' = 'Ambiguous context resolution for {0}. The following contexts would match: {1}' # $contextObject, ($foundContext.Name -join ", ") 'Set-AdmfContext.Context.Applying' = 'Applying context: {0}' # $ContextObject.Name 'Set-AdmfContext.Context.Error.DCConfig' = 'Error parsing DC configuration file for context {0}' # $ContextObject.Name 'Set-AdmfContext.Context.Error.DomainConfig' = 'Error loading domain configuration | Context: {0} | Object Type: {1} | File: {2}' # $ContextObject.Name, $key, $file.FullName 'Set-AdmfContext.Context.Error.ForestConfig' = 'Error loading forest configuration | Context: {0} | Object Type: {1} | File: {2}' # $ContextObject.Name, $key, $file.FullName 'Set-AdmfContext.Context.Error.PostImport' = 'Error executing post-import script for context {0}' # $ContextObject.Name 'Set-AdmfContext.Context.Error.PreImport' = 'Error executing pre-import script for context {0}' # $ContextObject.Name 'Set-AdmfContext.Context.InvalidInput' = 'Invalid context input: {0} of type {1}. Either provide a name (as string) or a context object returned by Get-AdmfContext' # $contextObject, $contextObject.GetType().FullName 'Set-AdmfContext.Context.Loading' = 'Processing configuration file | Context: {0} | Object Type: {1} | File: {2}' # $ContextObject.Name, $key, $file.FullName 'Set-AdmfContext.Context.NotFound' = 'Unable to find ccontext: {0}' # $contextObject 'Set-AdmfContext.Domain.AccessError' = 'Failed to connect to {0} via ADWS' # $Server 'Set-AdmfContext.Interactive.Cancel' = 'Interactive prompt cancelled by user' # 'Set-AdmfContext.Resolution.ExclusionConflict' = 'Unable to process contexts, as a conflict between contexts has been detected: {0}' # ($conflictingContexts.Name -join ", ") 'Set-AdmfContext.Resolution.MissingPrerequisites' = 'Unable to process contexts, as a required prerequisite is missing: {0}' # ($missingPrerequisites -join ", ") 'Test-AdmfDC.Executing.Test' = 'Executing tests to verify <c="em">{0}</c> against <c="sub">{1}</c>' # 'Shares', $parameters.Server 'Test-AdmfDC.Skipping.Test.NoConfiguration' = 'Skipping tests to verify <c="em">{0}</c> as there is no configuration data available' # 'Shares' 'Test-AdmfDomain.Executing.Test' = 'Executing tests to verify <c="em">{0}</c> against <c="sub">{1}</c>' # 'OrganizationalUnits', $parameters.Server 'Test-AdmfDomain.Skipping.Test.NoConfiguration' = 'Skipping tests to verify <c="em">{0}</c> as there is no configuration data available' # 'OrganizationalUnits' 'Test-AdmfForest.Executing.Test' = 'Executing tests to verify <c="em">{0}</c> against <c="sub">{1}</c>' # 'Sites', $parameters.Server 'Test-AdmfForest.Skipping.Test.NoConfiguration' = 'Skipping tests to verify <c="em">{0}</c> as there is no configuration data available' # 'Sites' 'Validate.ContextStore.ExistsNot' = 'Context store already exists: {0}' # <user input>, <validation item> 'Validate.Path' = 'Path does not exist: {0}' # <user input>, <validation item> 'Validate.Path.Folder' = 'Path does not exist or is not a folder: {0}' # <user input>, <validation item> 'Validate.Pattern.ContextName' = 'Not a legal context name: {0}. Only use letters, numbers, underscore, dot or dash' # <user input>, <validation item> 'Validate.Pattern.ContextStoreName' = 'Not a legal context store name: {0}. Only use letters, numbers, underscore, dot or dash' # <user input>, <validation item> 'Validate.Type.Gpo' = 'Input is not a GPO object: {0}' # <user input>, <validation item> }
Invoke-AdmfDC.ps1
ADMF-1.13.100
function Invoke-AdmfDC { <# .SYNOPSIS Brings all DCs of the target domain into the desired/defined state. .DESCRIPTION Brings all DCs of the target domain into the desired/defined state. .PARAMETER Server The server / domain to work with. .PARAMETER Credential The credentials to use for this operation. .PARAMETER TargetServer The specific server(s) to process. If specified, only listed domain controllers will be affected. Specify the full FQDN of the server. .PARAMETER Options Which aspects to actually update. By default, all Components are applied. .PARAMETER CredentialProvider The credential provider to use to resolve the input credentials. See help on Register-AdmfCredentialProvider for details. .PARAMETER ContextPrompt Force displaying the Context selection User Interface. .PARAMETER Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. .EXAMPLE PS C:\> Invoke-AdmfDC -Server corp.contoso.com Brings all DCs of the domain corp.contoso.com into the desired/defined state. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '')] [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param ( [PSFComputer] $Server, [PSCredential] $Credential, [string[]] $TargetServer = @(), [ADMF.UpdateDCOptions[]] $Options = 'Default', [string] $CredentialProvider = 'default', [Alias('Ctx')] [switch] $ContextPrompt ) begin { Reset-DomainControllerCache $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential if (-not $Server -and $TargetServer) { $parameters.Server = $TargetServer | Select-Object -First 1 } $originalArgument = Invoke-PreCredentialProvider @parameters -ProviderName $CredentialProvider -Parameter $parameters -Cmdlet $PSCmdlet try { $dcServer = Resolve-DomainController @parameters -Confirm:$false } catch { Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential -Cmdlet $PSCmdlet throw } $parameters.Server = $dcServer Invoke-PSFCallback -Data $parameters -EnableException $true -PSCmdlet $PSCmdlet Set-AdmfContext @parameters -Interactive -ReUse:$(-not $ContextPrompt) -EnableException $parameters += $PSBoundParameters | ConvertTo-PSFHashtable -Include WhatIf, Confirm, Verbose, Debug $parameters.Server = $dcServer [ADMF.UpdateDCOptions]$newOptions = $Options } process { try { if ($newOptions -band [ADMF.UpdateDCOptions]::Share) { if (Get-DCShare) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDC.Executing.Invoke' -StringValues 'Shares', $parameters.Server Invoke-DCShare @parameters -TargetServer $TargetServer } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDC.Skipping.Test.NoConfiguration' -StringValues 'Shares' } } if ($newOptions -band [ADMF.UpdateDCOptions]::FSAccessRule) { if (Get-DCAccessRule) { Write-PSFMessage -Level Host -String 'Invoke-AdmfDC.Executing.Invoke' -StringValues 'FSAccessRules', $parameters.Server Invoke-DCAccessRule @parameters -TargetServer $TargetServer } else { Write-PSFMessage -Level Host -String 'Invoke-AdmfDC.Skipping.Test.NoConfiguration' -StringValues 'FSAccessRules' } } } catch { throw } finally { Disable-PSFConsoleInterrupt try { Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential -Cmdlet $PSCmdlet } finally { Enable-PSFConsoleInterrupt } } } }
Test-AdmfDC.ps1
ADMF-1.13.100
function Test-AdmfDC { <# .SYNOPSIS Tests whether all DCs in the target domain are in the desired state. .DESCRIPTION Tests whether all DCs in the target domain are in the desired state. .PARAMETER Server The server / domain to work with. .PARAMETER Credential The credentials to use for this operation. .PARAMETER TargetServer The specific server(s) to process. If specified, only listed domain controllers will be affected. Specify the full FQDN of the server. .PARAMETER Options What tests to execute. Defaults to all tests. .PARAMETER CredentialProvider The credential provider to use to resolve the input credentials. See help on Register-AdmfCredentialProvider for details. .PARAMETER ContextPrompt Force displaying the Context selection User Interface. .EXAMPLE PS C:\> Test-AdmfDC Tests the current domain's DCs whether they are compliant with the desired/defined state #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '')] [CmdletBinding()] param ( [PSFComputer] $Server, [PSCredential] $Credential, [string[]] $TargetServer = @(), [UpdateDCOptions[]] $Options = 'All', [string] $CredentialProvider = 'default', [Alias('Ctx')] [switch] $ContextPrompt ) begin { Reset-DomainControllerCache $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential if (-not $Server -and $TargetServer) { $parameters.Server = $TargetServer | Select-Object -First 1 } $originalArgument = Invoke-PreCredentialProvider @parameters -ProviderName $CredentialProvider -Parameter $parameters -Cmdlet $PSCmdlet try { $parameters.Server = Resolve-DomainController @parameters -ErrorAction Stop -Confirm:$false } catch { Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential -Cmdlet $PSCmdlet throw } Invoke-PSFCallback -Data $parameters -EnableException $true -PSCmdlet $PSCmdlet Set-AdmfContext @parameters -Interactive -ReUse:$(-not $ContextPrompt) -EnableException [UpdateDCOptions]$newOptions = $Options } process { try { if ($newOptions -band [UpdateDCOptions]::Share) { if (Get-DCShare) { Write-PSFMessage -Level Host -String 'Test-AdmfDC.Executing.Test' -StringValues 'Shares', $parameters.Server Test-DCShare @parameters -TargetServer $TargetServer } else { Write-PSFMessage -Level Host -String 'Test-AdmfDC.Skipping.Test.NoConfiguration' -StringValues 'Shares' } } if ($newOptions -band [UpdateDCOptions]::FSAccessRule) { if (Get-DCAccessRule) { Write-PSFMessage -Level Host -String 'Test-AdmfDC.Executing.Test' -StringValues 'FSAccessRules', $parameters.Server Test-DCAccessRule @parameters -TargetServer $TargetServer } else { Write-PSFMessage -Level Host -String 'Test-AdmfDC.Skipping.Test.NoConfiguration' -StringValues 'FSAccessRules' } } } catch { throw } finally { Disable-PSFConsoleInterrupt try { Invoke-PostCredentialProvider -ProviderName $CredentialProvider -Server $originalArgument.Server -Credential $originalArgument.Credential -Cmdlet $PSCmdlet } finally { Enable-PSFConsoleInterrupt } } } }
FileIntegrity.Tests.ps1
ADMF-1.13.100
$moduleRoot = (Resolve-Path "$global:testroot\..").Path . "$global:testroot\general\FileIntegrity.Exceptions.ps1" Describe "Verifying integrity of module files" { BeforeAll { function Get-FileEncoding { <# .SYNOPSIS Tests a file for encoding. .DESCRIPTION Tests a file for encoding. .PARAMETER Path The file to test #> [CmdletBinding()] Param ( [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [Alias('FullName')] [string] $Path ) if ($PSVersionTable.PSVersion.Major -lt 6) { [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path } else { [byte[]]$byte = Get-Content -AsByteStream -ReadCount 4 -TotalCount 4 -Path $Path } if ($byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf) { 'UTF8 BOM' } elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff) { 'Unicode' } elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff) { 'UTF32' } elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76) { 'UTF7' } else { 'Unknown' } } } Context "Validating PS1 Script files" { $allFiles = Get-ChildItem -Path $moduleRoot -Recurse | Where-Object Name -like "*.ps1" | Where-Object FullName -NotLike "$moduleRoot\tests\*" foreach ($file in $allFiles) { $name = $file.FullName.Replace("$moduleRoot\", '') It "[$name] Should have UTF8 encoding with Byte Order Mark" -TestCases @{ file = $file } { Get-FileEncoding -Path $file.FullName | Should -Be 'UTF8 BOM' } It "[$name] Should have no trailing space" -TestCases @{ file = $file } { ($file | Select-String "\s$" | Where-Object { $_.Line.Trim().Length -gt 0}).LineNumber | Should -BeNullOrEmpty } $tokens = $null $parseErrors = $null $ast = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$tokens, [ref]$parseErrors) It "[$name] Should have no syntax errors" -TestCases @{ parseErrors = $parseErrors } { $parseErrors | Should -BeNullOrEmpty } foreach ($command in $global:BannedCommands) { if ($global:MayContainCommand["$command"] -notcontains $file.Name) { It "[$name] Should not use $command" -TestCases @{ tokens = $tokens; command = $command } { $tokens | Where-Object Text -EQ $command | Should -BeNullOrEmpty } } } } } Context "Validating help.txt help files" { $allFiles = Get-ChildItem -Path $moduleRoot -Recurse | Where-Object Name -like "*.help.txt" | Where-Object FullName -NotLike "$moduleRoot\tests\*" foreach ($file in $allFiles) { $name = $file.FullName.Replace("$moduleRoot\", '') It "[$name] Should have UTF8 encoding" -TestCases @{ file = $file } { Get-FileEncoding -Path $file.FullName | Should -Be 'UTF8 BOM' } It "[$name] Should have no trailing space" -TestCases @{ file = $file } { ($file | Select-String "\s$" | Where-Object { $_.Line.Trim().Length -gt 0 } | Measure-Object).Count | Should -Be 0 } } } }
addefault_serviceAccount.psd1
ADMF-1.13.100
@{ Name = 'serviceAccount' ObjectClass = 'msDS-GroupManagedServiceAccount' Property = @('Name') TestScript = { $args[0].ObjectClass -eq 'msDS-GroupManagedServiceAccount' } LDAPFilter = '(objectCategory=msDS-GroupManagedServiceAccount)' }
addefault_sysvolSubscription.psd1
ADMF-1.13.100
@{ Name = 'sysvolSubscription' ObjectClass = 'msDFSR-Subscription' Property = @('cn') TestScript = { $args[0].CN -eq 'SYSVOL Subscription' } LDAPFilter = '(&(objectCategory=serviceConnectionPoint)(cn=SYSVOL Subscription))' }
Get-AdmfContext.ps1
ADMF-1.13.100
function Get-AdmfContext { <# .SYNOPSIS Return available contexts. .DESCRIPTION Return available contexts. By default, only the latest version of any given context will be returned. .PARAMETER Name The name of the context to filter by. .PARAMETER Store The context stores to look in. .PARAMETER All Return all versions of any given context, rather than just the latest version. .PARAMETER Current Displays the currently active contexts. .PARAMETER Importing Return the contexts that are currently being imported. Use this to react from within your context's scriptblocks to any other context that is selected. This parameter only has meaning when used within a context's scriptblocks. .PARAMETER DomainTable Return a list of which target domain has which contexts assigned in cache. .EXAMPLE PS C:\> Get-AdmfContext Returns the latest version of all available contexts. #> [CmdletBinding(DefaultParameterSetName = 'Search')] param ( [Parameter(ParameterSetName = 'Search')] [string] $Name = '*', [Parameter(ParameterSetName = 'Search')] [string] $Store = '*', [Parameter(ParameterSetName = 'Search')] [switch] $All, [Parameter(ParameterSetName = 'Current')] [switch] $Current, [Parameter(ParameterSetName = 'Importing')] [switch] $Importing, [Parameter(ParameterSetName = 'Server')] [switch] $DomainTable ) process { if ($Current) { return $script:loadedContexts } if ($DomainTable) { return $script:assignedContexts.Clone() } if ($Importing) { return (Get-PSFTaskEngineCache -Module ADMF -Name currentlyImportingContexts) } $contextStores = Get-AdmfContextStore -Name $Store $allContextData = foreach ($contextStore in $contextStores) { if (-not (Test-Path $contextStore.Path)) { continue } foreach ($folder in (Get-ChildItem -Path $contextStore.Path -Filter $Name -Directory)) { $versionFolders = Get-ChildItem -Path $folder.FullName -Directory | Where-Object { $_.Name -as [version] } | Sort-Object { [version]$_.Name } -Descending if (-not $All) { $versionFolders = $versionFolders | Select-Object -First 1 } foreach ($versionFolder in $versionFolders) { $resultObject = [pscustomobject]@{ PSTypeName = 'ADMF.Context' Name = $folder.Name Version = ($versionFolder.Name -as [version]) Store = $contextStore.Name Path = $versionFolder.FullName Description = '' Weight = 50 Author = '' Prerequisites = @() MutuallyExclusive = @() Group = 'Default' } if (Test-Path -Path "$($versionFolder.FullName)\context.json") { $contextData = Get-Content -Path "$($versionFolder.FullName)\context.json" | ConvertFrom-Json if ($contextData.Weight -as [int]) { $resultObject.Weight = $contextData.Weight -as [int] } if ($contextData.Description) { $resultObject.Description = $contextData.Description } if ($contextData.Author) { $resultObject.Author = $contextData.Author } if ($contextData.Prerequisites) { $resultObject.Prerequisites = $contextData.Prerequisites } if ($contextData.MutuallyExclusive) { $resultObject.MutuallyExclusive = $contextData.MutuallyExclusive } if ($contextData.Group) { $resultObject.Group = $contextData.Group } } $resultObject } } } if ($All) { return $allContextData } # Only return highest version if -All has not been set # The same context name might be stored in multiple stores $allContextData | Group-Object Name | ForEach-Object { $_.Group | Sort-Object Version -Descending | Select-Object -First 1 | Select-PSFObject -TypeName 'ADMF.Context' } } }
preImport.ps1
ADMF-1.13.100
# Scriptfile that is executed BEFORE the context resources are applied # Optional, delete file if not needed for performance benefit param ( [PSFComputer] $Server, [System.Management.Automation.PSCredential] $Credential )
strings.Exceptions.ps1
ADMF-1.13.100
$exceptions = @{ } <# A list of entries that MAY be in the language files, without causing the tests to fail. This is commonly used in modules that generate localized messages straight from C#. Specify the full key as it is written in the language files, do not prepend the modulename, as you would have to in C# code. Example: $exceptions['LegalSurplus'] = @( 'Exception.Streams.FailedCreate' 'Exception.Streams.FailedDispose' ) #> $exceptions['LegalSurplus'] = @( ) $exceptions
assignment.ps1
ADMF-1.13.100
<# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name ADMF.alcohol #> Register-PSFTeppArgumentCompleter -Command New-AdmfContext -Parameter Store -Name 'ADMF.Context.Store'
postimport.ps1
ADMF-1.13.100
# Add all things you want to run after importing the main code # Load Configuration Validations foreach ($file in (Get-ChildItem "$($script:ModuleRoot)\internal\configurationValidation\*.ps1" -ErrorAction Ignore)) { . Import-ModuleFile -Path $file.FullName } # Load Configurations foreach ($file in (Get-ChildItem "$($script:ModuleRoot)\internal\configurations\*.ps1" -ErrorAction Ignore)) { . Import-ModuleFile -Path $file.FullName } # Load Scriptblocks foreach ($file in (Get-ChildItem "$($script:ModuleRoot)\internal\scriptblocks\*.ps1" -ErrorAction Ignore)) { . Import-ModuleFile -Path $file.FullName } # Load Tab Expansion foreach ($file in (Get-ChildItem "$($script:ModuleRoot)\internal\tepp\*.tepp.ps1" -ErrorAction Ignore)) { . Import-ModuleFile -Path $file.FullName } # Load Tab Expansion Assignment . Import-ModuleFile -Path "$($script:ModuleRoot)\internal\tepp\assignment.ps1" # Load License . Import-ModuleFile -Path "$($script:ModuleRoot)\internal\scripts\license.ps1" # Load Variables . Import-ModuleFile -Path "$($script:ModuleRoot)\internal\scripts\variables.ps1" # Initialize some content . Import-ModuleFile -Path "$($script:ModuleRoot)\internal\scripts\initialize.ps1"
Set-AdmfContext.ps1
ADMF-1.13.100
function Set-AdmfContext { <# .SYNOPSIS Applies a set of configuration contexts. .DESCRIPTION Applies a set of configuration contexts. This merges the settings from all selected contexts into one configuration set. .PARAMETER Context Name of context or full context object to apply. .PARAMETER Interactive Show an interactive context selection prompt. This is designed for greater convenience when managing many forests. The system automatically uses Set-AdmfContext with this parameter when directly testing or invoking against a new domain without first selecting a context to apply. .PARAMETER ReUse ADMF remembers the last contexts assigned to a specific server/domain. By setting this parameter, it will re-use those contexts, rather than show the prompt again. This parameter is used by the system to prevent prompting automatically on each call. .PARAMETER DefineOnly Do not actually switch configuration sets. Just register the selected Contexts to the target domain, after validating the selection. .PARAMETER Server The server / domain to work with. .PARAMETER Credential The credentials to use for this operation. .PARAMETER DnsDomain The DNS Name of the domain to target. Removes the need for AD Resolution of the domain, potentially speeding up the -DefineOnly workflow. .PARAMETER NoDomain If used against a target without a domain, it will skip AD connect and instead use the server name for Context caching purposes. .PARAMETER EnableException This parameters disables user-friendly warnings and enables the throwing of exceptions. This is less user friendly, but allows catching exceptions in calling scripts. .EXAMPLE PS C:\> Set-AdmfContext -Interactive Interactively pick to select the contexts to apply to the user's own domain. .EXAMPLE PS C:\> Set-AdmfContext -Interactive -Server contoso.com Interactively pick to select the contexts to apply to the contoso.com domain. .EXAMPLE PS C:\> Set-AdmfContext -Context Default, Production, Europe -Server eu.contoso.com Configures the contexts Default, Production and Europe to be applied to eu.contoso.com. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding(DefaultParameterSetName = 'name')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'name')] [Alias('Name')] [object[]] $Context, [Parameter(ParameterSetName = 'interactive')] [switch] $Interactive, [switch] $ReUse, [switch] $DefineOnly, [PSFComputer] $Server = $env:USERDNSDOMAIN, [System.Management.Automation.PSCredential] $Credential, [string] $DnsDomain, [Parameter(DontShow = $true)] [switch] $NoDomain, [switch] $EnableException ) begin { #region Utility Functions function Set-Context { [CmdletBinding()] param ( $ContextObject, [string] $Server, [System.Management.Automation.PSCredential] $Credential, [System.Management.Automation.PSCmdlet] $Cmdlet, [bool] $EnableException ) Write-PSFMessage -String 'Set-AdmfContext.Context.Applying' -StringValues $ContextObject.Name -Target $ContextObject $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential $stopParam = @{ EnableException = $EnableException Cmdlet = $Cmdlet Target = $ContextObject StepsUpward = 1 } #region PreImport if (Test-Path "$($ContextObject.Path)\preImport.ps1") { try { $null = & "$($ContextObject.Path)\preImport.ps1" @parameters } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.PreImport' -StringValues $ContextObject.Name -ErrorRecord $_ return } } #endregion PreImport #region Forest $forestFields = @{ 'exchangeschema' = Get-Command Register-FMExchangeSchema 'schema' = Get-Command Register-FMSchema 'schemaDefaultPermissions' = Get-Command Register-FMSchemaDefaultPermission 'servers' = Get-Command Register-FMServer 'sitelinks' = Get-Command Register-FMSiteLink 'sites' = Get-Command Register-FMSite 'subnets' = Get-Command Register-FMSubnet } foreach ($key in $forestFields.Keys) { if (-not (Test-Path "$($ContextObject.Path)\forest\$key")) { continue } foreach ($file in (Get-ChildItem "$($ContextObject.Path)\forest\$key\" -Recurse | Where-Object Extension -In ".json", '.psd1')) { Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, $key, $file.FullName try { foreach ($dataSet in (Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop | Write-Output | ConvertTo-PSFHashtable -Include $($forestFields[$key].Parameters.Keys))) { if ($forestFields[$key].Parameters.Keys -contains 'ContextName') { $dataSet['ContextName'] = $ContextObject.Name } & $forestFields[$key] @dataSet -ErrorAction Stop } } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, $key, $file.FullName -ErrorRecord $_ return } } } if (Test-Path "$($ContextObject.Path)\forest\schemaldif") { $filesProcessed = @() #region Process Ldif Configuration foreach ($file in (Get-ChildItem "$($ContextObject.Path)\forest\schemaldif\" -Recurse | Where-Object Extension -In ".json", '.psd1')) { $jsonData = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe foreach ($jsonEntry in $jsonData) { $targetPath = Join-Path "$($ContextObject.Path)\forest\schemaldif" $jsonEntry.Path if ($filesProcessed -contains $targetPath) { continue } try { $ldifItem = Get-Item -Path $targetPath -ErrorAction Stop -Force } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, 'Schema (ldif)', $file.FullName -ErrorRecord $_ return } $ldifParam = @{ Path = $ldifItem.FullName Name = $ldifItem.BaseName ContextName = $ContextObject.Name } if ($jsonEntry.Name) { $ldifParam.Name = $jsonEntry.Name } if ($jsonEntry.Weight) { $ldifParam['Weight'] = $jsonEntry.Weight } if ($jsonEntry.MissingObjectExemption) { $ldifParam['MissingObjectExemption'] = $jsonEntry.MissingObjectExemption } try { Register-FMSchemaLdif @ldifParam -ErrorAction Stop $filesProcessed += $ldifItem.FullName } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, 'schemaldif', $file.FullName -ErrorRecord $_ return } } } #endregion Process Ldif Configuration #region Process Ldif Files without configuration foreach ($file in (Get-ChildItem "$($ContextObject.Path)\forest\schemaldif\" -Recurse -Filter "*.ldf")) { # Skip files already defined in json if ($filesProcessed -contains $file.FullName) { continue } try { Register-FMSchemaLdif -Name $file.BaseName -Path $file.FullName -ContextName $ContextObject.Name -ErrorAction Stop } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, 'schemaldif', $file.FullName -ErrorRecord $_ return } } #endregion Process Ldif Files without configuration } # Forest Level $forestLevelPath = Resolve-DataFile -Path "$($ContextObject.Path)\forest\forest_level" if ($forestLevelPath) { $file = Get-Item -Path $forestLevelPath Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, 'ForestLevel', $file.FullName try { $dataSet = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop Register-FMForestLevel -Level $dataSet.Level -ContextName $ContextObject.Name } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, 'ForestLevel', $file.FullName -ErrorRecord $_ return } } #region NTAuthStore if (Test-Path "$($ContextObject.Path)\forest\ntAuthStore") { foreach ($file in (Get-ChildItem "$($ContextObject.Path)\forest\ntAuthStore" -Recurse -File)) { switch ($file.Extension) { { $_ -in '.json', '.psd1' } { Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, 'NTAuthStore', $file.FullName try { $jsonData = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop if ($jsonData.PSObject.Properties.Name -eq 'Authorative') { Register-FMNTAuthStore -Authorative:$jsonData.Authorative } } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, 'NTAuthStore', $file.FullName -ErrorRecord $_ return } } '.cer' { Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, 'NTAuthStore', $file.FullName try { $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromCertFile($file.FullName) Register-FMNTAuthStore -Certificate $cert } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, 'NTAuthStore', $file.FullName -ErrorRecord $_ return } } } } } #endregion NTAuthStore #region Certificates if (Test-Path "$($ContextObject.Path)\forest\certificates") { foreach ($file in (Get-ChildItem "$($ContextObject.Path)\forest\certificates" -Recurse -File)) { switch ($file.Extension) { { $_ -in '.json', '.psd1' } { Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, 'Certificates', $file.FullName try { $jsonData = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop foreach ($deletion in $jsonData.Delete) { Register-FMCertificate -Remove $deletion.Thumbprint -Type $deletion.Type -ContextName $ContextObject.Name } foreach ($addition in $jsonData.Add) { Register-FMCertificate -Certificate ($addition.Certificate | ConvertFrom-PSFClixml) -Type $addition.Type -ContextName $ContextObject.Name } foreach ($authority in $jsonData.Authority) { Register-FMCertificate -Type $authority.Type -Authorative $authority.Authorative } } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, 'Certificates', $file.FullName -ErrorRecord $_ return } } '.cer' { Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, 'Certificates', $file.FullName try { switch -regex ($file.Name) { '^NTAuthCA' { $type = 'NTAuthCA' } '^RootCA' { $type = 'RootCA' } '^SubCA' { $type = 'SubCA' } '^CrossCA' { $type = 'CrossCA' } '^KRA' { $type = 'KRA' } default { throw "Bad filename, cannot divine certificate type: $($file.Name)" } } $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromCertFile($file.FullName) Register-FMCertificate -Certificate $cert -Type $type -ContextName $ContextObject.Name } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, 'Certificates', $file.FullName -ErrorRecord $_ return } } } } } #endregion Certificates #endregion Forest #region Domain $domainFields = @{ 'organizationalunits' = Get-Command Register-DMOrganizationalUnit 'accessrules' = Get-Command Register-DMAccessRule 'accessrulemodes' = Get-Command Register-DMAccessRuleMode 'acls' = Get-Command Register-DMAcl 'builtinsids' = Get-Command Register-DMBuiltInSID 'exchange' = Get-Command Register-DMExchange 'gplinks' = Get-Command Register-DMGPLink 'gpowners' = Get-Command Register-DMGPOwner 'gppermissions' = Get-Command Register-DMGPPermission 'gppermissionfilters' = Get-Command Register-DMGPPermissionFilter 'gpregistrysettings' = Get-Command Register-DMGPRegistrySetting 'groups' = Get-Command Register-DMGroup 'groupmemberships' = Get-Command Register-DMGroupMembership 'names' = Get-Command Register-DMNameMapping 'objects' = Get-Command Register-DMObject 'psos' = Get-Command Register-DMPasswordPolicy 'serviceaccounts' = Get-Command Register-DMServiceAccount 'users' = Get-Command Register-DMUser 'wmifilter' = Get-Command Register-DMWmiFilter } foreach ($key in $domainFields.Keys) { if (-not (Test-Path "$($ContextObject.Path)\domain\$key")) { continue } foreach ($file in (Get-ChildItem "$($ContextObject.Path)\domain\$key\" -Recurse | Where-Object Extension -In '.json', '.psd1')) { Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, $key, $file.FullName try { foreach ($dataSet in (Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop | Write-Output | ConvertTo-PSFHashtable -Include $($domainFields[$key].Parameters.Keys))) { if ($domainFields[$key].Parameters.Keys -contains 'ContextName') { $dataSet['ContextName'] = $ContextObject.Name } & $domainFields[$key] @dataSet -ErrorAction Stop } } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.DomainConfig' -StringValues $ContextObject.Name, $key, $file.FullName -ErrorRecord $_ return } } } # Group Policy $exportDataPath = Resolve-DataFile -Path "$($ContextObject.Path)\domain\grouppolicies\exportData" if ($exportDataPath) { $file = Get-Item $exportDataPath Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, 'Group Policy', $file.FullName try { $dataSet = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop | ConvertTo-PSFHashtable -Include DisplayName, Description, ID, ExportID, WMiFilter, MayModify foreach ($policyEntry in $dataSet) { Register-DMGroupPolicy @policyEntry -Path "$($ContextObject.Path)\domain\grouppolicies\$($policyEntry.ID)" -ContextName $ContextObject.Name } } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.DomainConfig' -StringValues $ContextObject.Name, 'Group Policy', $file.FullName -ErrorRecord $_ return } } # Object Categories foreach ($file in (Get-ChildItem "$($ContextObject.Path)\domain\objectcategories" -Filter '*.psd1' -ErrorAction Ignore)) { try { $dataSet = Import-PSFPowerShellDataFile -Path $file.FullName $dataSet.TestScript = $dataSet.TestScript.Invoke() | Write-Output # Remove automatic scriptblock nesting Register-DMObjectCategory @dataSet -ContextName $ContextObject.Name } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.DomainConfig' -StringValues $ContextObject.Name, 'Object Categories', $file.FullName -ErrorRecord $_ return } } # Domain Data foreach ($file in (Get-ChildItem "$($ContextObject.Path)\domain\domaindata" -Filter '*.psd1' -ErrorAction Ignore)) { try { $dataSet = Import-PSFPowerShellDataFile -Path $file.FullName $dataSet.Scriptblock = $dataSet.Scriptblock.Invoke() | Write-Output # Remove automatic scriptblock nesting Register-DMDomainData @dataSet -ContextName $ContextObject.Name } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.DomainConfig' -StringValues $ContextObject.Name, 'Domain Data', $file.FullName -ErrorRecord $_ return } } # Domain Level $domainLevelPath = Resolve-DataFile -Path "$($ContextObject.Path)\domain\domain_level" if ($domainLevelPath) { $file = Get-Item -Path $domainLevelPath Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, 'DomainLevel', $file.FullName try { $dataSet = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop Register-DMDomainLevel -Level $dataSet.Level -ContextName $ContextObject.Name } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.DomainConfig' -StringValues $ContextObject.Name, 'DomainLevel', $file.FullName -ErrorRecord $_ return } } # Content Mode $contentModePath = Resolve-DataFile -Path "$($ContextObject.Path)\domain\content_mode" if ($contentModePath) { $file = Get-Item -Path $contentModePath Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, 'ContentMode', $file.FullName try { $dataSet = Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop if ($dataSet.Mode) { Set-DMContentMode -Mode $dataSet.Mode } if ($dataSet.Include) { $includes = @((Get-DMContentMode).Include) foreach ($entry in $dataSet.Include) { $includes += $entry } Set-DMContentMode -Include $includes } if ($dataSet.Exclude) { $excludes = @((Get-DMContentMode).Exclude) foreach ($entry in $dataSet.Exclude) { $excludes += $entry } Set-DMContentMode -Exclude $excludes } if ($dataSet.UserExcludePattern) { $userExcludePatterns = @((Get-DMContentMode).UserExcludePattern) foreach ($entry in $dataSet.UserExcludePattern) { $userExcludePatterns += $entry -replace '%GUID%', '(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})' } Set-DMContentMode -UserExcludePattern $userExcludePatterns } if ($dataSet.Keys -contains 'RemoveUnknownWmiFilter') { Set-DMContentMode -RemoveUnknownWmiFilter $dataSet.RemoveUnknownWmiFilter } } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.DomainConfig' -StringValues $ContextObject.Name, 'ContentMode', $file.FullName -ErrorRecord $_ return } } #endregion Domain #region DC $dcConfigPath = Resolve-DataFile -Path "$($ContextObject.Path)\dc\dc_config" if ($dcConfigPath) { try { $dcData = Import-PSFPowerShellDataFile -LiteralPath $dcConfigPath -Unsafe -ErrorAction Stop } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.DCConfig' -StringValues $ContextObject.Name -ErrorRecord $_ return } if ($null -ne $dcData.NoDNS) { Set-PSFConfig -FullName 'DCManagement.Defaults.NoDNS' -Value $dcData.NoDNS } if ($null -ne $dcData.NoReboot) { Set-PSFConfig -FullName 'DCManagement.Defaults.NoReboot' -Value $dcData.NoReboot } if ($dcData.DatabasePath) { Set-PSFConfig -FullName 'DCManagement.Defaults.DatabasePath' -Value $dcData.DatabasePath } if ($dcData.LogPath) { Set-PSFConfig -FullName 'DCManagement.Defaults.LogPath' -Value $dcData.LogPath } if ($dcData.SysvolPath) { Set-PSFConfig -FullName 'DCManagement.Defaults.SysvolPath' -Value $dcData.SysvolPath } } $dcFields = @{ 'shares' = Get-Command Register-DCShare 'fsaccessrules' = Get-Command Register-DCAccessRule } foreach ($key in $dcFields.Keys) { if (-not (Test-Path "$($ContextObject.Path)\dc\$key")) { continue } foreach ($file in Get-ChildItem "$($ContextObject.Path)\dc\$key\" -Recurse | Where-Object Extension -In ".json", '.psd1') { Write-PSFMessage -Level Debug -String 'Set-AdmfContext.Context.Loading' -StringValues $ContextObject.Name, $key, $file.FullName try { foreach ($dataSet in (Import-PSFPowerShellDataFile -LiteralPath $file.FullName -Unsafe -ErrorAction Stop | Write-Output | ConvertTo-PSFHashtable -Include $($dcFields[$key].Parameters.Keys))) { if ($dcFields[$key].Parameters.Keys -contains 'ContextName') { $dataSet['ContextName'] = $ContextObject.Name } & $dcFields[$key] @dataSet -ErrorAction Stop } } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.ForestConfig' -StringValues $ContextObject.Name, $key, $file.FullName -ErrorRecord $_ return } } } #endregion DC #region PostImport if (Test-Path "$($ContextObject.Path)\postImport.ps1") { try { $null = & "$($ContextObject.Path)\postImport.ps1" @parameters } catch { Clear-AdcConfiguration Stop-PSFFunction @stopParam -String 'Set-AdmfContext.Context.Error.PostImport' -StringValues $ContextObject.Name -ErrorRecord $_ return } } #endregion PostImport } #endregion Utility Functions $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential $selectedContexts = @{ } # Common parameters for Stop-PSFFunction $commonParam = @{ EnableException = $EnableException Continue = $true Cmdlet = $PSCmdlet } if ($NoDomain) { $domain = [pscustomobject]@{ DNSRoot = $Server } return # Ends the current block and moves on to process } if ($DnsDomain) { $domain = [pscustomobject]@{ DNSRoot = $DnsDomain } return # Ends the current block and moves on to process } $adParameters = $parameters.Clone() if (-not $adParameters.Credential) { $adParameters.Remove('Credential') } try { $domain = Get-ADDomain @adParameters -ErrorAction Stop } catch { Stop-PSFFunction -String 'Set-AdmfContext.Domain.AccessError' -StringValues $Server -EnableException $EnableException -ErrorRecord $_ -Cmdlet $PSCmdlet return } } process { if (Test-PSFFunctionInterrupt) { return } #region Explicitly specified contexts foreach ($contextObject in $Context) { if ($contextObject -is [string]) { $foundContext = Get-AdmfContext -Name $contextObject if (-not $foundContext) { Stop-PSFFunction @commonParam -String 'Set-AdmfContext.Context.NotFound' -StringValues $contextObject } if ($foundContext.Count -gt 1) { Stop-PSFFunction @commonParam -String 'Set-AdmfContext.Context.Ambiguous' -StringValues $contextObject, ($foundContext.Name -join ", ") } $selectedContexts[$foundContext.Name] = $foundContext continue } if ($contextObject.PSObject.Typenames -eq 'ADMF.Context') { $selectedContexts[$contextObject.Name] = $contextObject continue } Stop-PSFFunction @commonParam -String 'Set-AdmfContext.Context.InvalidInput' -StringValues $contextObject, $contextObject.GetType().FullName } #endregion Explicitly specified contexts #region Interactively chosen contexts if ($Interactive) { if ($ReUse -and $script:assignedContexts["$($domain.DNSRoot)"]) { foreach ($contextObject in $script:assignedContexts["$($domain.DNSRoot)"]) { $selectedContexts[$contextObject.Name] = $contextObject } return } try { foreach ($contextObject in (Invoke-CallbackMenu @parameters)) { $selectedContexts[$contextObject.Name] = $contextObject } } catch { Stop-PSFFunction -String 'Set-AdmfContext.Interactive.Cancel' -EnableException $EnableException -ErrorRecord $_ return } } #endregion Interactively chosen contexts } end { if (Test-PSFFunctionInterrupt) { return } #region Handle errors in selection $missingPrerequisites = $selectedContexts.Values.Prerequisites | Where-Object { $_ -notin $selectedContexts.Values.Name } if ($missingPrerequisites) { Stop-PSFFunction -String 'Set-AdmfContext.Resolution.MissingPrerequisites' -StringValues ($missingPrerequisites -join ", ") -EnableException $EnableException -Category InvalidData return } $conflictingContexts = $selectedContexts.Values.MutuallyExclusive | Where-Object { $_ -in $selectedContexts.Values.Name } if ($conflictingContexts) { Stop-PSFFunction -String 'Set-AdmfContext.Resolution.ExclusionConflict' -StringValues ($conflictingContexts.Name -join ", ") -EnableException $EnableException -Category InvalidData return } #endregion Handle errors in selection # Do nothing if the currently loaded contexts are equal to the selected ones if ( $script:loadedContexts.Name -and $selectedContexts.Values.Name -and -not (Compare-Object -ReferenceObject $selectedContexts.Values.Name -DifferenceObject $script:loadedContexts.Name) ) { # When switching from one domain to a new one, make sure that the selection is cached, even if it is the same selection. # Otherwise, the second domain will keep reprompting for contexts if (-not $script:assignedContexts["$($domain.DNSRoot)"]) { $script:assignedContexts["$($domain.DNSRoot)"] = $selectedContexts.Values } return } # In Define Only Mode: Register Context to domain and terminate peacefully if ($DefineOnly) { $script:assignedContexts["$($domain.DNSRoot)"] = $selectedContexts.Values | Sort-Object Weight return } # Kill previous configuration $script:loadedContexts = @() Clear-AdcConfiguration Set-PSFTaskEngineCache -Module ADMF -Name currentlyImportingContexts -Value $selectedContexts.Values foreach ($contextObject in ($selectedContexts.Values | Sort-Object Weight)) { if (Test-PSFFunctionInterrupt) { return } Set-Context @parameters -ContextObject $contextObject -Cmdlet $PSCmdlet -EnableException $EnableException if (Test-PSFFunctionInterrupt) { return } } $script:assignedContexts["$($domain.DNSRoot)"] = $selectedContexts.Values | Sort-Object Weight $script:loadedContexts = @($selectedContexts.Values | Sort-Object Weight) Set-PSFTaskEngineCache -Module ADMF -Name currentlyImportingContexts -Value @() } }