From c1656321b1662f3f4dbac1e9611bc4a435d86ce8 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 09:51:16 +0200 Subject: [PATCH 01/29] Remove semicolon from rows --- .../MSFT_xADDomain/MSFT_xADDomain.psm1 | 100 +++---- .../MSFT_xADDomainDefaultPasswordPolicy.psm1 | 84 +++--- DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 | 4 +- .../MSFT_xADOrganizationalUnit.psm1 | 4 +- DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 | 196 ++++++------- .../MSFT_xWaitForADDomain.psm1 | 2 +- Tests/Unit/MSFT_xADDomain.Tests.ps1 | 180 ++++++------ ...T_xADDomainDefaultPasswordPolicy.Tests.ps1 | 142 +++++----- Tests/Unit/MSFT_xADGroup.Tests.ps1 | 264 +++++++++--------- .../MSFT_xADManagedServiceAccount.Tests.ps1 | 2 +- .../Unit/MSFT_xADOrganizationalUnit.Tests.ps1 | 30 +- Tests/Unit/MSFT_xADUser.Tests.ps1 | 2 +- 12 files changed, 505 insertions(+), 505 deletions(-) diff --git a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 index 3ecad350f..4fdd2f47f 100644 --- a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 +++ b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 @@ -85,8 +85,8 @@ function Get-TargetResource ) Assert-Module -ModuleName 'ADDSDeployment' -ImportModule - $domainFQDN = Resolve-DomainFQDN -DomainName $DomainName -ParentDomainName $ParentDomainName; - $isDomainMember = Test-DomainMember; + $domainFQDN = Resolve-DomainFQDN -DomainName $DomainName -ParentDomainName $ParentDomainName + $isDomainMember = Test-DomainMember $retries = 0 $maxRetries = 5 @@ -99,12 +99,12 @@ function Get-TargetResource if ($isDomainMember) { ## We're already a domain member, so take the credentials out of the equation - Write-Verbose ($script:localizedData.QueryDomainWithLocalCredential -f $domainFQDN); - $domain = Get-ADDomain -Identity $domainFQDN -ErrorAction Stop; + Write-Verbose ($script:localizedData.QueryDomainWithLocalCredential -f $domainFQDN) + $domain = Get-ADDomain -Identity $domainFQDN -ErrorAction Stop $forest = Get-ADForest -Identity $domain.Forest -ErrorAction Stop } else { - Write-Verbose ($script:localizedData.QueryDomainWithCredential -f $domainFQDN); + Write-Verbose ($script:localizedData.QueryDomainWithCredential -f $domainFQDN) $domain = Get-ADDomain -Identity $domainFQDN -Credential $DomainAdministratorCredential -ErrorAction Stop $forest = Get-ADForest -Identity $domain.Forest -Credential $DomainAdministratorCredential -ErrorAction Stop } @@ -112,33 +112,33 @@ function Get-TargetResource ## No need to check whether the node is actually a domain controller. If we don't throw an exception, ## the domain is already UP - and this resource shouldn't run. Domain controller functionality ## should be checked by the xADDomainController resource? - Write-Verbose ($script:localizedData.DomainFound -f $domain.DnsRoot); + Write-Verbose ($script:localizedData.DomainFound -f $domain.DnsRoot) $targetResource = @{ - DomainName = $domain.DnsRoot; - ParentDomainName = $domain.ParentDomain; - DomainNetBIOSName = $domain.NetBIOSName; + DomainName = $domain.DnsRoot + ParentDomainName = $domain.ParentDomain + DomainNetBIOSName = $domain.NetBIOSName ForestMode = (ConvertTo-DeploymentForestMode -Mode $forest.ForestMode) -as [String] DomainMode = (ConvertTo-DeploymentDomainMode -Mode $domain.DomainMode) -as [String] } - return $targetResource; + return $targetResource } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { - $errorMessage = $script:localizedData.ExistingDomainMemberError -f $DomainName; - ThrowInvalidOperationError -ErrorId 'xADDomain_DomainMember' -ErrorMessage $errorMessage; + $errorMessage = $script:localizedData.ExistingDomainMemberError -f $DomainName + ThrowInvalidOperationError -ErrorId 'xADDomain_DomainMember' -ErrorMessage $errorMessage } catch [Microsoft.ActiveDirectory.Management.ADServerDownException] { Write-Verbose ($script:localizedData.DomainNotFound -f $domainFQDN) - $domain = @{ }; + $domain = @{ } # will fall into retry mechanism } catch [System.Security.Authentication.AuthenticationException] { - $errorMessage = $script:localizedData.InvalidCredentialError -f $DomainName; - ThrowInvalidOperationError -ErrorId 'xADDomain_InvalidCredential' -ErrorMessage $errorMessage; + $errorMessage = $script:localizedData.InvalidCredentialError -f $DomainName + ThrowInvalidOperationError -ErrorId 'xADDomain_InvalidCredential' -ErrorMessage $errorMessage } catch { @@ -206,42 +206,42 @@ function Test-TargetResource ) $targetResource = Get-TargetResource @PSBoundParameters - $isCompliant = $true; + $isCompliant = $true ## The Get-Target resource returns .DomainName as the domain's FQDN. Therefore, we ## need to resolve this before comparison. $domainFQDN = Resolve-DomainFQDN -DomainName $DomainName -ParentDomainName $ParentDomainName if ($domainFQDN -ne $targetResource.DomainName) { - $message = $script:localizedData.ResourcePropertyValueIncorrect -f 'DomainName', $domainFQDN, $targetResource.DomainName; - Write-Verbose -Message $message; - $isCompliant = $false; + $message = $script:localizedData.ResourcePropertyValueIncorrect -f 'DomainName', $domainFQDN, $targetResource.DomainName + Write-Verbose -Message $message + $isCompliant = $false } - $propertyNames = @('ParentDomainName','DomainNetBIOSName'); + $propertyNames = @('ParentDomainName','DomainNetBIOSName') foreach ($propertyName in $propertyNames) { if ($PSBoundParameters.ContainsKey($propertyName)) { - $propertyValue = (Get-Variable -Name $propertyName).Value; + $propertyValue = (Get-Variable -Name $propertyName).Value if ($targetResource.$propertyName -ne $propertyValue) { - $message = $script:localizedData.ResourcePropertyValueIncorrect -f $propertyName, $propertyValue, $targetResource.$propertyName; - Write-Verbose -Message $message; - $isCompliant = $false; + $message = $script:localizedData.ResourcePropertyValueIncorrect -f $propertyName, $propertyValue, $targetResource.$propertyName + Write-Verbose -Message $message + $isCompliant = $false } } } if ($isCompliant) { - Write-Verbose -Message ($script:localizedData.ResourceInDesiredState -f $domainFQDN); - return $true; + Write-Verbose -Message ($script:localizedData.ResourceInDesiredState -f $domainFQDN) + return $true } else { - Write-Verbose -Message ($script:localizedData.ResourceNotInDesiredState -f $domainFQDN); - return $false; + Write-Verbose -Message ($script:localizedData.ResourceNotInDesiredState -f $domainFQDN) + return $false } } #end function Test-TargetResource @@ -297,66 +297,66 @@ function Set-TargetResource ) # Debug can pause Install-ADDSForest/Install-ADDSDomain, so we remove it. - [ref] $null = $PSBoundParameters.Remove('Debug'); + [ref] $null = $PSBoundParameters.Remove('Debug') ## Not entirely necessary, but run Get-TargetResouece to ensure we raise any pre-flight errors. - $targetResource = Get-TargetResource @PSBoundParameters; + $targetResource = Get-TargetResource @PSBoundParameters $installADDSParams = @{ - SafeModeAdministratorPassword = $SafemodeAdministratorPassword.Password; - NoRebootOnCompletion = $true; - Force = $true; + SafeModeAdministratorPassword = $SafemodeAdministratorPassword.Password + NoRebootOnCompletion = $true + Force = $true } if ($PSBoundParameters.ContainsKey('DnsDelegationCredential')) { - $installADDSParams['DnsDelegationCredential'] = $DnsDelegationCredential; - $installADDSParams['CreateDnsDelegation'] = $true; + $installADDSParams['DnsDelegationCredential'] = $DnsDelegationCredential + $installADDSParams['CreateDnsDelegation'] = $true } if ($PSBoundParameters.ContainsKey('DatabasePath')) { - $installADDSParams['DatabasePath'] = $DatabasePath; + $installADDSParams['DatabasePath'] = $DatabasePath } if ($PSBoundParameters.ContainsKey('LogPath')) { - $installADDSParams['LogPath'] = $LogPath; + $installADDSParams['LogPath'] = $LogPath } if ($PSBoundParameters.ContainsKey('SysvolPath')) { - $installADDSParams['SysvolPath'] = $SysvolPath; + $installADDSParams['SysvolPath'] = $SysvolPath } if ($PSBoundParameters.ContainsKey('DomainMode')) { - $installADDSParams['DomainMode'] = $DomainMode; + $installADDSParams['DomainMode'] = $DomainMode } if ($PSBoundParameters.ContainsKey('ParentDomainName')) { - Write-Verbose -Message ($script:localizedData.CreatingChildDomain -f $DomainName, $ParentDomainName); + Write-Verbose -Message ($script:localizedData.CreatingChildDomain -f $DomainName, $ParentDomainName) $installADDSParams['Credential'] = $DomainAdministratorCredential $installADDSParams['NewDomainName'] = $DomainName $installADDSParams['ParentDomainName'] = $ParentDomainName - $installADDSParams['DomainType'] = 'ChildDomain'; + $installADDSParams['DomainType'] = 'ChildDomain' if ($PSBoundParameters.ContainsKey('DomainNetBIOSName')) { - $installADDSParams['NewDomainNetbiosName'] = $DomainNetBIOSName; + $installADDSParams['NewDomainNetbiosName'] = $DomainNetBIOSName } - Install-ADDSDomain @installADDSParams; - Write-Verbose -Message ($script:localizedData.CreatedChildDomain); + Install-ADDSDomain @installADDSParams + Write-Verbose -Message ($script:localizedData.CreatedChildDomain) } else { - Write-Verbose -Message ($script:localizedData.CreatingForest -f $DomainName); - $installADDSParams['DomainName'] = $DomainName; + Write-Verbose -Message ($script:localizedData.CreatingForest -f $DomainName) + $installADDSParams['DomainName'] = $DomainName if ($PSBoundParameters.ContainsKey('DomainNetbiosName')) { - $installADDSParams['DomainNetbiosName'] = $DomainNetBIOSName; + $installADDSParams['DomainNetbiosName'] = $DomainNetBIOSName } if ($PSBoundParameters.ContainsKey('ForestMode')) { $installADDSParams['ForestMode'] = $ForestMode } - Install-ADDSForest @installADDSParams; - Write-Verbose -Message ($script:localizedData.CreatedForest -f $DomainName); + Install-ADDSForest @installADDSParams + Write-Verbose -Message ($script:localizedData.CreatedForest -f $DomainName) } 'Finished' | Out-File -FilePath (Get-TrackingFilename -DomainName $DomainName) -Force @@ -367,4 +367,4 @@ function Set-TargetResource } #end function Set-TargetResource -Export-ModuleMember -Function *-TargetResource; +Export-ModuleMember -Function *-TargetResource diff --git a/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 b/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 index 1271c66f3..4006db3e9 100644 --- a/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 +++ b/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 @@ -37,25 +37,25 @@ function Get-TargetResource [System.Management.Automation.CredentialAttribute()] $Credential ) - Assert-Module -ModuleName 'ActiveDirectory'; + Assert-Module -ModuleName 'ActiveDirectory' - $PSBoundParameters['Identity'] = $DomainName; - $getADDefaultDomainPasswordPolicyParams = Get-ADCommonParameters @PSBoundParameters; - Write-Verbose -Message ($script:localizedData.QueryingDomainPasswordPolicy -f $DomainName); - $policy = Get-ADDefaultDomainPasswordPolicy @getADDefaultDomainPasswordPolicyParams; + $PSBoundParameters['Identity'] = $DomainName + $getADDefaultDomainPasswordPolicyParams = Get-ADCommonParameters @PSBoundParameters + Write-Verbose -Message ($script:localizedData.QueryingDomainPasswordPolicy -f $DomainName) + $policy = Get-ADDefaultDomainPasswordPolicy @getADDefaultDomainPasswordPolicyParams $targetResource = @{ - DomainName = $DomainName; - ComplexityEnabled = $policy.ComplexityEnabled; - LockoutDuration = ConvertFrom-Timespan -Timespan $policy.LockoutDuration -TimeSpanType Minutes; - LockoutObservationWindow = ConvertFrom-Timespan -Timespan $policy.LockoutObservationWindow -TimeSpanType Minutes; - LockoutThreshold = $policy.LockoutThreshold; - MinPasswordAge = ConvertFrom-Timespan -Timespan $policy.MinPasswordAge -TimeSpanType Minutes; - MaxPasswordAge = ConvertFrom-Timespan -Timespan $policy.MaxPasswordAge -TimeSpanType Minutes; - MinPasswordLength = $policy.MinPasswordLength; - PasswordHistoryCount = $policy.PasswordHistoryCount; - ReversibleEncryptionEnabled = $policy.ReversibleEncryptionEnabled; + DomainName = $DomainName + ComplexityEnabled = $policy.ComplexityEnabled + LockoutDuration = ConvertFrom-Timespan -Timespan $policy.LockoutDuration -TimeSpanType Minutes + LockoutObservationWindow = ConvertFrom-Timespan -Timespan $policy.LockoutObservationWindow -TimeSpanType Minutes + LockoutThreshold = $policy.LockoutThreshold + MinPasswordAge = ConvertFrom-Timespan -Timespan $policy.MinPasswordAge -TimeSpanType Minutes + MaxPasswordAge = ConvertFrom-Timespan -Timespan $policy.MaxPasswordAge -TimeSpanType Minutes + MinPasswordLength = $policy.MinPasswordLength + PasswordHistoryCount = $policy.PasswordHistoryCount + ReversibleEncryptionEnabled = $policy.ReversibleEncryptionEnabled } - return $targetResource; + return $targetResource } #end Get-TargetResource function Test-TargetResource @@ -104,44 +104,44 @@ function Test-TargetResource $Credential ) $getTargetResourceParams = @{ - DomainName = $DomainName; + DomainName = $DomainName } if ($PSBoundParameters.ContainsKey('Credential')) { - $getTargetResourceParams['Credential'] = $Credential; + $getTargetResourceParams['Credential'] = $Credential } if ($PSBoundParameters.ContainsKey('DomainController')) { - $getTargetResourceParams['DomainController'] = $DomainController; + $getTargetResourceParams['DomainController'] = $DomainController } - $targetResource = Get-TargetResource @getTargetResourceParams; + $targetResource = Get-TargetResource @getTargetResourceParams - $inDesiredState = $true; + $inDesiredState = $true foreach ($property in $mutablePropertyMap) { - $propertyName = $property.Name; + $propertyName = $property.Name if ($PSBoundParameters.ContainsKey($propertyName)) { - $expectedValue = $PSBoundParameters[$propertyName]; - $actualValue = $targetResource[$propertyName]; + $expectedValue = $PSBoundParameters[$propertyName] + $actualValue = $targetResource[$propertyName] if ($expectedValue -ne $actualValue) { - $valueIncorrectMessage = $script:localizedData.ResourcePropertyValueIncorrect -f $propertyName, $expectedValue, $actualValue; - Write-Verbose -Message $valueIncorrectMessage; - $inDesiredState = $false; + $valueIncorrectMessage = $script:localizedData.ResourcePropertyValueIncorrect -f $propertyName, $expectedValue, $actualValue + Write-Verbose -Message $valueIncorrectMessage + $inDesiredState = $false } } } if ($inDesiredState) { - Write-Verbose -Message ($script:localizedData.ResourceInDesiredState -f $DomainName); - return $true; + Write-Verbose -Message ($script:localizedData.ResourceInDesiredState -f $DomainName) + return $true } else { - Write-Verbose -Message ($script:localizedData.ResourceNotInDesiredState -f $DomainName); - return $false; + Write-Verbose -Message ($script:localizedData.ResourceNotInDesiredState -f $DomainName) + return $false } } #end Test-TargetResource @@ -189,27 +189,27 @@ function Set-TargetResource [System.Management.Automation.CredentialAttribute()] $Credential ) - Assert-Module -ModuleName 'ActiveDirectory'; - $PSBoundParameters['Identity'] = $DomainName; - $setADDefaultDomainPasswordPolicyParams = Get-ADCommonParameters @PSBoundParameters; + Assert-Module -ModuleName 'ActiveDirectory' + $PSBoundParameters['Identity'] = $DomainName + $setADDefaultDomainPasswordPolicyParams = Get-ADCommonParameters @PSBoundParameters foreach ($property in $mutablePropertyMap) { - $propertyName = $property.Name; + $propertyName = $property.Name if ($PSBoundParameters.ContainsKey($propertyName)) { - $propertyValue = $PSBoundParameters[$propertyName]; + $propertyValue = $PSBoundParameters[$propertyName] if ($property.IsTimeSpan -eq $true) { - $propertyValue = ConvertTo-TimeSpan -TimeSpan $propertyValue -TimeSpanType Minutes; + $propertyValue = ConvertTo-TimeSpan -TimeSpan $propertyValue -TimeSpanType Minutes } - $setADDefaultDomainPasswordPolicyParams[$propertyName] = $propertyValue; - Write-Verbose -Message ($script:localizedData.SettingPasswordPolicyValue -f $propertyName, $propertyValue); + $setADDefaultDomainPasswordPolicyParams[$propertyName] = $propertyValue + Write-Verbose -Message ($script:localizedData.SettingPasswordPolicyValue -f $propertyName, $propertyValue) } } - Write-Verbose -Message ($script:localizedData.UpdatingDomainPasswordPolicy -f $DomainName); - [ref] $null = Set-ADDefaultDomainPasswordPolicy @setADDefaultDomainPasswordPolicyParams; + Write-Verbose -Message ($script:localizedData.UpdatingDomainPasswordPolicy -f $DomainName) + [ref] $null = Set-ADDefaultDomainPasswordPolicy @setADDefaultDomainPasswordPolicyParams } #end Set-TargetResource -Export-ModuleMember -Function *-TargetResource; +Export-ModuleMember -Function *-TargetResource diff --git a/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 b/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 index e14365963..2f9fab407 100644 --- a/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 +++ b/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 @@ -385,7 +385,7 @@ function Set-TargetResource if ($MembershipAttribute -eq 'DistinguishedName') { $AllMembers = $Members + $MembersToInclude + $MembersToExclude - $GroupMemberDomains = @(); + $GroupMemberDomains = @() foreach($member in $AllMembers) { $GroupMemberDomains += Get-ADDomainNameFromDistinguishedName -DistinguishedName $member @@ -393,7 +393,7 @@ function Set-TargetResource $GroupMemberDomainCount = ($GroupMemberDomains | Select-Object -Unique).count if( $GroupMemberDomainCount -gt 1 -or ($GroupMemberDomains -ine (Get-DomainName)).Count -gt 0 ) { - Write-Verbose -Message ($script:localizedData.GroupMembershipMultipleDomains -f $GroupMemberDomainCount); + Write-Verbose -Message ($script:localizedData.GroupMembershipMultipleDomains -f $GroupMemberDomainCount) $MembersInMultipleDomains = $true } } diff --git a/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 b/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 index 71f75122a..06a8d7d48 100644 --- a/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 +++ b/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 @@ -19,7 +19,7 @@ function Get-TargetResource [System.String] $Path ) - Assert-Module -ModuleName 'ActiveDirectory'; + Assert-Module -ModuleName 'ActiveDirectory' Write-Verbose ($script:localizedData.RetrievingOU -f $Name) $ou = Get-ADOrganizationalUnit -Filter { Name -eq $Name } -SearchBase $Path -SearchScope OneLevel -Properties ProtectedFromAccidentalDeletion, Description @@ -162,7 +162,7 @@ function Set-TargetResource $RestoreFromRecycleBin ) - Assert-Module -ModuleName 'ActiveDirectory'; + Assert-Module -ModuleName 'ActiveDirectory' $targetResource = Get-TargetResource -Name $Name -Path $Path if ($targetResource.Ensure -eq 'Present') diff --git a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 index b15ceb1d4..dedbc6890 100644 --- a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 +++ b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 @@ -363,49 +363,49 @@ function Get-TargetResource $ServicePrincipalNames ) - Assert-Module -ModuleName 'ActiveDirectory'; + Assert-Module -ModuleName 'ActiveDirectory' try { - $adCommonParameters = Get-ADCommonParameters @PSBoundParameters; + $adCommonParameters = Get-ADCommonParameters @PSBoundParameters - $adProperties = @(); + $adProperties = @() # Create an array of the AD propertie names to retrieve from the property map foreach ($property in $adPropertyMap) { if ($property.ADProperty) { - $adProperties += $property.ADProperty; + $adProperties += $property.ADProperty } else { - $adProperties += $property.Parameter; + $adProperties += $property.Parameter } } - Write-Verbose -Message ($script:localizedData.RetrievingADUser -f $UserName, $DomainName); - $adUser = Get-ADUser @adCommonParameters -Properties $adProperties; - Write-Verbose -Message ($script:localizedData.ADUserIsPresent -f $UserName, $DomainName); - $Ensure = 'Present'; + Write-Verbose -Message ($script:localizedData.RetrievingADUser -f $UserName, $DomainName) + $adUser = Get-ADUser @adCommonParameters -Properties $adProperties + Write-Verbose -Message ($script:localizedData.ADUserIsPresent -f $UserName, $DomainName) + $Ensure = 'Present' } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { - Write-Verbose -Message ($script:localizedData.ADUserNotPresent -f $UserName, $DomainName); - $Ensure = 'Absent'; + Write-Verbose -Message ($script:localizedData.ADUserNotPresent -f $UserName, $DomainName) + $Ensure = 'Absent' } catch { - Write-Error -Message ($script:localizedData.RetrievingADUserError -f $UserName, $DomainName); - throw $_; + Write-Error -Message ($script:localizedData.RetrievingADUserError -f $UserName, $DomainName) + throw $_ } $targetResource = @{ - DomainName = $DomainName; - Password = $Password; - UserName = $UserName; + DomainName = $DomainName + Password = $Password + UserName = $UserName DistinguishedName = $adUser.DistinguishedName; # Read-only property - Ensure = $Ensure; - DomainController = $DomainController; + Ensure = $Ensure + DomainController = $DomainController } # Retrieve each property from the ADPropertyMap and add to the hashtable @@ -416,7 +416,7 @@ function Get-TargetResource # The path returned is not the parent container if (-not [System.String]::IsNullOrEmpty($adUser.DistinguishedName)) { - $targetResource['Path'] = Get-ADObjectParentDN -DN $adUser.DistinguishedName; + $targetResource['Path'] = Get-ADObjectParentDN -DN $adUser.DistinguishedName } } elseif (($property.Parameter) -eq 'ServicePrincipalNames') { @@ -434,15 +434,15 @@ function Get-TargetResource elseif ($property.ADProperty) { # The AD property name is different to the function parameter to use this - $targetResource[$property.Parameter] = $adUser.($property.ADProperty); + $targetResource[$property.Parameter] = $adUser.($property.ADProperty) } else { # The AD property name matches the function parameter - $targetResource[$property.Parameter] = $adUser.($property.Parameter); + $targetResource[$property.Parameter] = $adUser.($property.Parameter) } } - return $targetResource; + return $targetResource } #end function Get-TargetResource @@ -753,42 +753,42 @@ function Test-TargetResource $ServicePrincipalNames ) - Assert-Parameters @PSBoundParameters; - $targetResource = Get-TargetResource @PSBoundParameters; - $isCompliant = $true; + Assert-Parameters @PSBoundParameters + $targetResource = Get-TargetResource @PSBoundParameters + $isCompliant = $true if ($Ensure -eq 'Absent') { if ($targetResource.Ensure -eq 'Present') { - Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f 'Ensure', $PSBoundParameters.Ensure, $targetResource.Ensure); - $isCompliant = $false; + Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f 'Ensure', $PSBoundParameters.Ensure, $targetResource.Ensure) + $isCompliant = $false } } else { # Add common name, ensure and enabled as they may not be explicitly passed and we want to enumerate them - $PSBoundParameters['Ensure'] = $Ensure; - $PSBoundParameters['Enabled'] = $Enabled; + $PSBoundParameters['Ensure'] = $Ensure + $PSBoundParameters['Enabled'] = $Enabled foreach ($parameter in $PSBoundParameters.Keys) { if ($parameter -eq 'Password' -and $PasswordNeverResets -eq $false) { $testPasswordParams = @{ - Username = $UserName; - Password = $Password; - DomainName = $DomainName; - PasswordAuthentication = $PasswordAuthentication; + Username = $UserName + Password = $Password + DomainName = $DomainName + PasswordAuthentication = $PasswordAuthentication } if ($DomainAdministratorCredential) { - $testPasswordParams['DomainAdministratorCredential'] = $DomainAdministratorCredential; + $testPasswordParams['DomainAdministratorCredential'] = $DomainAdministratorCredential } if (-not (Test-Password @testPasswordParams)) { - Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f 'Password', '', ''); - $isCompliant = $false; + Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f 'Password', '', '') + $isCompliant = $false } } # Only check properties that are returned by Get-TargetResource @@ -802,28 +802,28 @@ function Test-TargetResource elseif ($parameter -eq 'ServicePrincipalNames') { $testMembersParams = @{ - ExistingMembers = $targetResource.ServicePrincipalNames -as [System.String[]]; - Members = $ServicePrincipalNames; + ExistingMembers = $targetResource.ServicePrincipalNames -as [System.String[]] + Members = $ServicePrincipalNames } if (-not (Test-Members @testMembersParams)) { - $existingSPNs = $testMembersParams['ExistingMembers'] -join ','; - $desiredSPNs = $ServicePrincipalNames -join ','; + $existingSPNs = $testMembersParams['ExistingMembers'] -join ',' + $desiredSPNs = $ServicePrincipalNames -join ',' Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f ` - 'ServicePrincipalNames', $desiredSPNs, $existingSPNs); - $isCompliant = $false; + 'ServicePrincipalNames', $desiredSPNs, $existingSPNs) + $isCompliant = $false } } elseif ($PSBoundParameters.$parameter -ne $targetResource.$parameter) { - Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f $parameter, $PSBoundParameters.$parameter, $targetResource.$parameter); - $isCompliant = $false; + Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f $parameter, $PSBoundParameters.$parameter, $targetResource.$parameter) + $isCompliant = $false } } } #end foreach PSBoundParameter } - return $isCompliant; + return $isCompliant } #end function Test-TargetResource @@ -1133,12 +1133,12 @@ function Set-TargetResource $ServicePrincipalNames ) - Assert-Parameters @PSBoundParameters; - $targetResource = Get-TargetResource @PSBoundParameters; + Assert-Parameters @PSBoundParameters + $targetResource = Get-TargetResource @PSBoundParameters # Add common name, ensure and enabled as they may not be explicitly passed - $PSBoundParameters['Ensure'] = $Ensure; - $PSBoundParameters['Enabled'] = $Enabled; + $PSBoundParameters['Ensure'] = $Ensure + $PSBoundParameters['Enabled'] = $Enabled if ($Ensure -eq 'Present') { @@ -1155,26 +1155,26 @@ function Set-TargetResource if (-not $RestoreFromRecycleBin -or ($RestoreFromRecycleBin -and -not $restorationSuccessful)) { # User does not exist and needs creating - $newADUserParams = Get-ADCommonParameters @PSBoundParameters -UseNameParameter; + $newADUserParams = Get-ADCommonParameters @PSBoundParameters -UseNameParameter if ($PSBoundParameters.ContainsKey('Path')) { - $newADUserParams['Path'] = $Path; + $newADUserParams['Path'] = $Path } # Populate the AccountPassword parameter of New-ADUser if password declared if ($PSBoundParameters.ContainsKey('Password')) { - $newADUserParams['AccountPassword'] = $Password.Password; + $newADUserParams['AccountPassword'] = $Password.Password } - Write-Verbose -Message ($script:localizedData.AddingADUser -f $UserName); - New-ADUser @newADUserParams -SamAccountName $UserName; + Write-Verbose -Message ($script:localizedData.AddingADUser -f $UserName) + New-ADUser @newADUserParams -SamAccountName $UserName # Now retrieve the newly created user - $targetResource = Get-TargetResource @PSBoundParameters; + $targetResource = Get-TargetResource @PSBoundParameters } } - $setADUserParams = Get-ADCommonParameters @PSBoundParameters; - $replaceUserProperties = @{ }; - $removeUserProperties = @{ }; + $setADUserParams = Get-ADCommonParameters @PSBoundParameters + $replaceUserProperties = @{ } + $removeUserProperties = @{ } foreach ($parameter in $PSBoundParameters.Keys) { # Only check/action properties specified/declared parameters that match one of the function's @@ -1184,43 +1184,43 @@ function Set-TargetResource if ($parameter -eq 'Path' -and ($PSBoundParameters.Path -ne $targetResource.Path)) { # Cannot move users by updating the DistinguishedName property - $adCommonParameters = Get-ADCommonParameters @PSBoundParameters; + $adCommonParameters = Get-ADCommonParameters @PSBoundParameters # Using the SamAccountName for identity with Move-ADObject does not work, use the DN instead - $adCommonParameters['Identity'] = $targetResource.DistinguishedName; - Write-Verbose -Message ($script:localizedData.MovingADUser -f $targetResource.Path, $PSBoundParameters.Path); - Move-ADObject @adCommonParameters -TargetPath $PSBoundParameters.Path; + $adCommonParameters['Identity'] = $targetResource.DistinguishedName + Write-Verbose -Message ($script:localizedData.MovingADUser -f $targetResource.Path, $PSBoundParameters.Path) + Move-ADObject @adCommonParameters -TargetPath $PSBoundParameters.Path } elseif ($parameter -eq 'CommonName' -and ($PSBoundParameters.CommonName -ne $targetResource.CommonName)) { # Cannot rename users by updating the CN property directly - $adCommonParameters = Get-ADCommonParameters @PSBoundParameters; + $adCommonParameters = Get-ADCommonParameters @PSBoundParameters # Using the SamAccountName for identity with Rename-ADObject does not work, use the DN instead - $adCommonParameters['Identity'] = $targetResource.DistinguishedName; - Write-Verbose -Message ($script:localizedData.RenamingADUser -f $targetResource.CommonName, $PSBoundParameters.CommonName); - Rename-ADObject @adCommonParameters -NewName $PSBoundParameters.CommonName; + $adCommonParameters['Identity'] = $targetResource.DistinguishedName + Write-Verbose -Message ($script:localizedData.RenamingADUser -f $targetResource.CommonName, $PSBoundParameters.CommonName) + Rename-ADObject @adCommonParameters -NewName $PSBoundParameters.CommonName } elseif ($parameter -eq 'Password' -and $PasswordNeverResets -eq $false) { - $adCommonParameters = Get-ADCommonParameters @PSBoundParameters; - Write-Verbose -Message ($script:localizedData.SettingADUserPassword -f $UserName); - Set-ADAccountPassword @adCommonParameters -Reset -NewPassword $Password.Password; + $adCommonParameters = Get-ADCommonParameters @PSBoundParameters + Write-Verbose -Message ($script:localizedData.SettingADUserPassword -f $UserName) + Set-ADAccountPassword @adCommonParameters -Reset -NewPassword $Password.Password } elseif ($parameter -eq 'Enabled' -and ($PSBoundParameters.$parameter -ne $targetResource.$parameter)) { # We cannot enable/disable an account with -Add or -Replace parameters, but inform that # we will change this as it is out of compliance (it always gets set anyway) - Write-Verbose -Message ($script:localizedData.UpdatingADUserProperty -f $parameter, $PSBoundParameters.$parameter); + Write-Verbose -Message ($script:localizedData.UpdatingADUserProperty -f $parameter, $PSBoundParameters.$parameter) } elseif ($parameter -eq 'ServicePrincipalNames') { Write-Verbose -Message ($script:localizedData.UpdatingADUserProperty -f ` - 'ServicePrincipalNames', ($ServicePrincipalNames -join ',')); - $replaceUserProperties['ServicePrincipalName'] = $ServicePrincipalNames; + 'ServicePrincipalNames', ($ServicePrincipalNames -join ',')) + $replaceUserProperties['ServicePrincipalName'] = $ServicePrincipalNames } elseif ($PSBoundParameters.$parameter -ne $targetResource.$parameter) { # Find the associated AD property - $adProperty = $adPropertyMap | Where-Object { $_.Parameter -eq $parameter }; + $adProperty = $adPropertyMap | Where-Object { $_.Parameter -eq $parameter } if ([System.String]::IsNullOrEmpty($adProperty)) { @@ -1232,38 +1232,38 @@ function Set-TargetResource # Only remove if the existing value in not null or empty if (-not ([System.String]::IsNullOrEmpty($targetResource.$parameter))) { - Write-Verbose -Message ($script:localizedData.RemovingADUserProperty -f $parameter, $PSBoundParameters.$parameter); + Write-Verbose -Message ($script:localizedData.RemovingADUserProperty -f $parameter, $PSBoundParameters.$parameter) if ($adProperty.UseCmdletParameter -eq $true) { # We need to pass the parameter explicitly to Set-ADUser, not via -Remove - $setADUserParams[$adProperty.Parameter] = $PSBoundParameters.$parameter; + $setADUserParams[$adProperty.Parameter] = $PSBoundParameters.$parameter } elseif ([System.String]::IsNullOrEmpty($adProperty.ADProperty)) { - $removeUserProperties[$adProperty.Parameter] = $targetResource.$parameter; + $removeUserProperties[$adProperty.Parameter] = $targetResource.$parameter } else { - $removeUserProperties[$adProperty.ADProperty] = $targetResource.$parameter; + $removeUserProperties[$adProperty.ADProperty] = $targetResource.$parameter } } } #end if remove existing value else { # We are replacing the existing value - Write-Verbose -Message ($script:localizedData.UpdatingADUserProperty -f $parameter, $PSBoundParameters.$parameter); + Write-Verbose -Message ($script:localizedData.UpdatingADUserProperty -f $parameter, $PSBoundParameters.$parameter) if ($adProperty.UseCmdletParameter -eq $true) { # We need to pass the parameter explicitly to Set-ADUser, not via -Replace - $setADUserParams[$adProperty.Parameter] = $PSBoundParameters.$parameter; + $setADUserParams[$adProperty.Parameter] = $PSBoundParameters.$parameter } elseif ([System.String]::IsNullOrEmpty($adProperty.ADProperty)) { - $replaceUserProperties[$adProperty.Parameter] = $PSBoundParameters.$parameter; + $replaceUserProperties[$adProperty.Parameter] = $PSBoundParameters.$parameter } else { - $replaceUserProperties[$adProperty.ADProperty] = $PSBoundParameters.$parameter; + $replaceUserProperties[$adProperty.ADProperty] = $PSBoundParameters.$parameter } } #end if replace existing value } @@ -1274,22 +1274,22 @@ function Set-TargetResource # Only pass -Remove and/or -Replace if we have something to set/change if ($replaceUserProperties.Count -gt 0) { - $setADUserParams['Replace'] = $replaceUserProperties; + $setADUserParams['Replace'] = $replaceUserProperties } if ($removeUserProperties.Count -gt 0) { - $setADUserParams['Remove'] = $removeUserProperties; + $setADUserParams['Remove'] = $removeUserProperties } - Write-Verbose -Message ($script:localizedData.UpdatingADUser -f $UserName); - [ref] $null = Set-ADUser @setADUserParams -Enabled $Enabled; + Write-Verbose -Message ($script:localizedData.UpdatingADUser -f $UserName) + [ref] $null = Set-ADUser @setADUserParams -Enabled $Enabled } elseif (($Ensure -eq 'Absent') -and ($targetResource.Ensure -eq 'Present')) { # User exists and needs removing - Write-Verbose ($script:localizedData.RemovingADUser -f $UserName); - $adCommonParameters = Get-ADCommonParameters @PSBoundParameters; - [ref] $null = Remove-ADUser @adCommonParameters -Confirm:$false; + Write-Verbose ($script:localizedData.RemovingADUser -f $UserName) + $adCommonParameters = Get-ADCommonParameters @PSBoundParameters + [ref] $null = Remove-ADUser @adCommonParameters -Confirm:$false } } #end function Set-TargetResource @@ -1328,10 +1328,10 @@ function Assert-Parameters if (($PSBoundParameters.ContainsKey('Password')) -and ($Enabled -eq $false)) { $throwInvalidArgumentErrorParams = @{ - ErrorId = 'xADUser_DisabledAccountPasswordConflict'; - ErrorMessage = $script:localizedData.PasswordParameterConflictError -f 'Enabled', $false, 'Password'; + ErrorId = 'xADUser_DisabledAccountPasswordConflict' + ErrorMessage = $script:localizedData.PasswordParameterConflictError -f 'Enabled', $false, 'Password' } - ThrowInvalidArgumentError @throwInvalidArgumentErrorParams; + ThrowInvalidArgumentError @throwInvalidArgumentErrorParams } # ChangePasswordAtLogon cannot be set for an account that also has PasswordNeverExpires set @@ -1379,8 +1379,8 @@ function Test-Password $PasswordAuthentication ) - Write-Verbose -Message ($script:localizedData.CreatingADDomainConnection -f $DomainName); - Add-Type -AssemblyName 'System.DirectoryServices.AccountManagement'; + Write-Verbose -Message ($script:localizedData.CreatingADDomainConnection -f $DomainName) + Add-Type -AssemblyName 'System.DirectoryServices.AccountManagement' if ($DomainAdministratorCredential) { @@ -1389,7 +1389,7 @@ function Test-Password $DomainName, $DomainAdministratorCredential.UserName, $DomainAdministratorCredential.GetNetworkCredential().Password - ); + ) } else { @@ -1398,9 +1398,9 @@ function Test-Password $DomainName, $null, $null - ); + ) } - Write-Verbose -Message ($script:localizedData.CheckingADUserPassword -f $UserName); + Write-Verbose -Message ($script:localizedData.CheckingADUserPassword -f $UserName) if ($PasswordAuthentication -eq 'Negotiate') { @@ -1410,7 +1410,7 @@ function Test-Password [System.DirectoryServices.AccountManagement.ContextOptions]::Negotiate -bor [System.DirectoryServices.AccountManagement.ContextOptions]::Signing -bor [System.DirectoryServices.AccountManagement.ContextOptions]::Sealing - ); + ) } else { @@ -1418,7 +1418,7 @@ function Test-Password return $principalContext.ValidateCredentials( $UserName, $Password.GetNetworkCredential().Password - ); + ) } } #end function Test-Password diff --git a/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 b/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 index e1fe97e18..a72664ec2 100644 --- a/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 +++ b/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 @@ -98,7 +98,7 @@ function Set-TargetResource Remove-Item $rebootLogFile -ErrorAction SilentlyContinue } - break; + break } else { diff --git a/Tests/Unit/MSFT_xADDomain.Tests.ps1 b/Tests/Unit/MSFT_xADDomain.Tests.ps1 index 86d3b0671..dd7f18ad1 100644 --- a/Tests/Unit/MSFT_xADDomain.Tests.ps1 +++ b/Tests/Unit/MSFT_xADDomain.Tests.ps1 @@ -50,19 +50,19 @@ try Invoke-TestSetup InModuleScope $script:dscResourceName { - $correctDomainName = 'present.com'; - $incorrectDomainName = 'incorrect.com'; - $missingDomainName = 'missing.com'; + $correctDomainName = 'present.com' + $incorrectDomainName = 'incorrect.com' + $missingDomainName = 'missing.com' $forestMode = [Microsoft.DirectoryServices.Deployment.Types.ForestMode]::Win2012R2 $mgmtForestMode = [Microsoft.ActiveDirectory.Management.ADForestMode]::Windows2012R2Forest $domainMode = [Microsoft.DirectoryServices.Deployment.Types.DomainMode]::Win2012R2 $mgmtDomainMode = [Microsoft.ActiveDirectory.Management.ADDomainMode]::Windows2012R2Domain - $testAdminCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); - $invalidCredential = New-Object System.Management.Automation.PSCredential 'Invalid', (ConvertTo-SecureString 'InvalidPassword' -AsPlainText -Force); + $testAdminCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + $invalidCredential = New-Object System.Management.Automation.PSCredential 'Invalid', (ConvertTo-SecureString 'InvalidPassword' -AsPlainText -Force) $testDefaultParams = @{ - DomainAdministratorCredential = $testAdminCredential; - SafemodeAdministratorPassword = $testAdminCredential; + DomainAdministratorCredential = $testAdminCredential + SafemodeAdministratorPassword = $testAdminCredential } #region Function Get-TargetResource @@ -78,7 +78,7 @@ try } Mock -CommandName Get-ADForest -MockWith { [psobject]@{ForestMode = $mgmtForestMode} } - $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName; + $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName Assert-MockCalled -CommandName Assert-Module -ParameterFilter { $ModuleName -eq 'ADDSDeployment' } -Scope It } @@ -93,9 +93,9 @@ try Mock -CommandName Get-ADForest -MockWith { [psobject]@{ForestMode = $mgmtForestMode} } - $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName; + $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName - $result -is [System.Collections.Hashtable] | Should Be $true; + $result -is [System.Collections.Hashtable] | Should Be $true } It 'Calls "Get-ADDomain" without credentials if domain member' { @@ -107,7 +107,7 @@ try } } - $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName; + $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName Assert-MockCalled -CommandName Get-ADDomain -ParameterFilter { $Credential -eq $null } -Scope It } @@ -122,34 +122,34 @@ try } Mock -CommandName Get-ADForest -ParameterFilter { $Credential -eq $null } -MockWith { [psobject]@{ForestMode = $mgmtForestMode} } - $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName; + $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName Assert-MockCalled -CommandName Get-ADForest -ParameterFilter { $Credential -eq $null } -Scope It } It 'Throws "Invalid credentials" when domain is available but authentication fails' { Mock -CommandName Get-ADDomain -ParameterFilter { $Identity.ToString() -eq $incorrectDomainName } -MockWith { - Write-Error -Exception (New-Object System.Security.Authentication.AuthenticationException); + Write-Error -Exception (New-Object System.Security.Authentication.AuthenticationException) } ## Match operator is case-sensitive! - { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should Throw 'invalid credentials'; + { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should Throw 'invalid credentials' } It 'Throws "Computer is already a domain member" when is already a domain member' { Mock -CommandName Get-ADDomain -ParameterFilter { $Identity.ToString() -eq $incorrectDomainName } -MockWith { - Write-Error -Exception (New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException); + Write-Error -Exception (New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) } - { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should Throw 'Computer is already a domain member'; + { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should Throw 'Computer is already a domain member' } It 'Does not throw when domain cannot be located' { Mock -CommandName Get-ADDomain -ParameterFilter { $Identity.ToString() -eq $missingDomainName } -MockWith { - Write-Error -Exception (New-Object Microsoft.ActiveDirectory.Management.ADServerDownException); + Write-Error -Exception (New-Object Microsoft.ActiveDirectory.Management.ADServerDownException) } - { Get-TargetResource @testDefaultParams -DomainName $missingDomainName } | Should Not Throw; + { Get-TargetResource @testDefaultParams -DomainName $missingDomainName } | Should Not Throw } It 'Returns the correct domain mode' { @@ -180,76 +180,76 @@ try #region Function Test-TargetResource Describe 'xADDomain\Test-TargetResource' { - $correctDomainName = 'present.com'; - $correctChildDomainName = 'present'; - $correctDomainNetBIOSName = 'PRESENT'; - $incorrectDomainName = 'incorrect.com'; - $parentDomainName = 'parent.com'; - $testAdminCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); + $correctDomainName = 'present.com' + $correctChildDomainName = 'present' + $correctDomainNetBIOSName = 'PRESENT' + $incorrectDomainName = 'incorrect.com' + $parentDomainName = 'parent.com' + $testAdminCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) $testDefaultParams = @{ - DomainAdministratorCredential = $testAdminCredential; - SafemodeAdministratorPassword = $testAdminCredential; + DomainAdministratorCredential = $testAdminCredential + SafemodeAdministratorPassword = $testAdminCredential } $stubDomain = @{ - DomainName = $correctDomainName; - DomainNetBIOSName = $correctDomainNetBIOSName; + DomainName = $correctDomainName + DomainNetBIOSName = $correctDomainNetBIOSName } ## Get-TargetResource returns the domain FQDN for .DomainName $stubChildDomain = @{ - DomainName = "$correctChildDomainName.$parentDomainName"; - ParentDomainName = $parentDomainName; - DomainNetBIOSName = $correctDomainNetBIOSName; + DomainName = "$correctChildDomainName.$parentDomainName" + ParentDomainName = $parentDomainName + DomainNetBIOSName = $correctDomainNetBIOSName } It 'Returns "True" when "DomainName" matches' { Mock -CommandName Get-TargetResource -MockWith { return $stubDomain; } - $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName; + $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName - $result | Should Be $true; + $result | Should Be $true } It 'Returns "False" when "DomainName" does not match' { Mock -CommandName Get-TargetResource -MockWith { return $stubDomain; } - $result = Test-TargetResource @testDefaultParams -DomainName $incorrectDomainName; + $result = Test-TargetResource @testDefaultParams -DomainName $incorrectDomainName - $result | Should Be $false; + $result | Should Be $false } It 'Returns "True" when "DomainNetBIOSName" matches' { Mock -CommandName Get-TargetResource -MockWith { return $stubDomain; } - $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName -DomainNetBIOSName $correctDomainNetBIOSName; + $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName -DomainNetBIOSName $correctDomainNetBIOSName - $result | Should Be $true; + $result | Should Be $true } It 'Returns "False" when "DomainNetBIOSName" does not match' { Mock -CommandName Get-TargetResource -MockWith { return $stubDomain; } - $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName -DomainNetBIOSName 'INCORRECT'; + $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName -DomainNetBIOSName 'INCORRECT' - $result | Should Be $false; + $result | Should Be $false } It 'Returns "True" when "ParentDomainName" matches' { Mock -CommandName Get-TargetResource -MockWith { return $stubChildDomain; } - $result = Test-TargetResource @testDefaultParams -DomainName $correctChildDomainName -ParentDomainName $parentDomainName; + $result = Test-TargetResource @testDefaultParams -DomainName $correctChildDomainName -ParentDomainName $parentDomainName - $result | Should Be $true; + $result | Should Be $true } It 'Returns "False" when "ParentDomainName" does not match' { Mock -CommandName Get-TargetResource -MockWith { return $stubChildDomain; } - $result = Test-TargetResource @testDefaultParams -DomainName $correctChildDomainName -ParentDomainName 'incorrect.com'; + $result = Test-TargetResource @testDefaultParams -DomainName $correctChildDomainName -ParentDomainName 'incorrect.com' - $result | Should Be $false; + $result | Should Be $false } } @@ -275,32 +275,32 @@ try ) } - $testDomainName = 'present.com'; - $testParentDomainName = 'parent.com'; - $testDomainNetBIOSNameName = 'PRESENT'; - $testDomainForestMode = 'WinThreshold'; - $testAdminCredential = New-Object System.Management.Automation.PSCredential 'Admin', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); - $testSafemodePassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); - $testSafemodeCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testSafemodePassword; - $testDelegationCredential = New-Object System.Management.Automation.PSCredential 'Delegation', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); + $testDomainName = 'present.com' + $testParentDomainName = 'parent.com' + $testDomainNetBIOSNameName = 'PRESENT' + $testDomainForestMode = 'WinThreshold' + $testAdminCredential = New-Object System.Management.Automation.PSCredential 'Admin', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + $testSafemodePassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + $testSafemodeCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testSafemodePassword + $testDelegationCredential = New-Object System.Management.Automation.PSCredential 'Delegation', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) $newForestParams = @{ - DomainName = $testDomainName; - DomainAdministratorCredential = $testAdminCredential; - SafemodeAdministratorPassword = $testSafemodeCredential; + DomainName = $testDomainName + DomainAdministratorCredential = $testAdminCredential + SafemodeAdministratorPassword = $testSafemodeCredential } $newDomainParams = @{ - DomainName = $testDomainName; - ParentDomainName = $testParentDomainName; - DomainAdministratorCredential = $testAdminCredential; - SafemodeAdministratorPassword = $testSafemodeCredential; + DomainName = $testDomainName + ParentDomainName = $testParentDomainName + DomainAdministratorCredential = $testAdminCredential + SafemodeAdministratorPassword = $testSafemodeCredential } $stubTargetResource = @{ - DomainName = $testDomainName; - ParentDomainName = $testParentDomainName; - DomainNetBIOSName = $testDomainNetBIOSNameName; + DomainName = $testDomainName + ParentDomainName = $testParentDomainName + DomainNetBIOSName = $testDomainNetBIOSNameName ForestName = $testParentDomainName ForestMode = $testDomainForestMode DomainMode = $testDomainForestMode @@ -310,7 +310,7 @@ try It 'Calls "Install-ADDSForest" with "DomainName" when creating forest' { Mock -CommandName Install-ADDSForest -ParameterFilter { $DomainName -eq $testDomainName } - Set-TargetResource @newForestParams; + Set-TargetResource @newForestParams Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $DomainName -eq $testDomainName } -Scope It } @@ -318,7 +318,7 @@ try It 'Calls "Install-ADDSForest" with "SafemodeAdministratorPassword" when creating forest' { Mock -CommandName Install-ADDSForest -ParameterFilter { $SafemodeAdministratorPassword -eq $testSafemodePassword } - Set-TargetResource @newForestParams; + Set-TargetResource @newForestParams Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $SafemodeAdministratorPassword -eq $testSafemodePassword } -Scope It } @@ -326,7 +326,7 @@ try It 'Calls "Install-ADDSForest" with "DnsDelegationCredential" when creating forest, if specified' { Mock -CommandName Install-ADDSForest -ParameterFilter { $DnsDelegationCredential -eq $testDelegationCredential } - Set-TargetResource @newForestParams -DnsDelegationCredential $testDelegationCredential; + Set-TargetResource @newForestParams -DnsDelegationCredential $testDelegationCredential Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $DnsDelegationCredential -eq $testDelegationCredential } -Scope It } @@ -334,34 +334,34 @@ try It 'Calls "Install-ADDSForest" with "CreateDnsDelegation" when creating forest, if specified' { Mock -CommandName Install-ADDSForest -ParameterFilter { $CreateDnsDelegation -eq $true } - Set-TargetResource @newForestParams -DnsDelegationCredential $testDelegationCredential; + Set-TargetResource @newForestParams -DnsDelegationCredential $testDelegationCredential Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $CreateDnsDelegation -eq $true } -Scope It } It 'Calls "Install-ADDSForest" with "DatabasePath" when creating forest, if specified' { - $testPath = 'TestPath'; + $testPath = 'TestPath' Mock -CommandName Install-ADDSForest -ParameterFilter { $DatabasePath -eq $testPath } - Set-TargetResource @newForestParams -DatabasePath $testPath; + Set-TargetResource @newForestParams -DatabasePath $testPath Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $DatabasePath -eq $testPath } -Scope It } It 'Calls "Install-ADDSForest" with "LogPath" when creating forest, if specified' { - $testPath = 'TestPath'; + $testPath = 'TestPath' Mock -CommandName Install-ADDSForest -ParameterFilter { $LogPath -eq $testPath } - Set-TargetResource @newForestParams -LogPath $testPath; + Set-TargetResource @newForestParams -LogPath $testPath Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $LogPath -eq $testPath } -Scope It } It 'Calls "Install-ADDSForest" with "SysvolPath" when creating forest, if specified' { - $testPath = 'TestPath'; + $testPath = 'TestPath' Mock -CommandName Install-ADDSForest -ParameterFilter { $SysvolPath -eq $testPath } - Set-TargetResource @newForestParams -SysvolPath $testPath; + Set-TargetResource @newForestParams -SysvolPath $testPath Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $SysvolPath -eq $testPath } -Scope It } @@ -369,7 +369,7 @@ try It 'Calls "Install-ADDSForest" with "DomainNetbiosName" when creating forest, if specified' { Mock -CommandName Install-ADDSForest -ParameterFilter { $DomainNetbiosName -eq $testDomainNetBIOSNameName } - Set-TargetResource @newForestParams -DomainNetBIOSName $testDomainNetBIOSNameName; + Set-TargetResource @newForestParams -DomainNetBIOSName $testDomainNetBIOSNameName Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $DomainNetbiosName -eq $testDomainNetBIOSNameName } -Scope It } @@ -377,7 +377,7 @@ try It 'Calls "Install-ADDSForest" with "ForestMode" when creating forest, if specified' { Mock -CommandName Install-ADDSForest -ParameterFilter { $ForestMode -eq $testDomainForestMode } - Set-TargetResource @newForestParams -ForestMode $testDomainForestMode; + Set-TargetResource @newForestParams -ForestMode $testDomainForestMode Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $ForestMode -eq $testDomainForestMode } -Scope It } @@ -385,7 +385,7 @@ try It 'Calls "Install-ADDSForest" with "DomainMode" when creating forest, if specified' { Mock -CommandName Install-ADDSForest -ParameterFilter { $DomainMode -eq $testDomainForestMode } - Set-TargetResource @newForestParams -DomainMode $testDomainForestMode; + Set-TargetResource @newForestParams -DomainMode $testDomainForestMode Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $DomainMode -eq $testDomainForestMode } -Scope It } @@ -395,7 +395,7 @@ try It 'Calls "Install-ADDSDomain" with "NewDomainName" when creating child domain' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $NewDomainName -eq $testDomainName } - Set-TargetResource @newDomainParams; + Set-TargetResource @newDomainParams Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $NewDomainName -eq $testDomainName } -Scope It } @@ -403,7 +403,7 @@ try It 'Calls "Install-ADDSDomain" with "ParentDomainName" when creating child domain' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $ParentDomainName -eq $testParentDomainName } - Set-TargetResource @newDomainParams; + Set-TargetResource @newDomainParams Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $ParentDomainName -eq $testParentDomainName } -Scope It } @@ -411,7 +411,7 @@ try It 'Calls "Install-ADDSDomain" with "DomainType" when creating child domain' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $DomainType -eq 'ChildDomain' } - Set-TargetResource @newDomainParams; + Set-TargetResource @newDomainParams Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $DomainType -eq 'ChildDomain' } -Scope It } @@ -419,7 +419,7 @@ try It 'Calls "Install-ADDSDomain" with "SafemodeAdministratorPassword" when creating child domain' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $SafemodeAdministratorPassword -eq $testSafemodePassword } - Set-TargetResource @newDomainParams; + Set-TargetResource @newDomainParams Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $SafemodeAdministratorPassword -eq $testSafemodePassword } -Scope It } @@ -427,7 +427,7 @@ try It 'Calls "Install-ADDSDomain" with "Credential" when creating child domain' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $Credential -eq $testParentDomainName } - Set-TargetResource @newDomainParams; + Set-TargetResource @newDomainParams Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $ParentDomainName -eq $testParentDomainName } -Scope It } @@ -435,7 +435,7 @@ try It 'Calls "Install-ADDSDomain" with "ParentDomainName" when creating child domain' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $ParentDomainName -eq $testParentDomainName } - Set-TargetResource @newDomainParams; + Set-TargetResource @newDomainParams Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $ParentDomainName -eq $testParentDomainName } -Scope It } @@ -443,7 +443,7 @@ try It 'Calls "Install-ADDSDomain" with "DnsDelegationCredential" when creating child domain, if specified' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $DnsDelegationCredential -eq $testDelegationCredential } - Set-TargetResource @newDomainParams -DnsDelegationCredential $testDelegationCredential; + Set-TargetResource @newDomainParams -DnsDelegationCredential $testDelegationCredential Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $DnsDelegationCredential -eq $testDelegationCredential } -Scope It } @@ -451,34 +451,34 @@ try It 'Calls "Install-ADDSDomain" with "CreateDnsDelegation" when creating child domain, if specified' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $CreateDnsDelegation -eq $true } - Set-TargetResource @newDomainParams -DnsDelegationCredential $testDelegationCredential; + Set-TargetResource @newDomainParams -DnsDelegationCredential $testDelegationCredential Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $CreateDnsDelegation -eq $true } -Scope It } It 'Calls "Install-ADDSDomain" with "DatabasePath" when creating child domain, if specified' { - $testPath = 'TestPath'; + $testPath = 'TestPath' Mock -CommandName Install-ADDSDomain -ParameterFilter { $DatabasePath -eq $testPath } - Set-TargetResource @newDomainParams -DatabasePath $testPath; + Set-TargetResource @newDomainParams -DatabasePath $testPath Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $DatabasePath -eq $testPath } -Scope It } It 'Calls "Install-ADDSDomain" with "LogPath" when creating child domain, if specified' { - $testPath = 'TestPath'; + $testPath = 'TestPath' Mock -CommandName Install-ADDSDomain -ParameterFilter { $LogPath -eq $testPath } - Set-TargetResource @newDomainParams -LogPath $testPath; + Set-TargetResource @newDomainParams -LogPath $testPath Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $LogPath -eq $testPath } -Scope It } It 'Calls "Install-ADDSDomain" with "SysvolPath" when creating child domain, if specified' { - $testPath = 'TestPath'; + $testPath = 'TestPath' Mock -CommandName Install-ADDSDomain -ParameterFilter { $SysvolPath -eq $testPath } - Set-TargetResource @newDomainParams -SysvolPath $testPath; + Set-TargetResource @newDomainParams -SysvolPath $testPath Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $SysvolPath -eq $testPath } -Scope It } @@ -486,7 +486,7 @@ try It 'Calls "Install-ADDSDomain" with "NewDomainNetbiosName" when creating child domain, if specified' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $NewDomainNetbiosName -eq $testDomainNetBIOSNameName } - Set-TargetResource @newDomainParams -DomainNetBIOSName $testDomainNetBIOSNameName; + Set-TargetResource @newDomainParams -DomainNetBIOSName $testDomainNetBIOSNameName Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $NewDomainNetbiosName -eq $testDomainNetBIOSNameName } -Scope It } @@ -494,7 +494,7 @@ try It 'Calls "Install-ADDSDomain" with "DomainMode" when creating child domain, if specified' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $DomainMode -eq $testDomainForestMode } - Set-TargetResource @newDomainParams -DomainMode $testDomainForestMode; + Set-TargetResource @newDomainParams -DomainMode $testDomainForestMode Assert-MockCalled -CommandName Install-ADDSDomain -ParameterFilter { $DomainMode -eq $testDomainForestMode } -Scope It } diff --git a/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 b/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 index 471947270..b55ace962 100644 --- a/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 +++ b/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 @@ -39,24 +39,24 @@ try Invoke-TestSetup InModuleScope $script:dscResourceName { - $testDomainName = 'contoso.com'; + $testDomainName = 'contoso.com' $testDefaultParams = @{ - DomainName = $testDomainName; + DomainName = $testDomainName } - $testDomainController = 'testserver.contoso.com'; - $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); - $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword; + $testDomainController = 'testserver.contoso.com' + $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword $fakePasswordPolicy = @{ - ComplexityEnabled = $true; - LockoutDuration = New-TimeSpan -Minutes 30; - LockoutObservationWindow = New-TimeSpan -Minutes 30; - LockoutThreshold = 3; - MinPasswordAge = New-TimeSpan -Days 1; - MaxPasswordAge = New-TimeSpan -Days 42; - MinPasswordLength = 7; - PasswordHistoryCount = 12; - ReversibleEncryptionEnabled = $false; + ComplexityEnabled = $true + LockoutDuration = New-TimeSpan -Minutes 30 + LockoutObservationWindow = New-TimeSpan -Minutes 30 + LockoutThreshold = 3 + MinPasswordAge = New-TimeSpan -Days 1 + MaxPasswordAge = New-TimeSpan -Days 42 + MinPasswordLength = 7 + PasswordHistoryCount = 12 + ReversibleEncryptionEnabled = $false } #region Function Get-TargetResource @@ -66,7 +66,7 @@ try It 'Calls "Assert-Module" to check "ActiveDirectory" module is installed' { Mock -CommandName Get-ADDefaultDomainPasswordPolicy { return $fakePasswordPolicy; } - $result = Get-TargetResource @testDefaultParams; + $result = Get-TargetResource @testDefaultParams Assert-MockCalled -CommandName Assert-Module -ParameterFilter { $ModuleName -eq 'ActiveDirectory' } -Scope It } @@ -74,15 +74,15 @@ try It 'Returns "System.Collections.Hashtable" object type' { Mock -CommandName Get-ADDefaultDomainPasswordPolicy { return $fakePasswordPolicy; } - $result = Get-TargetResource @testDefaultParams; + $result = Get-TargetResource @testDefaultParams - $result -is [System.Collections.Hashtable] | Should Be $true; + $result -is [System.Collections.Hashtable] | Should Be $true } It 'Calls "Get-ADDefaultDomainPasswordPolicy" without credentials by default' { Mock -CommandName Get-ADDefaultDomainPasswordPolicy -ParameterFilter { $Credential -eq $null } -MockWith { return $fakePasswordPolicy; } - $result = Get-TargetResource @testDefaultParams; + $result = Get-TargetResource @testDefaultParams Assert-MockCalled -CommandName Get-ADDefaultDomainPasswordPolicy -ParameterFilter { $Credential -eq $null } -Scope It } @@ -90,7 +90,7 @@ try It 'Calls "Get-ADDefaultDomainPasswordPolicy" with credentials when specified' { Mock -CommandName Get-ADDefaultDomainPasswordPolicy -ParameterFilter { $Credential -eq $testCredential } -MockWith { return $fakePasswordPolicy; } - $result = Get-TargetResource @testDefaultParams -Credential $testCredential; + $result = Get-TargetResource @testDefaultParams -Credential $testCredential Assert-MockCalled -CommandName Get-ADDefaultDomainPasswordPolicy -ParameterFilter { $Credential -eq $testCredential } -Scope It } @@ -98,7 +98,7 @@ try It 'Calls "Get-ADDefaultDomainPasswordPolicy" without server by default' { Mock -CommandName Get-ADDefaultDomainPasswordPolicy -ParameterFilter { $Server -eq $null } -MockWith { return $fakePasswordPolicy; } - $result = Get-TargetResource @testDefaultParams; + $result = Get-TargetResource @testDefaultParams Assert-MockCalled -CommandName Get-ADDefaultDomainPasswordPolicy -ParameterFilter { $Server -eq $null } -Scope It } @@ -106,7 +106,7 @@ try It 'Calls "Get-ADDefaultDomainPasswordPolicy" with server when specified' { Mock -CommandName Get-ADDefaultDomainPasswordPolicy -ParameterFilter { $Server -eq $testDomainController } -MockWith { return $fakePasswordPolicy; } - $result = Get-TargetResource @testDefaultParams -DomainController $testDomainController; + $result = Get-TargetResource @testDefaultParams -DomainController $testDomainController Assert-MockCalled -CommandName Get-ADDefaultDomainPasswordPolicy -ParameterFilter { $Server -eq $testDomainController } -Scope It } @@ -116,38 +116,38 @@ try #region Function Test-TargetResource Describe 'xADDomainDefaultPasswordPolicy\Test-TargetResource' { - $testDomainName = 'contoso.com'; + $testDomainName = 'contoso.com' $testDefaultParams = @{ - DomainName = $testDomainName; + DomainName = $testDomainName } - $testDomainController = 'testserver.contoso.com'; - $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); - $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword; + $testDomainController = 'testserver.contoso.com' + $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword $stubPasswordPolicy = @{ - ComplexityEnabled = $true; - LockoutDuration = (New-TimeSpan -Minutes 30).TotalMinutes; - LockoutObservationWindow = (New-TimeSpan -Minutes 30).TotalMinutes; - LockoutThreshold = 3; - MinPasswordAge = (New-TimeSpan -Days 1).TotalMinutes; - MaxPasswordAge = (New-TimeSpan -Days 42).TotalMinutes; - MinPasswordLength = 7; - PasswordHistoryCount = 12; - ReversibleEncryptionEnabled = $true; + ComplexityEnabled = $true + LockoutDuration = (New-TimeSpan -Minutes 30).TotalMinutes + LockoutObservationWindow = (New-TimeSpan -Minutes 30).TotalMinutes + LockoutThreshold = 3 + MinPasswordAge = (New-TimeSpan -Days 1).TotalMinutes + MaxPasswordAge = (New-TimeSpan -Days 42).TotalMinutes + MinPasswordLength = 7 + PasswordHistoryCount = 12 + ReversibleEncryptionEnabled = $true } It 'Returns "System.Boolean" object type' { Mock -CommandName Get-TargetResource -MockWith { return $stubPasswordPolicy; } - $result = Test-TargetResource @testDefaultParams; + $result = Test-TargetResource @testDefaultParams - $result -is [System.Boolean] | Should Be $true; + $result -is [System.Boolean] | Should Be $true } It 'Calls "Get-TargetResource" with "Credential" parameter when specified' { Mock -CommandName Get-TargetResource -ParameterFilter { $Credential -eq $testCredential } { return $stubPasswordPolicy; } - $result = Test-TargetResource @testDefaultParams -Credential $testCredential; + $result = Test-TargetResource @testDefaultParams -Credential $testCredential Assert-MockCalled -CommandName Get-TargetResource -ParameterFilter { $Credential -eq $testCredential } -Scope It } @@ -155,7 +155,7 @@ try It 'Calls "Get-TargetResource" with "DomainController" parameter when specified' { Mock -CommandName Get-TargetResource -ParameterFilter { $DomainController -eq $testDomainController } { return $stubPasswordPolicy; } - $result = Test-TargetResource @testDefaultParams -DomainController $testDomainController; + $result = Test-TargetResource @testDefaultParams -DomainController $testDomainController Assert-MockCalled -CommandName Get-TargetResource -ParameterFilter { $DomainController -eq $testDomainController } -Scope It } @@ -164,34 +164,34 @@ try { It "Passes when '$propertyName' parameter matches resource property value" { Mock -CommandName Get-TargetResource -MockWith { return $stubPasswordPolicy; } - $propertyDefaultParams = $testDefaultParams.Clone(); - $propertyDefaultParams[$propertyName] = $stubPasswordPolicy[$propertyName]; + $propertyDefaultParams = $testDefaultParams.Clone() + $propertyDefaultParams[$propertyName] = $stubPasswordPolicy[$propertyName] - $result = Test-TargetResource @propertyDefaultParams; + $result = Test-TargetResource @propertyDefaultParams - $result | Should Be $true; + $result | Should Be $true } It "Fails when '$propertyName' parameter does not match resource property value" { Mock -CommandName Get-TargetResource -MockWith { return $stubPasswordPolicy; } - $propertyDefaultParams = $testDefaultParams.Clone(); + $propertyDefaultParams = $testDefaultParams.Clone() switch ($stubPasswordPolicy[$propertyName].GetType()) { 'bool' { - $propertyDefaultParams[$propertyName] = -not $stubPasswordPolicy[$propertyName]; + $propertyDefaultParams[$propertyName] = -not $stubPasswordPolicy[$propertyName] } 'string' { - $propertyDefaultParams[$propertyName] = 'not{0}' -f $stubPasswordPolicy[$propertyName]; + $propertyDefaultParams[$propertyName] = 'not{0}' -f $stubPasswordPolicy[$propertyName] } default { - $propertyDefaultParams[$propertyName] = $stubPasswordPolicy[$propertyName] + 1; + $propertyDefaultParams[$propertyName] = $stubPasswordPolicy[$propertyName] + 1 } } - $result = Test-TargetResource @propertyDefaultParams; + $result = Test-TargetResource @propertyDefaultParams - $result | Should Be $false; + $result | Should Be $false } } #end foreach property @@ -200,24 +200,24 @@ try #region Function Set-TargetResource Describe 'xADDomainDefaultPasswordPolicy\Set-TargetResource' { - $testDomainName = 'contoso.com'; + $testDomainName = 'contoso.com' $testDefaultParams = @{ - DomainName = $testDomainName; + DomainName = $testDomainName } - $testDomainController = 'testserver.contoso.com'; - $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); - $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword; + $testDomainController = 'testserver.contoso.com' + $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword $stubPasswordPolicy = @{ - ComplexityEnabled = $true; - LockoutDuration = (New-TimeSpan -Minutes 30).TotalMinutes; - LockoutObservationWindow = (New-TimeSpan -Minutes 30).TotalMinutes; - LockoutThreshold = 3; - MinPasswordAge = (New-TimeSpan -Days 1).TotalMinutes; - MaxPasswordAge = (New-TimeSpan -Days 42).TotalMinutes; - MinPasswordLength = 7; - PasswordHistoryCount = 12; - ReversibleEncryptionEnabled = $true; + ComplexityEnabled = $true + LockoutDuration = (New-TimeSpan -Minutes 30).TotalMinutes + LockoutObservationWindow = (New-TimeSpan -Minutes 30).TotalMinutes + LockoutThreshold = 3 + MinPasswordAge = (New-TimeSpan -Days 1).TotalMinutes + MaxPasswordAge = (New-TimeSpan -Days 42).TotalMinutes + MinPasswordLength = 7 + PasswordHistoryCount = 12 + ReversibleEncryptionEnabled = $true } Mock -CommandName Assert-Module -ParameterFilter { $ModuleName -eq 'ActiveDirectory' } @@ -225,7 +225,7 @@ try It 'Calls "Assert-Module" to check "ActiveDirectory" module is installed' { Mock -CommandName Set-ADDefaultDomainPasswordPolicy - $result = Set-TargetResource @testDefaultParams; + $result = Set-TargetResource @testDefaultParams Assert-MockCalled -CommandName Assert-Module -ParameterFilter { $ModuleName -eq 'ActiveDirectory' } -Scope It } @@ -233,7 +233,7 @@ try It 'Calls "Set-ADDefaultDomainPasswordPolicy" without "Credential" parameter by default' { Mock -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $Credential -eq $null } - $result = Set-TargetResource @testDefaultParams; + $result = Set-TargetResource @testDefaultParams Assert-MockCalled -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $Credential -eq $null } -Scope It } @@ -241,7 +241,7 @@ try It 'Calls "Set-ADDefaultDomainPasswordPolicy" with "Credential" parameter when specified' { Mock -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $Credential -eq $testCredential } - $result = Set-TargetResource @testDefaultParams -Credential $testCredential; + $result = Set-TargetResource @testDefaultParams -Credential $testCredential Assert-MockCalled -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $Credential -eq $testCredential } -Scope It } @@ -249,7 +249,7 @@ try It 'Calls "Set-ADDefaultDomainPasswordPolicy" without "Server" parameter by default' { Mock -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $Server -eq $null } - $result = Set-TargetResource @testDefaultParams; + $result = Set-TargetResource @testDefaultParams Assert-MockCalled -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $Server -eq $null } -Scope It } @@ -257,7 +257,7 @@ try It 'Calls "Set-ADDefaultDomainPasswordPolicy" with "Server" parameter when specified' { Mock -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $Server -eq $testDomainController } - $result = Set-TargetResource @testDefaultParams -DomainController $testDomainController; + $result = Set-TargetResource @testDefaultParams -DomainController $testDomainController Assert-MockCalled -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $Server -eq $testDomainController } -Scope It } @@ -265,11 +265,11 @@ try foreach ($propertyName in $stubPasswordPolicy.Keys) { It "Calls 'Set-ADDefaultDomainPasswordPolicy' with '$propertyName' parameter when specified" { - $propertyDefaultParams = $testDefaultParams.Clone(); - $propertyDefaultParams[$propertyName] = $stubPasswordPolicy[$propertyName]; + $propertyDefaultParams = $testDefaultParams.Clone() + $propertyDefaultParams[$propertyName] = $stubPasswordPolicy[$propertyName] Mock -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $PSBoundParameters.ContainsKey($propertyName) } - $result = Set-TargetResource @propertyDefaultParams; + $result = Set-TargetResource @propertyDefaultParams Assert-MockCalled -CommandName Set-ADDefaultDomainPasswordPolicy -ParameterFilter { $PSBoundParameters.ContainsKey($propertyName) } -Scope It } diff --git a/Tests/Unit/MSFT_xADGroup.Tests.ps1 b/Tests/Unit/MSFT_xADGroup.Tests.ps1 index 8428a6c49..64322d7b3 100644 --- a/Tests/Unit/MSFT_xADGroup.Tests.ps1 +++ b/Tests/Unit/MSFT_xADGroup.Tests.ps1 @@ -41,60 +41,60 @@ try InModuleScope $script:dscResourceName { $testPresentParams = @{ GroupName = 'TestGroup' - GroupScope = 'Global'; - Category = 'Security'; - Path = 'OU=Fake,DC=contoso,DC=com'; - Description = 'Test AD group description'; - DisplayName = 'Test display name'; - Ensure = 'Present'; - Notes = 'This is a test AD group'; - ManagedBy = 'CN=User 1,CN=Users,DC=contoso,DC=com'; + GroupScope = 'Global' + Category = 'Security' + Path = 'OU=Fake,DC=contoso,DC=com' + Description = 'Test AD group description' + DisplayName = 'Test display name' + Ensure = 'Present' + Notes = 'This is a test AD group' + ManagedBy = 'CN=User 1,CN=Users,DC=contoso,DC=com' } - $testAbsentParams = $testPresentParams.Clone(); - $testAbsentParams['Ensure'] = 'Absent'; + $testAbsentParams = $testPresentParams.Clone() + $testAbsentParams['Ensure'] = 'Absent' $testPresentParamsMultiDomain = $testPresentParams.Clone() $testPresentParamsMultiDomain.MembershipAttribute = 'DistinguishedName' $fakeADGroup = @{ - Name = $testPresentParams.GroupName; - Identity = $testPresentParams.GroupName; - GroupScope = $testPresentParams.GroupScope; - GroupCategory = $testPresentParams.Category; - DistinguishedName = "CN=$($testPresentParams.GroupName),$($testPresentParams.Path)"; - Description = $testPresentParams.Description; - DisplayName = $testPresentParams.DisplayName; - ManagedBy = $testPresentParams.ManagedBy; - Info = $testPresentParams.Notes; + Name = $testPresentParams.GroupName + Identity = $testPresentParams.GroupName + GroupScope = $testPresentParams.GroupScope + GroupCategory = $testPresentParams.Category + DistinguishedName = "CN=$($testPresentParams.GroupName),$($testPresentParams.Path)" + Description = $testPresentParams.Description + DisplayName = $testPresentParams.DisplayName + ManagedBy = $testPresentParams.ManagedBy + Info = $testPresentParams.Notes } $fakeADUser1 = [PSCustomObject] @{ - DistinguishedName = 'CN=User 1,CN=Users,DC=contoso,DC=com'; - ObjectGUID = 'a97cc867-0c9e-4928-8387-0dba0c883b8e'; - SamAccountName = 'USER1'; + DistinguishedName = 'CN=User 1,CN=Users,DC=contoso,DC=com' + ObjectGUID = 'a97cc867-0c9e-4928-8387-0dba0c883b8e' + SamAccountName = 'USER1' SID = 'S-1-5-21-1131554080-2861379300-292325817-1106' } $fakeADUser2 = [PSCustomObject] @{ - DistinguishedName = 'CN=User 2,CN=Users,DC=contoso,DC=com'; - ObjectGUID = 'a97cc867-0c9e-4928-8387-0dba0c883b8f'; - SamAccountName = 'USER2'; + DistinguishedName = 'CN=User 2,CN=Users,DC=contoso,DC=com' + ObjectGUID = 'a97cc867-0c9e-4928-8387-0dba0c883b8f' + SamAccountName = 'USER2' SID = 'S-1-5-21-1131554080-2861379300-292325817-1107' } $fakeADUser3 = [PSCustomObject] @{ - DistinguishedName = 'CN=User 3,CN=Users,DC=contoso,DC=com'; - ObjectGUID = 'a97cc867-0c9e-4928-8387-0dba0c883b90'; - SamAccountName = 'USER3'; + DistinguishedName = 'CN=User 3,CN=Users,DC=contoso,DC=com' + ObjectGUID = 'a97cc867-0c9e-4928-8387-0dba0c883b90' + SamAccountName = 'USER3' SID = 'S-1-5-21-1131554080-2861379300-292325817-1108' } $fakeADUser4 = [PSCustomObject] @{ - DistinguishedName = 'CN=User 4,CN=Users,DC=sub,DC=contoso,DC=com'; - ObjectGUID = 'ebafa34e-b020-40cd-8652-ee7286419869'; - SamAccountName = 'USER4'; + DistinguishedName = 'CN=User 4,CN=Users,DC=sub,DC=contoso,DC=com' + ObjectGUID = 'ebafa34e-b020-40cd-8652-ee7286419869' + SamAccountName = 'USER4' SID = 'S-1-5-21-1131554080-2861379300-292325817-1109' } - $testDomainController = 'TESTDC'; - $testCredentials = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); + $testDomainController = 'TESTDC' + $testCredentials = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) #region Function Get-TargetResource Describe 'xADGroup\Get-TargetResource' { @@ -104,7 +104,7 @@ try Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - $result = Get-TargetResource @testPresentParams; # -DomainName $correctDomainName; + $result = Get-TargetResource @testPresentParams; # -DomainName $correctDomainName Assert-MockCalled -CommandName Assert-Module -ParameterFilter { $ModuleName -eq 'ActiveDirectory' } -Scope It } @@ -113,13 +113,13 @@ try Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - (Get-TargetResource @testPresentParams).Ensure | Should Be 'Present'; + (Get-TargetResource @testPresentParams).Ensure | Should Be 'Present' } It "Returns 'Ensure' is 'Absent' when group does not exist" { Mock -CommandName Get-ADGroup { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } - (Get-TargetResource @testPresentParams).Ensure | Should Be 'Absent'; + (Get-TargetResource @testPresentParams).Ensure | Should Be 'Absent' } @@ -127,7 +127,7 @@ try Mock -CommandName Get-ADGroup -ParameterFilter { $Server -eq $testDomainController } -MockWith { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - Get-TargetResource @testPresentParams -DomainController $testDomainController; + Get-TargetResource @testPresentParams -DomainController $testDomainController Assert-MockCalled -CommandName Get-ADGroup -ParameterFilter { $Server -eq $testDomainController } -Scope It } @@ -136,7 +136,7 @@ try Mock -CommandName Get-ADGroup -ParameterFilter { $Credential -eq $testCredentials } -MockWith { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - Get-TargetResource @testPresentParams -Credential $testCredentials; + Get-TargetResource @testPresentParams -Credential $testCredentials Assert-MockCalled -CommandName Get-ADGroup -ParameterFilter { $Credential -eq $testCredentials } -Scope It } @@ -145,7 +145,7 @@ try Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember -ParameterFilter { $Server -eq $testDomainController } -MockWith { return @($fakeADUser1, $fakeADUser2); } - Get-TargetResource @testPresentParams -DomainController $testDomainController; + Get-TargetResource @testPresentParams -DomainController $testDomainController Assert-MockCalled -CommandName Get-ADGroupMember -ParameterFilter { $Server -eq $testDomainController } -Scope It } @@ -154,7 +154,7 @@ try Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember -ParameterFilter { $Credential -eq $testCredentials } -MockWith { return @($fakeADUser1, $fakeADUser2); } - Get-TargetResource @testPresentParams -Credential $testCredentials; + Get-TargetResource @testPresentParams -Credential $testCredentials Assert-MockCalled -CommandName Get-ADGroupMember -ParameterFilter { $Credential -eq $testCredentials } -Scope It } @@ -172,63 +172,63 @@ try Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser1.$attribute, $fakeADUser2.$attribute -MembershipAttribute $attribute; + $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser1.$attribute, $fakeADUser2.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $true; + $targetResource | Should Be $true } It "Fails when group membership counts do not match using '$attribute'" { Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1); } - $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser2.$attribute, $fakeADUser3.$attribute -MembershipAttribute $attribute; + $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser2.$attribute, $fakeADUser3.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $false; + $targetResource | Should Be $false } It "Fails when group 'Members' do not match using '$attribute'" { Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser2.$attribute, $fakeADUser3.$attribute -MembershipAttribute $attribute; + $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser2.$attribute, $fakeADUser3.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $false; + $targetResource | Should Be $false } It "Passes when specified 'MembersToInclude' match using '$attribute'" { Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - $targetResource = Test-TargetResource @testPresentParams -MembersToInclude $fakeADUser2.$attribute -MembershipAttribute $attribute; + $targetResource = Test-TargetResource @testPresentParams -MembersToInclude $fakeADUser2.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $true; + $targetResource | Should Be $true } It "Fails when specified 'MembersToInclude' are missing using '$attribute'" { Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - $targetResource = Test-TargetResource @testPresentParams -MembersToInclude $fakeADUser3.$attribute -MembershipAttribute $attribute; + $targetResource = Test-TargetResource @testPresentParams -MembersToInclude $fakeADUser3.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $false; + $targetResource | Should Be $false } It "Passes when specified 'MembersToExclude' are missing using '$attribute'" { Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - $targetResource = Test-TargetResource @testPresentParams -MembersToExclude $fakeADUser3.$attribute -MembershipAttribute $attribute; + $targetResource = Test-TargetResource @testPresentParams -MembersToExclude $fakeADUser3.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $true; + $targetResource | Should Be $true } It "Fails when when specified 'MembersToExclude' match using '$attribute'" { Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - $targetResource = Test-TargetResource @testPresentParams -MembersToExclude $fakeADUser2.$attribute -MembershipAttribute $attribute; + $targetResource = Test-TargetResource @testPresentParams -MembersToExclude $fakeADUser2.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $false; + $targetResource | Should Be $false } } #end foreach attribute @@ -241,72 +241,72 @@ try It "Fails when group exists, 'Ensure' is 'Present' but 'Scope' is wrong" { Mock -CommandName Get-TargetResource -MockWith { - $duffADGroup = $testPresentParams.Clone(); - $duffADGroup['GroupScope'] = 'Universal'; - return $duffADGroup; + $duffADGroup = $testPresentParams.Clone() + $duffADGroup['GroupScope'] = 'Universal' + return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false; + Test-TargetResource @testPresentParams | Should Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Category' is wrong" { Mock -CommandName Get-TargetResource -MockWith { - $duffADGroup = $testPresentParams.Clone(); - $duffADGroup['Category'] = 'Distribution'; - return $duffADGroup; + $duffADGroup = $testPresentParams.Clone() + $duffADGroup['Category'] = 'Distribution' + return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false; + Test-TargetResource @testPresentParams | Should Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Path' is wrong" { Mock -CommandName Get-TargetResource -MockWith { - $duffADGroup = $testPresentParams.Clone(); - $duffADGroup['Path'] = 'OU=WrongPath,DC=contoso,DC=com'; - return $duffADGroup; + $duffADGroup = $testPresentParams.Clone() + $duffADGroup['Path'] = 'OU=WrongPath,DC=contoso,DC=com' + return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false; + Test-TargetResource @testPresentParams | Should Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Description' is wrong" { Mock -CommandName Get-TargetResource -MockWith { - $duffADGroup = $testPresentParams.Clone(); - $duffADGroup['Description'] = 'Test AD group description is wrong'; - return $duffADGroup; + $duffADGroup = $testPresentParams.Clone() + $duffADGroup['Description'] = 'Test AD group description is wrong' + return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false; + Test-TargetResource @testPresentParams | Should Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'DisplayName' is wrong" { Mock -CommandName Get-TargetResource -MockWith { - $duffADGroup = $testPresentParams.Clone(); - $duffADGroup['DisplayName'] = 'Wrong display name'; - return $duffADGroup; + $duffADGroup = $testPresentParams.Clone() + $duffADGroup['DisplayName'] = 'Wrong display name' + return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false; + Test-TargetResource @testPresentParams | Should Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'ManagedBy' is wrong" { Mock -CommandName Get-TargetResource -MockWith { - $duffADGroup = $testPresentParams.Clone(); - $duffADGroup['ManagedBy'] = $fakeADUser3.DistinguishedName; - return $duffADGroup; + $duffADGroup = $testPresentParams.Clone() + $duffADGroup['ManagedBy'] = $fakeADUser3.DistinguishedName + return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false; + Test-TargetResource @testPresentParams | Should Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Notes' is wrong" { Mock -CommandName Get-TargetResource -MockWith { - $duffADGroup = $testPresentParams.Clone(); - $duffADGroup['Notes'] = 'These notes are clearly wrong'; - return $duffADGroup; + $duffADGroup = $testPresentParams.Clone() + $duffADGroup['Notes'] = 'These notes are clearly wrong' + return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false; + Test-TargetResource @testPresentParams | Should Be $false } It "Fails when group exists and 'Ensure' is 'Absent'" { @@ -339,15 +339,15 @@ try Mock -CommandName Set-ADGroup Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } - Set-TargetResource @testPresentParams; + Set-TargetResource @testPresentParams Assert-MockCalled -CommandName New-ADGroup -Scope It } $testProperties = @{ - Description = 'Test AD Group description is wrong'; - ManagedBy = $fakeADUser3.DistinguishedName; - DisplayName = 'Test DisplayName'; + Description = 'Test AD Group description is wrong' + ManagedBy = $fakeADUser3.DistinguishedName + DisplayName = 'Test DisplayName' } foreach ($property in $testProperties.Keys) @@ -356,14 +356,14 @@ try Mock -CommandName Set-ADGroup Mock -CommandName Get-ADGroupMember Mock -CommandName Get-ADGroup -MockWith { - $duffADGroup = $fakeADGroup.Clone(); - $duffADGroup[$property] = $testProperties.$property; - return $duffADGroup; + $duffADGroup = $fakeADGroup.Clone() + $duffADGroup[$property] = $testProperties.$property + return $duffADGroup } - Set-TargetResource @testPresentParams; + Set-TargetResource @testPresentParams - Assert-MockCalled -CommandName Set-ADGroup -Scope It -Exactly 1; + Assert-MockCalled -CommandName Set-ADGroup -Scope It -Exactly 1 } } @@ -371,42 +371,42 @@ try Mock -CommandName Set-ADGroup -ParameterFilter { $GroupCategory -eq $testPresentParams.Category } Mock -CommandName Get-ADGroupMember Mock -CommandName Get-ADGroup -MockWith { - $duffADGroup = $fakeADGroup.Clone(); - $duffADGroup['GroupCategory'] = 'Distribution'; - return $duffADGroup; + $duffADGroup = $fakeADGroup.Clone() + $duffADGroup['GroupCategory'] = 'Distribution' + return $duffADGroup } - Set-TargetResource @testPresentParams; + Set-TargetResource @testPresentParams - Assert-MockCalled -CommandName Set-ADGroup -ParameterFilter { $GroupCategory -eq $testPresentParams.Category } -Scope It -Exactly 1; + Assert-MockCalled -CommandName Set-ADGroup -ParameterFilter { $GroupCategory -eq $testPresentParams.Category } -Scope It -Exactly 1 } It "Calls 'Set-ADGroup' when 'Ensure' is 'Present' and 'Notes' is specified" { Mock -CommandName Set-ADGroup -ParameterFilter { $Replace -ne $null } Mock -CommandName Get-ADGroupMember Mock -CommandName Get-ADGroup { - $duffADGroup = $fakeADGroup.Clone(); - $duffADGroup['Info'] = 'My test note..'; - return $duffADGroup; + $duffADGroup = $fakeADGroup.Clone() + $duffADGroup['Info'] = 'My test note..' + return $duffADGroup } - Set-TargetResource @testPresentParams; + Set-TargetResource @testPresentParams - Assert-MockCalled -CommandName Set-ADGroup -ParameterFilter { $Replace -ne $null } -Scope It -Exactly 1; + Assert-MockCalled -CommandName Set-ADGroup -ParameterFilter { $Replace -ne $null } -Scope It -Exactly 1 } It "Calls 'Set-ADGroup' twice when 'Ensure' is 'Present', the group exists but the 'Scope' has changed" { Mock -CommandName Set-ADGroup Mock -CommandName Get-ADGroupMember Mock -CommandName Get-ADGroup -MockWith { - $duffADGroup = $fakeADGroup.Clone(); - $duffADGroup['GroupScope'] = 'DomainLocal'; - return $duffADGroup; + $duffADGroup = $fakeADGroup.Clone() + $duffADGroup['GroupScope'] = 'DomainLocal' + return $duffADGroup } - Set-TargetResource @testPresentParams; + Set-TargetResource @testPresentParams - Assert-MockCalled -CommandName Set-ADGroup -Scope It -Exactly 2; + Assert-MockCalled -CommandName Set-ADGroup -Scope It -Exactly 2 } It "Adds group members when 'Ensure' is 'Present', the group exists and 'Members' are specified" { @@ -415,7 +415,7 @@ try Mock -CommandName Add-ADCommonGroupMember Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } - Set-TargetResource @testPresentParams -Members @($fakeADUser1.SamAccountName, $fakeADUser2.SamAccountName); + Set-TargetResource @testPresentParams -Members @($fakeADUser1.SamAccountName, $fakeADUser2.SamAccountName) Assert-MockCalled -CommandName Add-ADCommonGroupMember -Scope It } @@ -429,7 +429,7 @@ try Mock -CommandName Get-ADDomainNameFromDistinguishedName -MockWith { return 'contoso.com' } Mock -CommandName Write-Verbose -ParameterFilter { $Message -and $Message -match 'Group membership objects are in .* different AD Domains.'} - Set-TargetResource @testPresentParamsMultiDomain -Members @($fakeADUser1.distinguishedName, $fakeADUser2.distinguishedName); + Set-TargetResource @testPresentParamsMultiDomain -Members @($fakeADUser1.distinguishedName, $fakeADUser2.distinguishedName) Assert-MockCalled -CommandName Get-ADDomainNameFromDistinguishedName Assert-MockCalled -CommandName Add-ADCommonGroupMember -Scope It @@ -460,7 +460,7 @@ try } Mock -CommandName Write-Verbose -ParameterFilter { $Message -and $Message -match 'Group membership objects are in .* different AD Domains.'} - Set-TargetResource @testPresentParamsMultiDomain -Members @($fakeADUser1.distinguishedName, $fakeADUser4.distinguishedName); + Set-TargetResource @testPresentParamsMultiDomain -Members @($fakeADUser1.distinguishedName, $fakeADUser4.distinguishedName) Assert-MockCalled -CommandName Get-ADDomainNameFromDistinguishedName Assert-MockCalled -CommandName Add-ADCommonGroupMember -Scope It @@ -473,7 +473,7 @@ try Mock -CommandName Add-ADCommonGroupMember Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } - Set-TargetResource @testPresentParams -MembersToInclude @($fakeADUser1.SamAccountName, $fakeADUser2.SamAccountName); + Set-TargetResource @testPresentParams -MembersToInclude @($fakeADUser1.SamAccountName, $fakeADUser2.SamAccountName) Assert-MockCalled -CommandName Add-ADCommonGroupMember -Scope It } @@ -483,12 +483,12 @@ try Mock -CommandName Get-ADGroupMember Mock -CommandName Move-ADObject Mock -CommandName Get-ADGroup -MockWith { - $duffADGroup = $fakeADGroup.Clone(); - $duffADGroup['DistinguishedName'] = "CN=$($testPresentParams.GroupName),OU=WrongPath,DC=contoso,DC=com"; - return $duffADGroup; + $duffADGroup = $fakeADGroup.Clone() + $duffADGroup['DistinguishedName'] = "CN=$($testPresentParams.GroupName),OU=WrongPath,DC=contoso,DC=com" + return $duffADGroup } - Set-TargetResource @testPresentParams; + Set-TargetResource @testPresentParams Assert-MockCalled -CommandName Move-ADObject -Scope It } @@ -500,10 +500,10 @@ try Mock -CommandName Add-ADCommonGroupMember Mock -CommandName Remove-ADGroupMember - Set-TargetResource @testPresentParams -Members $fakeADuser1.SamAccountName; + Set-TargetResource @testPresentParams -Members $fakeADuser1.SamAccountName - Assert-MockCalled -CommandName Remove-ADGroupMember -Scope It -Exactly 1; - Assert-MockCalled -CommandName Add-ADCommonGroupMember -Scope It -Exactly 1; + Assert-MockCalled -CommandName Remove-ADGroupMember -Scope It -Exactly 1 + Assert-MockCalled -CommandName Add-ADCommonGroupMember -Scope It -Exactly 1 } It "Does not reset group membership when 'Ensure' is 'Present' and existing group is empty" { @@ -512,9 +512,9 @@ try Mock -CommandName Get-ADGroupMember Mock -CommandName Remove-ADGroupMember - Set-TargetResource @testPresentParams -MembersToExclude $fakeADuser1.SamAccountName; + Set-TargetResource @testPresentParams -MembersToExclude $fakeADuser1.SamAccountName - Assert-MockCalled -CommandName Remove-ADGroupMember -Scope It -Exactly 0; + Assert-MockCalled -CommandName Remove-ADGroupMember -Scope It -Exactly 0 } It "Removes members when 'Ensure' is 'Present' and 'MembersToExclude' is incorrect" { @@ -523,9 +523,9 @@ try Mock -CommandName Get-ADGroupMember -MockWith { return @($fakeADUser1, $fakeADUser2); } Mock -CommandName Remove-ADGroupMember - Set-TargetResource @testPresentParams -MembersToExclude $fakeADuser1.SamAccountName; + Set-TargetResource @testPresentParams -MembersToExclude $fakeADuser1.SamAccountName - Assert-MockCalled -CommandName Remove-ADGroupMember -Scope It -Exactly 1; + Assert-MockCalled -CommandName Remove-ADGroupMember -Scope It -Exactly 1 } It "Adds members when 'Ensure' is 'Present' and 'MembersToInclude' is incorrect" { @@ -534,16 +534,16 @@ try Mock -CommandName Get-ADGroupMember -MockWith { return @($fakeADUser1, $fakeADUser2); } Mock -CommandName Add-ADCommonGroupMember - Set-TargetResource @testPresentParams -MembersToInclude $fakeADuser3.SamAccountName; + Set-TargetResource @testPresentParams -MembersToInclude $fakeADuser3.SamAccountName - Assert-MockCalled -CommandName Add-ADCommonGroupMember -Scope It -Exactly 1; + Assert-MockCalled -CommandName Add-ADCommonGroupMember -Scope It -Exactly 1 } It "Removes group when 'Ensure' is 'Absent' and group exists" { Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup; } Mock -CommandName Remove-ADGroup - Set-TargetResource @testAbsentParams; + Set-TargetResource @testAbsentParams Assert-MockCalled -CommandName Remove-ADGroup -Scope It } @@ -554,7 +554,7 @@ try Mock -CommandName Get-ADGroupMember Mock -CommandName Set-ADGroup -ParameterFilter { $Credential -eq $testCredentials } - Set-TargetResource @testPresentParams -Credential $testCredentials; + Set-TargetResource @testPresentParams -Credential $testCredentials Assert-MockCalled -CommandName Set-ADGroup -ParameterFilter { $Credential -eq $testCredentials } -Scope It } @@ -564,7 +564,7 @@ try Mock -CommandName Set-ADGroup -ParameterFilter { $Credential -eq $testCredentials } Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } - Set-TargetResource @testPresentParams -Credential $testCredentials; + Set-TargetResource @testPresentParams -Credential $testCredentials Assert-MockCalled -CommandName Set-ADGroup -ParameterFilter { $Credential -eq $testCredentials } -Scope It } @@ -574,12 +574,12 @@ try Mock -CommandName Get-ADGroupMember Mock -CommandName Move-ADObject -ParameterFilter { $Credential -eq $testCredentials } Mock -CommandName Get-ADGroup -MockWith { - $duffADGroup = $fakeADGroup.Clone(); - $duffADGroup['DistinguishedName'] = "CN=$($testPresentParams.GroupName),OU=WrongPath,DC=contoso,DC=com"; - return $duffADGroup; + $duffADGroup = $fakeADGroup.Clone() + $duffADGroup['DistinguishedName'] = "CN=$($testPresentParams.GroupName),OU=WrongPath,DC=contoso,DC=com" + return $duffADGroup } - Set-TargetResource @testPresentParams -Credential $testCredentials; + Set-TargetResource @testPresentParams -Credential $testCredentials Assert-MockCalled -CommandName Move-ADObject -ParameterFilter { $Credential -eq $testCredentials } -Scope It } @@ -655,7 +655,7 @@ try Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } Mock -CommandName Restore-ADCommonObject -MockWith { return [PSCustomObject] $fakeADGroup;} - Set-TargetResource @restoreParam; + Set-TargetResource @restoreParam Assert-MockCalled -CommandName Restore-AdCommonObject -Scope It Assert-MockCalled -CommandName New-ADGroup -Scope It -Exactly -Times 0 @@ -670,7 +670,7 @@ try Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } Mock -CommandName Restore-ADCommonObject - Set-TargetResource @restoreParam; + Set-TargetResource @restoreParam Assert-MockCalled -CommandName Restore-AdCommonObject -Scope It Assert-MockCalled -CommandName New-ADGroup -Scope It diff --git a/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 b/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 index 55d0595c1..ffe98a7f2 100644 --- a/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 +++ b/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 @@ -58,7 +58,7 @@ try $mockPath = 'OU=Fake,DC=contoso,DC=com' $mockDomainController = 'MockDC' - $mockCredentials = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); + $mockCredentials = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) $mockADUSer = @{ SamAccountName = 'User1' diff --git a/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 b/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 index 31486a75b..0e97af33f 100644 --- a/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 +++ b/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 @@ -44,22 +44,22 @@ try function Remove-ADOrganizationalUnit { param ($Name, $Credential) } function New-ADOrganizationalUnit { param ($Name, $Credential) } - $testCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force); + $testCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) $testPresentParams = @{ Name = 'TestOU' - Path = 'OU=Fake,DC=contoso,DC=com'; - Description = 'Test AD OU description'; - Ensure = 'Present'; + Path = 'OU=Fake,DC=contoso,DC=com' + Description = 'Test AD OU description' + Ensure = 'Present' } - $testAbsentParams = $testPresentParams.Clone(); - $testAbsentParams['Ensure'] = 'Absent'; + $testAbsentParams = $testPresentParams.Clone() + $testAbsentParams['Ensure'] = 'Absent' $protectedFakeAdOu = @{ - Name = $testPresentParams.Name; - ProtectedFromAccidentalDeletion = $true; - Description = $testPresentParams.Description; + Name = $testPresentParams.Name + ProtectedFromAccidentalDeletion = $true + Description = $testPresentParams.Description } #region Function Get-TargetResource @@ -99,8 +99,8 @@ try It 'Returns "ProtectedFromAccidentalDeletion" = "$false" when OU is not protected' { Mock -CommandName Assert-Module Mock -CommandName Get-ADOrganizationalUnit -MockWith { - $unprotectedFakeAdOu = $protectedFakeAdOu.Clone(); - $unprotectedFakeAdOu['ProtectedFromAccidentalDeletion'] = $false; + $unprotectedFakeAdOu = $protectedFakeAdOu.Clone() + $unprotectedFakeAdOu['ProtectedFromAccidentalDeletion'] = $false return [PSCustomObject] $unprotectedFakeAdOu } $targetResource = Get-TargetResource -Name $testPresentParams.Name -Path $testPresentParams.Path @@ -111,8 +111,8 @@ try It 'Returns an empty description' { Mock -CommandName Assert-Module Mock -CommandName Get-ADOrganizationalUnit -MockWith { - $noDescriptionFakeAdOu = $protectedFakeAdOu.Clone(); - $noDescriptionFakeAdOu['Description'] = ''; + $noDescriptionFakeAdOu = $protectedFakeAdOu.Clone() + $noDescriptionFakeAdOu['Description'] = '' return [PSCustomObject] $noDescriptionFakeAdOu } @@ -291,7 +291,7 @@ try Mock -CommandName Get-TargetResource -MockWith { return @{Ensure = 'Absent'}} Mock -CommandName Restore-ADCommonObject -MockWith { return [PSCustomObject] $protectedFakeAdOu } - Set-TargetResource @restoreParam; + Set-TargetResource @restoreParam Assert-MockCalled -CommandName Restore-AdCommonObject -Scope It Assert-MockCalled -CommandName New-ADOrganizationalUnit -Scope It -Exactly -Times 0 @@ -304,7 +304,7 @@ try Mock -CommandName New-ADOrganizationalUnit Mock -CommandName Restore-ADCommonObject - Set-TargetResource @restoreParam; + Set-TargetResource @restoreParam Assert-MockCalled -CommandName Restore-AdCommonObject -Scope It Assert-MockCalled -CommandName New-ADOrganizationalUnit -Scope It diff --git a/Tests/Unit/MSFT_xADUser.Tests.ps1 b/Tests/Unit/MSFT_xADUser.Tests.ps1 index 4368e6f0e..16ed801a4 100644 --- a/Tests/Unit/MSFT_xADUser.Tests.ps1 +++ b/Tests/Unit/MSFT_xADUser.Tests.ps1 @@ -65,7 +65,7 @@ try 'EmailAddress', 'EmployeeID', 'EmployeeNumber', 'HomeDirectory', 'HomeDrive', 'HomePage', 'ProfilePath', 'LogonScript', 'Notes', 'OfficePhone', 'MobilePhone', 'Fax', 'Pager', 'IPPhone', 'HomePhone', 'CommonName' ) - $testBooleanProperties = @('PasswordNeverExpires', 'CannotChangePassword', 'ChangePasswordAtLogon', 'TrustedForDelegation', 'Enabled'); + $testBooleanProperties = @('PasswordNeverExpires', 'CannotChangePassword', 'ChangePasswordAtLogon', 'TrustedForDelegation', 'Enabled') $testArrayProperties = @('ServicePrincipalNames') #region Function Get-TargetResource From 7d2ed6ba1e6120ef5649ffff57674c0692f14a7f Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 09:54:52 +0200 Subject: [PATCH 02/29] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb6ab0c6e..ce3aed627 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,8 @@ used to enforce the `Enabled` property of computer accounts. This resource replaces the deprecated `Enabled` property in the resource xADComputer. + - Cleanup of code + - Removed semicolon throughout where it is not needed. - Changes to xADComputer - Refactored the resource and the unit tests. - BREAKING CHANGE: The `Enabled` property is **DEPRECATED** and is no From 8aff5a7fc089935a38122ae6dafff00a3a71e716 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 10:01:21 +0200 Subject: [PATCH 03/29] Migrate tests to Pester syntax v4.x (issue #322) --- CHANGELOG.md | 1 + Tests/Unit/MSFT_xADDomain.Tests.ps1 | 24 +-- ...T_xADDomainDefaultPasswordPolicy.Tests.ps1 | 8 +- Tests/Unit/MSFT_xADGroup.Tests.ps1 | 44 +++--- Tests/Unit/MSFT_xADKDSKey.Tests.ps1 | 6 +- .../MSFT_xADManagedServiceAccount.Tests.ps1 | 8 +- .../MSFT_xADObjectPermissionEntry.Tests.ps1 | 44 +++--- .../Unit/MSFT_xADOrganizationalUnit.Tests.ps1 | 28 ++-- Tests/Unit/MSFT_xADReplicationSite.Tests.ps1 | 20 +-- .../Unit/MSFT_xADReplicationSubnet.Tests.ps1 | 36 ++--- .../MSFT_xADServicePrincipalName.Tests.ps1 | 36 ++--- Tests/Unit/MSFT_xADUser.Tests.ps1 | 56 +++---- Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 | 34 ++--- Tests/Unit/xActiveDirectory.Common.Tests.ps1 | 138 +++++++++--------- 14 files changed, 242 insertions(+), 241 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce3aed627..b57a84cf2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ xADComputer. - Cleanup of code - Removed semicolon throughout where it is not needed. + - Migrate tests to Pester syntax v4.x ([issue #322](https://github.com/PowerShell/xActiveDirectory/issues/322)). - Changes to xADComputer - Refactored the resource and the unit tests. - BREAKING CHANGE: The `Enabled` property is **DEPRECATED** and is no diff --git a/Tests/Unit/MSFT_xADDomain.Tests.ps1 b/Tests/Unit/MSFT_xADDomain.Tests.ps1 index dd7f18ad1..faa9eadb7 100644 --- a/Tests/Unit/MSFT_xADDomain.Tests.ps1 +++ b/Tests/Unit/MSFT_xADDomain.Tests.ps1 @@ -95,7 +95,7 @@ try $result = Get-TargetResource @testDefaultParams -DomainName $correctDomainName - $result -is [System.Collections.Hashtable] | Should Be $true + $result -is [System.Collections.Hashtable] | Should -Be $true } It 'Calls "Get-ADDomain" without credentials if domain member' { @@ -133,7 +133,7 @@ try } ## Match operator is case-sensitive! - { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should Throw 'invalid credentials' + { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should -Throw 'invalid credentials' } It 'Throws "Computer is already a domain member" when is already a domain member' { @@ -141,7 +141,7 @@ try Write-Error -Exception (New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) } - { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should Throw 'Computer is already a domain member' + { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should -Throw 'Computer is already a domain member' } It 'Does not throw when domain cannot be located' { @@ -149,7 +149,7 @@ try Write-Error -Exception (New-Object Microsoft.ActiveDirectory.Management.ADServerDownException) } - { Get-TargetResource @testDefaultParams -DomainName $missingDomainName } | Should Not Throw + { Get-TargetResource @testDefaultParams -DomainName $missingDomainName } | Should -Not -Throw } It 'Returns the correct domain mode' { @@ -161,7 +161,7 @@ try } Mock -CommandName Get-ADForest -MockWith { [psobject]@{ForestMode = $mgmtForestMode} } - (Get-TargetResource @testDefaultParams -DomainName $correctDomainName).DomainMode | Should Be $domainMode + (Get-TargetResource @testDefaultParams -DomainName $correctDomainName).DomainMode | Should -Be $domainMode } It 'Returns the correct forest mode' { @@ -173,7 +173,7 @@ try } Mock -CommandName Get-ADForest -MockWith { [psobject]@{ForestMode = $mgmtForestMode} } - (Get-TargetResource @testDefaultParams -DomainName $correctDomainName).ForestMode | Should Be $forestMode + (Get-TargetResource @testDefaultParams -DomainName $correctDomainName).ForestMode | Should -Be $forestMode } } #endregion @@ -209,7 +209,7 @@ try $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName - $result | Should Be $true + $result | Should -Be $true } It 'Returns "False" when "DomainName" does not match' { @@ -217,7 +217,7 @@ try $result = Test-TargetResource @testDefaultParams -DomainName $incorrectDomainName - $result | Should Be $false + $result | Should -Be $false } It 'Returns "True" when "DomainNetBIOSName" matches' { @@ -225,7 +225,7 @@ try $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName -DomainNetBIOSName $correctDomainNetBIOSName - $result | Should Be $true + $result | Should -Be $true } It 'Returns "False" when "DomainNetBIOSName" does not match' { @@ -233,7 +233,7 @@ try $result = Test-TargetResource @testDefaultParams -DomainName $correctDomainName -DomainNetBIOSName 'INCORRECT' - $result | Should Be $false + $result | Should -Be $false } It 'Returns "True" when "ParentDomainName" matches' { @@ -241,7 +241,7 @@ try $result = Test-TargetResource @testDefaultParams -DomainName $correctChildDomainName -ParentDomainName $parentDomainName - $result | Should Be $true + $result | Should -Be $true } It 'Returns "False" when "ParentDomainName" does not match' { @@ -249,7 +249,7 @@ try $result = Test-TargetResource @testDefaultParams -DomainName $correctChildDomainName -ParentDomainName 'incorrect.com' - $result | Should Be $false + $result | Should -Be $false } } diff --git a/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 b/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 index b55ace962..e81d31ffc 100644 --- a/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 +++ b/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 @@ -76,7 +76,7 @@ try $result = Get-TargetResource @testDefaultParams - $result -is [System.Collections.Hashtable] | Should Be $true + $result -is [System.Collections.Hashtable] | Should -Be $true } It 'Calls "Get-ADDefaultDomainPasswordPolicy" without credentials by default' { @@ -141,7 +141,7 @@ try $result = Test-TargetResource @testDefaultParams - $result -is [System.Boolean] | Should Be $true + $result -is [System.Boolean] | Should -Be $true } It 'Calls "Get-TargetResource" with "Credential" parameter when specified' { @@ -169,7 +169,7 @@ try $result = Test-TargetResource @propertyDefaultParams - $result | Should Be $true + $result | Should -Be $true } It "Fails when '$propertyName' parameter does not match resource property value" { @@ -191,7 +191,7 @@ try $result = Test-TargetResource @propertyDefaultParams - $result | Should Be $false + $result | Should -Be $false } } #end foreach property diff --git a/Tests/Unit/MSFT_xADGroup.Tests.ps1 b/Tests/Unit/MSFT_xADGroup.Tests.ps1 index 64322d7b3..4abb71a3d 100644 --- a/Tests/Unit/MSFT_xADGroup.Tests.ps1 +++ b/Tests/Unit/MSFT_xADGroup.Tests.ps1 @@ -113,13 +113,13 @@ try Mock -CommandName Get-ADGroup { return $fakeADGroup; } Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } - (Get-TargetResource @testPresentParams).Ensure | Should Be 'Present' + (Get-TargetResource @testPresentParams).Ensure | Should -Be 'Present' } It "Returns 'Ensure' is 'Absent' when group does not exist" { Mock -CommandName Get-ADGroup { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } - (Get-TargetResource @testPresentParams).Ensure | Should Be 'Absent' + (Get-TargetResource @testPresentParams).Ensure | Should -Be 'Absent' } @@ -174,7 +174,7 @@ try $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser1.$attribute, $fakeADUser2.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $true + $targetResource | Should -Be $true } It "Fails when group membership counts do not match using '$attribute'" { @@ -183,7 +183,7 @@ try $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser2.$attribute, $fakeADUser3.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $false + $targetResource | Should -Be $false } It "Fails when group 'Members' do not match using '$attribute'" { @@ -192,7 +192,7 @@ try $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser2.$attribute, $fakeADUser3.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $false + $targetResource | Should -Be $false } It "Passes when specified 'MembersToInclude' match using '$attribute'" { @@ -201,7 +201,7 @@ try $targetResource = Test-TargetResource @testPresentParams -MembersToInclude $fakeADUser2.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $true + $targetResource | Should -Be $true } It "Fails when specified 'MembersToInclude' are missing using '$attribute'" { @@ -210,7 +210,7 @@ try $targetResource = Test-TargetResource @testPresentParams -MembersToInclude $fakeADUser3.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $false + $targetResource | Should -Be $false } It "Passes when specified 'MembersToExclude' are missing using '$attribute'" { @@ -219,7 +219,7 @@ try $targetResource = Test-TargetResource @testPresentParams -MembersToExclude $fakeADUser3.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $true + $targetResource | Should -Be $true } It "Fails when when specified 'MembersToExclude' match using '$attribute'" { @@ -228,7 +228,7 @@ try $targetResource = Test-TargetResource @testPresentParams -MembersToExclude $fakeADUser2.$attribute -MembershipAttribute $attribute - $targetResource | Should Be $false + $targetResource | Should -Be $false } } #end foreach attribute @@ -236,7 +236,7 @@ try It "Fails when group does not exist and 'Ensure' is 'Present'" { Mock -CommandName Get-TargetResource -MockWith { return $testAbsentParams } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Scope' is wrong" { @@ -246,7 +246,7 @@ try return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Category' is wrong" { @@ -256,7 +256,7 @@ try return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Path' is wrong" { @@ -266,7 +266,7 @@ try return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Description' is wrong" { @@ -276,7 +276,7 @@ try return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'DisplayName' is wrong" { @@ -286,7 +286,7 @@ try return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'ManagedBy' is wrong" { @@ -296,7 +296,7 @@ try return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when group exists, 'Ensure' is 'Present' but 'Notes' is wrong" { @@ -306,25 +306,25 @@ try return $duffADGroup } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when group exists and 'Ensure' is 'Absent'" { Mock -CommandName Get-TargetResource -MockWith { return $testPresentParams } - Test-TargetResource @testAbsentParams | Should Be $false + Test-TargetResource @testAbsentParams | Should -Be $false } It "Passes when group exists, target matches and 'Ensure' is 'Present'" { Mock -CommandName Get-TargetResource -MockWith { return $testPresentParams } - Test-TargetResource @testPresentParams | Should Be $true + Test-TargetResource @testPresentParams | Should -Be $true } It "Passes when group does not exist and 'Ensure' is 'Absent'" { Mock -CommandName Get-TargetResource -MockWith { return $testAbsentParams } - Test-TargetResource @testAbsentParams | Should Be $true + Test-TargetResource @testAbsentParams | Should -Be $true } } @@ -629,7 +629,7 @@ try Mock -CommandName Add-ADCommonGroupMember $universalGroupInCompliance = Test-TargetResource -GroupName $testUniversalPresentParams.GroupName -DisplayName $testUniversalPresentParams.DisplayName - $universalGroupInCompliance | Should Be $true + $universalGroupInCompliance | Should -Be $true } # tests for issue 183 @@ -644,7 +644,7 @@ try Mock -CommandName Add-ADCommonGroupMember $universalGroupInCompliance = Test-TargetResource -GroupName $testUniversalPresentParams.GroupName -DisplayName $testUniversalPresentParams.DisplayName - $universalGroupInCompliance | Should Be $true + $universalGroupInCompliance | Should -Be $true } It "Calls Restore-AdCommonObject when RestoreFromRecycleBin is used" { diff --git a/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 b/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 index 16edf0c86..aa48aa8ab 100644 --- a/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 +++ b/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 @@ -404,7 +404,7 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParametersFuture - $getTargetResourceResult.Ensure | Should Be 'Absent' + $getTargetResourceResult.Ensure | Should -Be 'Absent' Assert-MockCalled -CommandName Assert-HasDomainAdminRights -Scope It -Exactly -Times 1 Assert-MockCalled -CommandName Get-KdsRootKey -Scope It -Exactly -Times 1 @@ -422,7 +422,7 @@ try } $getTargetResourceResult = Get-TargetResource @getTargetResourceParametersFuture - $getTargetResourceResult.Ensure | Should Be 'Absent' + $getTargetResourceResult.Ensure | Should -Be 'Absent' Assert-MockCalled -CommandName Assert-HasDomainAdminRights -Scope It -Exactly -Times 1 Assert-MockCalled -CommandName Get-KdsRootKey -Scope It -Exactly -Times 1 @@ -606,7 +606,7 @@ try } $testTargetResourceParametersFuture[$Parameter] = $value - Test-TargetResource @testTargetResourceParametersFuture | Should Be $false + Test-TargetResource @testTargetResourceParametersFuture | Should -Be $false Assert-MockCalled -CommandName Compare-TargetResourceState -ParameterFilter { $mockKDSRootKeyFuture.EffectiveTime -eq $EffectiveTime diff --git a/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 b/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 index ffe98a7f2..ed31b6b1e 100644 --- a/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 +++ b/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 @@ -442,7 +442,7 @@ try $getTargetResourceResult = Get-TargetResource @testResourceParametersSingle It "Should return 'Ensure' is 'Absent'" { - $getTargetResourceResult.Ensure | Should Be 'Absent' + $getTargetResourceResult.Ensure | Should -Be 'Absent' } It "Should return 'ServiceAccountName' when 'Absent'" { @@ -886,7 +886,7 @@ try DisplayName = '' } - Test-TargetResource @testResourceParametersGroup | Should Be $true + Test-TargetResource @testResourceParametersGroup | Should -Be $true } } @@ -960,7 +960,7 @@ try } $testResourceParametersSingle[$Parameter] = $value - Test-TargetResource @testResourceParametersSingle | Should Be $false + Test-TargetResource @testResourceParametersSingle | Should -Be $false } } @@ -1014,7 +1014,7 @@ try } $testResourceParametersGroup[$Parameter] = $value - Test-TargetResource @testResourceParametersGroup | Should Be $false + Test-TargetResource @testResourceParametersGroup | Should -Be $false } } } diff --git a/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 b/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 index 63b313065..7c1cad7c2 100644 --- a/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 +++ b/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 @@ -110,7 +110,7 @@ try $targetResource = Get-TargetResource @testDefaultParameters -Verbose # Assert - $targetResource | Should BeOfType [System.Collections.Hashtable] + $targetResource | Should -BeOfType [System.Collections.Hashtable] } It 'Should return a valid result if the ace is present' { @@ -118,14 +118,14 @@ try $targetResource = Get-TargetResource @testDefaultParameters -Verbose # Assert - $targetResource.Ensure | Should Be 'Present' - $targetResource.Path | Should Be $testDefaultParameters.Path - $targetResource.IdentityReference | Should Be $testDefaultParameters.IdentityReference - $targetResource.ActiveDirectoryRights | Should Be 'GenericAll' - $targetResource.AccessControlType | Should Be $testDefaultParameters.AccessControlType - $targetResource.ObjectType | Should Be $testDefaultParameters.ObjectType - $targetResource.ActiveDirectorySecurityInheritance | Should Be $testDefaultParameters.ActiveDirectorySecurityInheritance - $targetResource.InheritedObjectType | Should Be $testDefaultParameters.InheritedObjectType + $targetResource.Ensure | Should -Be 'Present' + $targetResource.Path | Should -Be $testDefaultParameters.Path + $targetResource.IdentityReference | Should -Be $testDefaultParameters.IdentityReference + $targetResource.ActiveDirectoryRights | Should -Be 'GenericAll' + $targetResource.AccessControlType | Should -Be $testDefaultParameters.AccessControlType + $targetResource.ObjectType | Should -Be $testDefaultParameters.ObjectType + $targetResource.ActiveDirectorySecurityInheritance | Should -Be $testDefaultParameters.ActiveDirectorySecurityInheritance + $targetResource.InheritedObjectType | Should -Be $testDefaultParameters.InheritedObjectType } } @@ -143,14 +143,14 @@ try $targetResource = Get-TargetResource @testDefaultParameters -Verbose # Assert - $targetResource.Ensure | Should Be 'Absent' - $targetResource.Path | Should Be $testDefaultParameters.Path - $targetResource.IdentityReference | Should Be $testDefaultParameters.IdentityReference - $targetResource.ActiveDirectoryRights | Should Be '' - $targetResource.AccessControlType | Should Be $testDefaultParameters.AccessControlType - $targetResource.ObjectType | Should Be $testDefaultParameters.ObjectType - $targetResource.ActiveDirectorySecurityInheritance | Should Be $testDefaultParameters.ActiveDirectorySecurityInheritance - $targetResource.InheritedObjectType | Should Be $testDefaultParameters.InheritedObjectType + $targetResource.Ensure | Should -Be 'Absent' + $targetResource.Path | Should -Be $testDefaultParameters.Path + $targetResource.IdentityReference | Should -Be $testDefaultParameters.IdentityReference + $targetResource.ActiveDirectoryRights | Should -Be '' + $targetResource.AccessControlType | Should -Be $testDefaultParameters.AccessControlType + $targetResource.ObjectType | Should -Be $testDefaultParameters.ObjectType + $targetResource.ActiveDirectorySecurityInheritance | Should -Be $testDefaultParameters.ActiveDirectorySecurityInheritance + $targetResource.InheritedObjectType | Should -Be $testDefaultParameters.InheritedObjectType } } } @@ -169,7 +169,7 @@ try $targetResource = Test-TargetResource @testDefaultParameters @testPresentParameters # Assert - $targetResource | Should BeOfType [System.Boolean] + $targetResource | Should -BeOfType [System.Boolean] } It 'Should return $true if the ace desired state is present' { @@ -177,7 +177,7 @@ try $targetResource = Test-TargetResource @testDefaultParameters @testPresentParameters -Verbose # Assert - $targetResource | Should Be $true + $targetResource | Should -Be $true } It 'Should return $false if the ace desired state is absent' { @@ -185,7 +185,7 @@ try $targetResource = Test-TargetResource @testDefaultParameters @testAbsentParameters # Assert - $targetResource | Should Be $false + $targetResource | Should -Be $false } } @@ -198,7 +198,7 @@ try $targetResource = Test-TargetResource @testDefaultParameters @testPresentParameters # Assert - $targetResource | Should Be $false + $targetResource | Should -Be $false } It 'Should return $true if the ace desired state is absent' { @@ -206,7 +206,7 @@ try $targetResource = Test-TargetResource @testDefaultParameters @testAbsentParameters # Assert - $targetResource | Should Be $true + $targetResource | Should -Be $true } } } diff --git a/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 b/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 index 0e97af33f..34f78237b 100644 --- a/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 +++ b/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 @@ -69,7 +69,7 @@ try Mock -CommandName Get-ADOrganizationalUnit -MockWith { return [PSCustomObject] $protectedFakeAdOu } $targetResource = Get-TargetResource -Name $testPresentParams.Name -Path $testPresentParams.Path - $targetResource -is [System.Collections.Hashtable] | Should Be $true + $targetResource -is [System.Collections.Hashtable] | Should -Be $true } It 'Returns "Ensure" = "Present" when OU exists' { @@ -77,7 +77,7 @@ try Mock -CommandName Get-ADOrganizationalUnit -MockWith { return [PSCustomObject] $protectedFakeAdOu } $targetResource = Get-TargetResource -Name $testPresentParams.Name -Path $testPresentParams.Path - $targetResource.Ensure | Should Be 'Present' + $targetResource.Ensure | Should -Be 'Present' } It 'Returns "Ensure" = "Absent" when OU does not exist' { @@ -85,7 +85,7 @@ try Mock -CommandName Get-ADOrganizationalUnit $targetResource = Get-TargetResource -Name $testPresentParams.Name -Path $testPresentParams.Path - $targetResource.Ensure | Should Be 'Absent' + $targetResource.Ensure | Should -Be 'Absent' } It 'Returns "ProtectedFromAccidentalDeletion" = "$true" when OU is protected' { @@ -93,7 +93,7 @@ try Mock -CommandName Get-ADOrganizationalUnit -MockWith { return [PSCustomObject] $protectedFakeAdOu } $targetResource = Get-TargetResource -Name $testPresentParams.Name -Path $testPresentParams.Path - $targetResource.ProtectedFromAccidentalDeletion | Should Be $true + $targetResource.ProtectedFromAccidentalDeletion | Should -Be $true } It 'Returns "ProtectedFromAccidentalDeletion" = "$false" when OU is not protected' { @@ -105,7 +105,7 @@ try } $targetResource = Get-TargetResource -Name $testPresentParams.Name -Path $testPresentParams.Path - $targetResource.ProtectedFromAccidentalDeletion | Should Be $false + $targetResource.ProtectedFromAccidentalDeletion | Should -Be $false } It 'Returns an empty description' { @@ -118,7 +118,7 @@ try $targetResource = Get-TargetResource -Name $testPresentParams.Name -Path $testPresentParams.Path - $targetResource.Description | Should BeNullOrEmpty + $targetResource.Description | Should -BeNullOrEmpty } } @@ -131,21 +131,21 @@ try Mock -CommandName Get-ADOrganizationalUnit -MockWith { return [PSCustomObject] $protectedFakeAdOu } $targetResource = Test-TargetResource @testPresentParams - $targetResource -is [System.Boolean] | Should Be $true + $targetResource -is [System.Boolean] | Should -Be $true } It 'Fails when OU does not exist and "Ensure" = "Present"' { Mock -CommandName Assert-Module Mock -CommandName Get-ADOrganizationalUnit - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It 'Fails when OU does exist and "Ensure" = "Absent"' { Mock -CommandName Assert-Module Mock -CommandName Get-ADOrganizationalUnit -MockWith { return [PSCustomObject] $protectedFakeAdOu } - Test-TargetResource @testAbsentParams | Should Be $false + Test-TargetResource @testAbsentParams | Should -Be $false } It 'Fails when OU does exist but "Description" is incorrect' { @@ -154,7 +154,7 @@ try $testDescriptionParams = $testPresentParams.Clone() $testDescriptionParams['Description'] = 'Wrong description' - Test-TargetResource @testDescriptionParams | Should Be $false + Test-TargetResource @testDescriptionParams | Should -Be $false } It 'Fails when OU does exist but "ProtectedFromAccidentalDeletion" is incorrect' { @@ -163,21 +163,21 @@ try $testProtectedFromAccidentalDeletionParams = $testPresentParams.Clone() $testProtectedFromAccidentalDeletionParams['ProtectedFromAccidentalDeletion'] = $false - Test-TargetResource @testProtectedFromAccidentalDeletionParams | Should Be $false + Test-TargetResource @testProtectedFromAccidentalDeletionParams | Should -Be $false } It 'Passes when OU does exist, "Ensure" = "Present" and all properties are correct' { Mock -CommandName Assert-Module Mock -CommandName Get-ADOrganizationalUnit -MockWith { return [PSCustomObject] $protectedFakeAdOu } - Test-TargetResource @testPresentParams | Should Be $true + Test-TargetResource @testPresentParams | Should -Be $true } It 'Passes when OU does not exist and "Ensure" = "Absent"' { Mock -CommandName Assert-Module Mock -CommandName Get-ADOrganizationalUnit - Test-TargetResource @testAbsentParams | Should Be $true + Test-TargetResource @testAbsentParams | Should -Be $true } It 'Passes when no OU description is specified with existing OU description' { @@ -186,7 +186,7 @@ try $testEmptyDescriptionParams = $testPresentParams.Clone() $testEmptyDescriptionParams['Description'] = '' - Test-TargetResource @testEmptyDescriptionParams | Should Be $true + Test-TargetResource @testEmptyDescriptionParams | Should -Be $true } } diff --git a/Tests/Unit/MSFT_xADReplicationSite.Tests.ps1 b/Tests/Unit/MSFT_xADReplicationSite.Tests.ps1 index 48a85b2bc..367a8120c 100644 --- a/Tests/Unit/MSFT_xADReplicationSite.Tests.ps1 +++ b/Tests/Unit/MSFT_xADReplicationSite.Tests.ps1 @@ -86,7 +86,7 @@ try $targetResource = Get-TargetResource -Name $presentSiteName # Assert - $targetResource -is [System.Collections.Hashtable] | Should Be $true + $targetResource -is [System.Collections.Hashtable] | Should -Be $true } It 'Should return present if the site exists' { @@ -98,8 +98,8 @@ try $targetResource = Get-TargetResource -Name $presentSiteName # Assert - $targetResource.Ensure | Should Be 'Present' - $targetResource.Name | Should Be $presentSiteName + $targetResource.Ensure | Should -Be 'Present' + $targetResource.Name | Should -Be $presentSiteName } It 'Should return absent if the site does not exist' { @@ -111,8 +111,8 @@ try $targetResource = Get-TargetResource -Name $absentSiteName # Assert - $targetResource.Ensure | Should Be 'Absent' - $targetResource.Name | Should Be $absentSiteName + $targetResource.Ensure | Should -Be 'Absent' + $targetResource.Name | Should -Be $absentSiteName } } #endregion @@ -128,7 +128,7 @@ try $targetResourceState = Test-TargetResource @presentSiteTestPresent # Assert - $targetResourceState -is [System.Boolean] | Should Be $true + $targetResourceState -is [System.Boolean] | Should -Be $true } It 'Should return true if the site should exists and does exists' { @@ -140,7 +140,7 @@ try $targetResourceState = Test-TargetResource @presentSiteTestPresent # Assert - $targetResourceState | Should Be $true + $targetResourceState | Should -Be $true } It 'Should return false if the site should exists but does not exists' { @@ -152,7 +152,7 @@ try $targetResourceState = Test-TargetResource @absentSiteTestPresent # Assert - $targetResourceState | Should Be $false + $targetResourceState | Should -Be $false } It 'Should return false if the site should not exists but does exists' { @@ -164,7 +164,7 @@ try $targetResourceState = Test-TargetResource @presentSiteTestAbsent # Assert - $targetResourceState | Should Be $false + $targetResourceState | Should -Be $false } It 'Should return true if the site should not exists and does not exists' { @@ -176,7 +176,7 @@ try $targetResourceState = Test-TargetResource @absentSiteTestAbsent # Assert - $targetResourceState | Should Be $true + $targetResourceState | Should -Be $true } } diff --git a/Tests/Unit/MSFT_xADReplicationSubnet.Tests.ps1 b/Tests/Unit/MSFT_xADReplicationSubnet.Tests.ps1 index cdb10f1b3..b6632900a 100644 --- a/Tests/Unit/MSFT_xADReplicationSubnet.Tests.ps1 +++ b/Tests/Unit/MSFT_xADReplicationSubnet.Tests.ps1 @@ -51,10 +51,10 @@ try $result = Get-TargetResource @testDefaultParameters - $result.Ensure | Should Be 'Absent' - $result.Name | Should Be $testDefaultParameters.Name - $result.Site | Should Be '' - $result.Location | Should Be '' + $result.Ensure | Should -Be 'Absent' + $result.Name | Should -Be $testDefaultParameters.Name + $result.Site | Should -Be '' + $result.Location | Should -Be '' } } @@ -76,10 +76,10 @@ try $result = Get-TargetResource @testDefaultParameters - $result.Ensure | Should Be 'Present' - $result.Name | Should Be $testDefaultParameters.Name - $result.Site | Should Be 'Default-First-Site-Name' - $result.Location | Should Be 'Seattle' + $result.Ensure | Should -Be 'Present' + $result.Name | Should -Be $testDefaultParameters.Name + $result.Site | Should -Be 'Default-First-Site-Name' + $result.Location | Should -Be 'Seattle' } } @@ -98,10 +98,10 @@ try $result = Get-TargetResource @testDefaultParameters - $result.Ensure | Should Be 'Present' - $result.Name | Should Be $testDefaultParameters.Name - $result.Site | Should Be '' - $result.Location | Should Be 'Seattle' + $result.Ensure | Should -Be 'Present' + $result.Name | Should -Be $testDefaultParameters.Name + $result.Site | Should -Be '' + $result.Location | Should -Be 'Seattle' } } } @@ -123,13 +123,13 @@ try It 'Should return false for present' { $result = Test-TargetResource -Ensure 'Present' @testDefaultParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should return true for absent' { $result = Test-TargetResource -Ensure 'Absent' @testDefaultParameters - $result | Should Be $true + $result | Should -Be $true } } @@ -150,25 +150,25 @@ try It 'Should return true for present' { $result = Test-TargetResource -Ensure 'Present' @testDefaultParameters - $result | Should Be $true + $result | Should -Be $true } It 'Should return false for absent' { $result = Test-TargetResource -Ensure 'Absent' @testDefaultParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should return false for wrong site' { $result = Test-TargetResource -Ensure 'Present' -Name $testDefaultParameters.Name -Site 'WrongSite' -Location $testDefaultParameters.Location - $result | Should Be $false + $result | Should -Be $false } It 'Should return false for wrong location' { $result = Test-TargetResource -Ensure 'Present' -Name $testDefaultParameters.Name -Site $testDefaultParameters.Site -Location 'WringLocation' - $result | Should Be $false + $result | Should -Be $false } } } diff --git a/Tests/Unit/MSFT_xADServicePrincipalName.Tests.ps1 b/Tests/Unit/MSFT_xADServicePrincipalName.Tests.ps1 index b0f81ea45..e280794c1 100644 --- a/Tests/Unit/MSFT_xADServicePrincipalName.Tests.ps1 +++ b/Tests/Unit/MSFT_xADServicePrincipalName.Tests.ps1 @@ -50,9 +50,9 @@ try $result = Get-TargetResource @testDefaultParameters - $result.Ensure | Should Be 'Absent' - $result.ServicePrincipalName | Should Be 'HOST/demo' - $result.Account | Should Be '' + $result.Ensure | Should -Be 'Absent' + $result.ServicePrincipalName | Should -Be 'HOST/demo' + $result.Account | Should -Be '' } } @@ -66,9 +66,9 @@ try $result = Get-TargetResource @testDefaultParameters - $result.Ensure | Should Be 'Present' - $result.ServicePrincipalName | Should Be 'HOST/demo' - $result.Account | Should Be 'User' + $result.Ensure | Should -Be 'Present' + $result.ServicePrincipalName | Should -Be 'HOST/demo' + $result.Account | Should -Be 'User' } } @@ -83,9 +83,9 @@ try $result = Get-TargetResource @testDefaultParameters - $result.Ensure | Should Be 'Present' - $result.ServicePrincipalName | Should Be 'HOST/demo' - $result.Account | Should Be 'User;Computer' + $result.Ensure | Should -Be 'Present' + $result.ServicePrincipalName | Should -Be 'HOST/demo' + $result.Account | Should -Be 'User;Computer' } } } @@ -105,13 +105,13 @@ try It 'Should return false for present' { $result = Test-TargetResource -Ensure 'Present' @testDefaultParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should return true for absent' { $result = Test-TargetResource -Ensure 'Absent' @testDefaultParameters - $result | Should Be $true + $result | Should -Be $true } } @@ -124,13 +124,13 @@ try It 'Should return true for present' { $result = Test-TargetResource -Ensure 'Present' @testDefaultParameters - $result | Should Be $true + $result | Should -Be $true } It 'Should return false for absent' { $result = Test-TargetResource -Ensure 'Absent' @testDefaultParameters - $result | Should Be $false + $result | Should -Be $false } } @@ -143,13 +143,13 @@ try It 'Should return false for present' { $result = Test-TargetResource -Ensure 'Present' @testDefaultParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should return false for absent' { $result = Test-TargetResource -Ensure 'Absent' @testDefaultParameters - $result | Should Be $false + $result | Should -Be $false } } @@ -163,13 +163,13 @@ try It 'Should return false for present' { $result = Test-TargetResource -Ensure 'Present' @testDefaultParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should return false for absent' { $result = Test-TargetResource -Ensure 'Absent' @testDefaultParameters - $result | Should Be $false + $result | Should -Be $false } } @@ -195,7 +195,7 @@ try It 'Should throw the correct exception' { - { Set-TargetResource @testPresentParams } | Should Throw "AD object with SamAccountName 'User' not found!" + { Set-TargetResource @testPresentParams } | Should -Throw "AD object with SamAccountName 'User' not found!" } } diff --git a/Tests/Unit/MSFT_xADUser.Tests.ps1 b/Tests/Unit/MSFT_xADUser.Tests.ps1 index 16ed801a4..5cf8587bc 100644 --- a/Tests/Unit/MSFT_xADUser.Tests.ps1 +++ b/Tests/Unit/MSFT_xADUser.Tests.ps1 @@ -75,7 +75,7 @@ try $adUser = Get-TargetResource @testPresentParams - $adUser -is [System.Collections.Hashtable] | Should Be $true + $adUser -is [System.Collections.Hashtable] | Should -Be $true } It "Returns 'Ensure' is 'Present' when user account exists" { @@ -83,7 +83,7 @@ try $adUser = Get-TargetResource @testPresentParams - $adUser.Ensure | Should Be 'Present' + $adUser.Ensure | Should -Be 'Present' } It "Returns 'Ensure' is 'Absent' when user account does not exist" { @@ -91,7 +91,7 @@ try $adUser = Get-TargetResource @testPresentParams - $adUser.Ensure | Should Be 'Absent' + $adUser.Ensure | Should -Be 'Absent' } It "Calls 'Get-ADUser' with 'Server' parameter when 'DomainController' specified" { @@ -123,46 +123,46 @@ try It "Passes when user account does not exist and 'Ensure' is 'Absent'" { Mock -CommandName Get-TargetResource -MockWith { return $testAbsentParams } - Test-TargetResource @testAbsentParams | Should Be $true + Test-TargetResource @testAbsentParams | Should -Be $true } It "Passes when user account exists and 'Ensure' is 'Present'" { Mock -CommandName Get-TargetResource -MockWith { return $testPresentParams } - Test-TargetResource @testPresentParams | Should Be $true + Test-TargetResource @testPresentParams | Should -Be $true } It "Passes when user account password matches, 'Password' is specified and 'PasswordNeverResets' is False" { Mock -CommandName Get-TargetResource -MockWith { return $testPresentParams } Mock -CommandName Test-Password { return $true } - Test-TargetResource @testPresentParams -Password $testCredential | Should Be $true + Test-TargetResource @testPresentParams -Password $testCredential | Should -Be $true } It "Passes when user account password does not match, 'Password' is specified and 'PasswordNeverResets' is True" { Mock -CommandName Get-TargetResource -MockWith { return $testPresentParams } Mock -CommandName Test-Password { return $false } - Test-TargetResource @testPresentParams -Password $testCredential -PasswordNeverResets $true | Should Be $true + Test-TargetResource @testPresentParams -Password $testCredential -PasswordNeverResets $true | Should -Be $true } It "Fails when user account does not exist and 'Ensure' is 'Present'" { Mock -CommandName Get-TargetResource -MockWith { return $testAbsentParams } - Test-TargetResource @testPresentParams | Should Be $false + Test-TargetResource @testPresentParams | Should -Be $false } It "Fails when user account exists, and 'Ensure' is 'Absent'" { Mock -CommandName Get-TargetResource -MockWith { return $testPresentParams } - Test-TargetResource @testAbsentParams | Should Be $false + Test-TargetResource @testAbsentParams | Should -Be $false } It "Fails when user account password is incorrect, 'Password' is specified and 'PasswordNeverResets' is False" { Mock -CommandName Get-TargetResource -MockWith { return $testPresentParams } Mock -CommandName Test-Password { return $false } - Test-TargetResource @testPresentParams -Password $testCredential | Should Be $false + Test-TargetResource @testPresentParams -Password $testCredential | Should -Be $false } It "Calls 'Test-Password' with 'Default' PasswordAuthentication by default" { @@ -196,7 +196,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $true + Test-TargetResource @testValidPresentParams | Should -Be $true } It "Fails when user account '$testParameter' does not match incorrect AD account property value" { @@ -210,7 +210,7 @@ try return $invalidADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } It "Fails when user account '$testParameter' does not match empty AD account property value" { @@ -224,7 +224,7 @@ try return $invalidADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } It "Fails when user account '$testParameter' does not match null AD account property value" { @@ -238,7 +238,7 @@ try return $invalidADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } It "Passes when empty user account '$testParameter' matches empty AD account property" { @@ -250,7 +250,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $true + Test-TargetResource @testValidPresentParams | Should -Be $true } It "Passes when empty user account '$testParameter' matches null AD account property" { @@ -262,7 +262,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $true + Test-TargetResource @testValidPresentParams | Should -Be $true } } #end foreach test string property @@ -279,7 +279,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $true + Test-TargetResource @testValidPresentParams | Should -Be $true } It "Should fail when user account '$testParameter' is true and does not match AD account property value" { @@ -318,7 +318,7 @@ try return $invalidADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } } #end foreach test boolean property @@ -334,7 +334,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $true + Test-TargetResource @testValidPresentParams | Should -Be $true } It "Passes when user account '$testParameter' matches single AD account property" { @@ -347,7 +347,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $true + Test-TargetResource @testValidPresentParams | Should -Be $true } It "Passes when user account '$testParameter' matches multiple AD account property" { $testParameterValue = @('Entry1', 'Entry2') @@ -359,7 +359,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $true + Test-TargetResource @testValidPresentParams | Should -Be $true } It "Fails when user account '$testParameter' does not match AD account property count" { $testParameterValue = @('Entry1', 'Entry2') @@ -371,7 +371,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } It "Fails when user account '$testParameter' does not match AD account property name" { @@ -384,7 +384,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } It "Fails when user account '$testParameter' does not match empty AD account property" { @@ -397,7 +397,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } It "Fails when empty user account '$testParameter' does not match AD account property" { @@ -410,7 +410,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } }#end foreach test array property @@ -658,15 +658,15 @@ try #region Function Assert-TargetResource Describe 'xADUser\Assert-Parameters' { It "Does not throw when 'PasswordNeverExpires' and 'CannotChangePassword' are specified" { - { Assert-Parameters -PasswordNeverExpires $true -CannotChangePassword $true } | Should Not Throw + { Assert-Parameters -PasswordNeverExpires $true -CannotChangePassword $true } | Should -Not -Throw } It "Throws when account is disabled and 'Password' is specified" { - { Assert-Parameters -Password $testCredential -Enabled $false } | Should Throw + { Assert-Parameters -Password $testCredential -Enabled $false } | Should -Throw } It "Does not throw when 'TrustedForDelegation' is specified" { - { Assert-Parameters -TrustedForDelegation $true } | Should Not Throw + { Assert-Parameters -TrustedForDelegation $true } | Should -Not -Throw } It "Should throw the correct error when 'PasswordNeverExpires' and 'ChangePasswordAtLogon' are specified" { diff --git a/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 b/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 index df501463e..1a833c8cf 100644 --- a/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 +++ b/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 @@ -64,19 +64,19 @@ try It 'Returns a "System.Collections.Hashtable" object type' { Mock -CommandName Get-Domain -MockWith {return $fakeDomainObject} $targetResource = Get-TargetResource @testParams - $targetResource -is [System.Collections.Hashtable] | Should Be $true + $targetResource -is [System.Collections.Hashtable] | Should -Be $true } It "Returns DomainName = $($testParams.DomainName) when domain is found" { Mock -CommandName Get-Domain -MockWith {return $fakeDomainObject} $targetResource = Get-TargetResource @testParams - $targetResource.DomainName | Should Be $testParams.DomainName + $targetResource.DomainName | Should -Be $testParams.DomainName } It "Returns an empty DomainName when domain is not found" { Mock -CommandName Get-Domain $targetResource = Get-TargetResource @testParams - $targetResource.DomainName | Should Be $null + $targetResource.DomainName | Should -Be $null } } #endregion @@ -87,17 +87,17 @@ try It 'Returns a "System.Boolean" object type' { Mock -CommandName Get-Domain -MockWith {return $fakeDomainObject} $targetResource = Test-TargetResource @testParams - $targetResource -is [System.Boolean] | Should Be $true + $targetResource -is [System.Boolean] | Should -Be $true } It 'Passes when domain found' { Mock -CommandName Get-Domain -MockWith {return $fakeDomainObject} - Test-TargetResource @testParams | Should Be $true + Test-TargetResource @testParams | Should -Be $true } It 'Fails when domain not found' { Mock -CommandName Get-Domain - Test-TargetResource @testParams | Should Be $false + Test-TargetResource @testParams | Should -Be $false } } #endregion @@ -113,44 +113,44 @@ try Mock -CommandName Get-Domain -MockWith {return $fakeDomainObject} Mock -CommandName Start-Sleep Mock -CommandName Clear-DnsClientCache - {Set-TargetResource @testParams} | Should Not Throw - $global:DSCMachineStatus | should not be 1 + {Set-TargetResource @testParams} | Should -Not -Throw + $global:DSCMachineStatus | should -not -be 1 Assert-MockCalled -CommandName Start-Sleep -Times 0 -Scope It Assert-MockCalled -CommandName Clear-DnsClientCache -Times 0 -Scope It } It "Throws exception and does not set `$global:DSCMachineStatus when domain not found after $($testParams.RetryCount) retries when RebootRetryCount is not set" { Mock -CommandName Get-Domain - {Set-TargetResource @testParams} | Should Throw - $global:DSCMachineStatus | should not be 1 + {Set-TargetResource @testParams} | Should -Throw + $global:DSCMachineStatus | should -not -be 1 } It "Throws exception when domain not found after $($rebootTestParams.RebootRetryCount) reboot retries when RebootRetryCount is exceeded" { Mock -CommandName Get-Domain Mock -CommandName Get-Content -MockWith {return $rebootTestParams.RebootRetryCount} - {Set-TargetResource @rebootTestParams} | Should Throw + {Set-TargetResource @rebootTestParams} | Should -Throw } It "Calls Set-Content if reboot count is less than RebootRetryCount when domain not found" { Mock -CommandName Get-Domain Mock -CommandName Get-Content -MockWith {return 0} Mock -CommandName Set-Content - {Set-TargetResource @rebootTestParams} | Should Not Throw + {Set-TargetResource @rebootTestParams} | Should -Not -Throw Assert-MockCalled -CommandName Set-Content -Times 1 -Exactly -Scope It } It "Sets `$global:DSCMachineStatus = 1 and does not throw an exception if the domain is not found and RebootRetryCount is not exceeded" { Mock -CommandName Get-Domain Mock -CommandName Get-Content -MockWith {return 0} - {Set-TargetResource @rebootTestParams} | Should Not Throw - $global:DSCMachineStatus | should be 1 + {Set-TargetResource @rebootTestParams} | Should -Not -Throw + $global:DSCMachineStatus | should -be 1 } It "Calls Get-Domain exactly $($testParams.RetryCount) times when domain not found" { Mock -CommandName Get-Domain Mock -CommandName Start-Sleep Mock -CommandName Clear-DnsClientCache - {Set-TargetResource @testParams} | Should Throw + {Set-TargetResource @testParams} | Should -Throw Assert-MockCalled -CommandName Get-Domain -Times $testParams.RetryCount -Exactly -Scope It } @@ -158,7 +158,7 @@ try Mock -CommandName Get-Domain Mock -CommandName Start-Sleep Mock -CommandName Clear-DnsClientCache - {Set-TargetResource @testParams} | Should Throw + {Set-TargetResource @testParams} | Should -Throw Assert-MockCalled -CommandName Start-Sleep -Times $testParams.RetryCount -Exactly -Scope It } @@ -166,7 +166,7 @@ try Mock -CommandName Get-Domain Mock -CommandName Start-Sleep Mock -CommandName Clear-DnsClientCache - {Set-TargetResource @testParams} | Should Throw + {Set-TargetResource @testParams} | Should -Throw Assert-MockCalled -CommandName Clear-DnsClientCache -Times $testParams.RetryCount -Exactly -Scope It } } diff --git a/Tests/Unit/xActiveDirectory.Common.Tests.ps1 b/Tests/Unit/xActiveDirectory.Common.Tests.ps1 index 376a85b74..cd49a2483 100644 --- a/Tests/Unit/xActiveDirectory.Common.Tests.ps1 +++ b/Tests/Unit/xActiveDirectory.Common.Tests.ps1 @@ -582,7 +582,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Resolve-DomainFQDN -DomainName $testDomainName -ParentDomainName $testParentDomainName - $result | Should Be $testDomainName + $result | Should -Be $testDomainName } It 'Returns compound "DomainName.ParentDomainName" when "ParentDomainName" supplied' { @@ -591,7 +591,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Resolve-DomainFQDN -DomainName $testDomainName -ParentDomainName $testParentDomainName - $result | Should Be ('{0}.{1}' -f $testDomainName, $testParentDomainName) + $result | Should -Be ('{0}.{1}' -f $testDomainName, $testParentDomainName) } } @@ -604,7 +604,7 @@ InModuleScope 'xActiveDirectory.Common' { } } - Test-DomainMember | Should Be $true + Test-DomainMember | Should -Be $true } It 'Returns "False" when workgroup member' { @@ -614,7 +614,7 @@ InModuleScope 'xActiveDirectory.Common' { } } - Test-DomainMember | Should Be $false + Test-DomainMember | Should -Be $false } } @@ -627,7 +627,7 @@ InModuleScope 'xActiveDirectory.Common' { } } - Get-DomainName | Should Be 'contoso.com' + Get-DomainName | Should -Be 'contoso.com' } } @@ -676,11 +676,11 @@ InModuleScope 'xActiveDirectory.Common' { Describe 'xActiveDirectory.Common\Get-ADObjectParentDN' { It 'Returns CN object parent path' { - Get-ADObjectParentDN -DN 'CN=Administrator,CN=Users,DC=contoso,DC=com' | Should Be 'CN=Users,DC=contoso,DC=com' + Get-ADObjectParentDN -DN 'CN=Administrator,CN=Users,DC=contoso,DC=com' | Should -Be 'CN=Users,DC=contoso,DC=com' } It 'Returns OU object parent path' { - Get-ADObjectParentDN -DN 'CN=Administrator,OU=Custom Organizational Unit,DC=contoso,DC=com' | Should Be 'OU=Custom Organizational Unit,DC=contoso,DC=com' + Get-ADObjectParentDN -DN 'CN=Administrator,OU=Custom Organizational Unit,DC=contoso,DC=com' | Should -Be 'OU=Custom Organizational Unit,DC=contoso,DC=com' } } @@ -688,65 +688,65 @@ InModuleScope 'xActiveDirectory.Common' { It 'Removes one duplicate' { $members = Remove-DuplicateMembers -Members 'User1','User2','USER1' - $members.Count | Should Be 2 - $members -contains 'User1' | Should Be $true - $members -contains 'User2' | Should Be $true + $members.Count | Should -Be 2 + $members -contains 'User1' | Should -Be $true + $members -contains 'User2' | Should -Be $true } It 'Removes two duplicates' { $members = Remove-DuplicateMembers -Members 'User1','User2','USER1','USER2' - $members.Count | Should Be 2 - $members -contains 'User1' | Should Be $true - $members -contains 'User2' | Should Be $true + $members.Count | Should -Be 2 + $members -contains 'User1' | Should -Be $true + $members -contains 'User2' | Should -Be $true } It 'Removes double duplicates' { $members = Remove-DuplicateMembers -Members 'User1','User2','USER1','user1' - $members.Count | Should Be 2 - $members -contains 'User1' | Should Be $true - $members -contains 'User2' | Should Be $true + $members.Count | Should -Be 2 + $members -contains 'User1' | Should -Be $true + $members -contains 'User2' | Should -Be $true } } Describe 'xActiveDirectory.Common\Test-Members' { It 'Passes when nothing is passed' { - Test-Members -ExistingMembers $null | Should Be $true + Test-Members -ExistingMembers $null | Should -Be $true } It 'Passes when there are existing members but members are required' { $testExistingMembers = @('USER1', 'USER2') - Test-Members -ExistingMembers $testExistingMembers | Should Be $true + Test-Members -ExistingMembers $testExistingMembers | Should -Be $true } It 'Passes when existing members match required members' { $testExistingMembers = @('USER1', 'USER2') $testMembers = @('USER2', 'USER1') - Test-Members -ExistingMembers $testExistingMembers -Members $testMembers | Should Be $true + Test-Members -ExistingMembers $testExistingMembers -Members $testMembers | Should -Be $true } It 'Fails when there are no existing members and members are required' { $testExistingMembers = @('USER1', 'USER2') $testMembers = @('USER1', 'USER3') - Test-Members -ExistingMembers $null -Members $testMembers | Should Be $false + Test-Members -ExistingMembers $null -Members $testMembers | Should -Be $false } It 'Fails when there are more existing members than the members required' { $testExistingMembers = @('USER1', 'USER2', 'USER3') $testMembers = @('USER1', 'USER3') - Test-Members -ExistingMembers $null -Members $testMembers | Should Be $false + Test-Members -ExistingMembers $null -Members $testMembers | Should -Be $false } It 'Fails when there are more existing members than the members required' { $testExistingMembers = @('USER1', 'USER2') $testMembers = @('USER1', 'USER3', 'USER2') - Test-Members -ExistingMembers $null -Members $testMembers | Should Be $false + Test-Members -ExistingMembers $null -Members $testMembers | Should -Be $false } It 'Fails when existing members do not match required members' { @@ -868,19 +868,19 @@ InModuleScope 'xActiveDirectory.Common' { } It "Throws if 'Members' and 'MembersToInclude' are specified" { - { Assert-MemberParameters -Members @('User1') -MembersToInclude @('User1') } | Should Throw 'parameters conflict' + { Assert-MemberParameters -Members @('User1') -MembersToInclude @('User1') } | Should -Throw 'parameters conflict' } It "Throws if 'Members' and 'MembersToExclude' are specified" { - { Assert-MemberParameters -Members @('User1') -MembersToExclude @('User2') } | Should Throw 'parameters conflict' + { Assert-MemberParameters -Members @('User1') -MembersToExclude @('User2') } | Should -Throw 'parameters conflict' } It "Throws if 'MembersToInclude' and 'MembersToExclude' contain the same member" { - { Assert-MemberParameters -MembersToExclude @('user1') -MembersToInclude @('USER1') } | Should Throw 'member must not be included in both' + { Assert-MemberParameters -MembersToExclude @('user1') -MembersToInclude @('USER1') } | Should -Throw 'member must not be included in both' } It "Throws if 'MembersToInclude' and 'MembersToExclude' are empty" { - { Assert-MemberParameters -MembersToExclude @() -MembersToInclude @() } | Should Throw 'At least one member must be specified' + { Assert-MemberParameters -MembersToExclude @() -MembersToInclude @() } | Should -Throw 'At least one member must be specified' } } @@ -890,7 +890,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertTo-TimeSpan -TimeSpan $testIntTimeSpan -TimeSpanType Minutes - $result -is [System.TimeSpan] | Should Be $true + $result -is [System.TimeSpan] | Should -Be $true } It 'Creates TimeSpan from seconds' { @@ -898,7 +898,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertTo-TimeSpan -TimeSpan $testIntTimeSpan -TimeSpanType Seconds - $result.TotalSeconds | Should Be $testIntTimeSpan + $result.TotalSeconds | Should -Be $testIntTimeSpan } It 'Creates TimeSpan from minutes' { @@ -906,7 +906,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertTo-TimeSpan -TimeSpan $testIntTimeSpan -TimeSpanType Minutes - $result.TotalMinutes | Should Be $testIntTimeSpan + $result.TotalMinutes | Should -Be $testIntTimeSpan } It 'Creates TimeSpan from hours' { @@ -914,7 +914,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertTo-TimeSpan -TimeSpan $testIntTimeSpan -TimeSpanType Hours - $result.TotalHours | Should Be $testIntTimeSpan + $result.TotalHours | Should -Be $testIntTimeSpan } It 'Creates TimeSpan from days' { @@ -922,7 +922,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertTo-TimeSpan -TimeSpan $testIntTimeSpan -TimeSpanType Days - $result.TotalDays | Should Be $testIntTimeSpan + $result.TotalDays | Should -Be $testIntTimeSpan } } @@ -933,7 +933,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertFrom-TimeSpan -TimeSpan $testTimeSpan -TimeSpanType Seconds - $result -is [System.UInt32] | Should Be $true + $result -is [System.UInt32] | Should -Be $true } It 'Converts TimeSpan to total seconds' { @@ -942,7 +942,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertFrom-TimeSpan -TimeSpan $testTimeSpan -TimeSpanType Seconds - $result | Should Be $testTimeSpan.TotalSeconds + $result | Should -Be $testTimeSpan.TotalSeconds } It 'Converts TimeSpan to total minutes' { @@ -951,7 +951,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertFrom-TimeSpan -TimeSpan $testTimeSpan -TimeSpanType Minutes - $result | Should Be $testTimeSpan.TotalMinutes + $result | Should -Be $testTimeSpan.TotalMinutes } It 'Converts TimeSpan to total hours' { @@ -960,7 +960,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertFrom-TimeSpan -TimeSpan $testTimeSpan -TimeSpanType Hours - $result | Should Be $testTimeSpan.TotalHours + $result | Should -Be $testTimeSpan.TotalHours } It 'Converts TimeSpan to total days' { @@ -969,7 +969,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = ConvertFrom-TimeSpan -TimeSpan $testTimeSpan -TimeSpanType Days - $result | Should Be $testTimeSpan.TotalDays + $result | Should -Be $testTimeSpan.TotalDays } } @@ -979,7 +979,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity - $result -is [System.Collections.Hashtable] | Should Be $true + $result -is [System.Collections.Hashtable] | Should -Be $true } It "Returns 'Identity' key by default" { @@ -987,7 +987,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity - $result['Identity'] | Should Be $testIdentity + $result['Identity'] | Should -Be $testIdentity } It "Returns 'Name' key when 'UseNameParameter' is specified" { @@ -995,7 +995,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -UseNameParameter - $result['Name'] | Should Be $testIdentity + $result['Name'] | Should -Be $testIdentity } foreach ($identityParam in @('UserName','GroupName','ComputerName')) @@ -1008,7 +1008,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters @getADCommonParameters - $result['Identity'] | Should Be $testIdentity + $result['Identity'] | Should -Be $testIdentity } } @@ -1018,7 +1018,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -CommonName $testCommonName - $result['Identity'] | Should Be $testIdentity + $result['Identity'] | Should -Be $testIdentity } It "Returns 'Identity' key with 'CommonName' when 'Identity', 'CommonName' and 'PreferCommonName' are specified" { @@ -1027,7 +1027,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -CommonName $testCommonName -PreferCommonName - $result['Identity'] | Should Be $testCommonName + $result['Identity'] | Should -Be $testCommonName } It "Returns 'Identity' key with 'Identity' when 'Identity' and 'PreferCommonName' are specified" { @@ -1035,7 +1035,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -PreferCommonName - $result['Identity'] | Should Be $testIdentity + $result['Identity'] | Should -Be $testIdentity } it "Returns 'Name' key when 'UseNameParameter' and 'PreferCommonName' are supplied" { @@ -1044,7 +1044,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -UseNameParameter -CommonName $testCommonName -PreferCommonName - $result['Name'] | Should Be $testCommonName + $result['Name'] | Should -Be $testCommonName } It "Does not return 'Credential' key by default" { @@ -1052,7 +1052,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity - $result.ContainsKey('Credential') | Should Be $false + $result.ContainsKey('Credential') | Should -Be $false } It "Returns 'Credential' key when specified" { @@ -1061,7 +1061,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -Credential $testCredential - $result['Credential'] | Should Be $testCredential + $result['Credential'] | Should -Be $testCredential } It "Does not return 'Server' key by default" { @@ -1069,7 +1069,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity - $result.ContainsKey('Server') | Should Be $false + $result.ContainsKey('Server') | Should -Be $false } It "Returns 'Server' key when specified" { @@ -1078,7 +1078,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -Server $testServer - $result['Server'] | Should Be $testServer + $result['Server'] | Should -Be $testServer } It "Converts 'DomainAdministratorCredential' parameter to 'Credential' key" { @@ -1087,7 +1087,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -DomainAdministratorCredential $testCredential - $result['Credential'] | Should Be $testCredential + $result['Credential'] | Should -Be $testCredential } It "Converts 'DomainController' parameter to 'Server' key" { @@ -1096,7 +1096,7 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -DomainController $testServer - $result['Server'] | Should Be $testServer + $result['Server'] | Should -Be $testServer } It 'Accepts remaining arguments' { @@ -1104,83 +1104,83 @@ InModuleScope 'xActiveDirectory.Common' { $result = Get-ADCommonParameters -Identity $testIdentity -UnexpectedParameter 42 - $result['Identity'] | Should Be $testIdentity + $result['Identity'] | Should -Be $testIdentity } } Describe 'xActiveDirectory.Common\ConvertTo-DeploymentForestMode' { It 'Converts an Microsoft.ActiveDirectory.Management.ForestMode to Microsoft.DirectoryServices.Deployment.Types.ForestMode' { - ConvertTo-DeploymentForestMode -Mode Windows2012Forest | Should BeOfType [Microsoft.DirectoryServices.Deployment.Types.ForestMode] + ConvertTo-DeploymentForestMode -Mode Windows2012Forest | Should -BeOfType [Microsoft.DirectoryServices.Deployment.Types.ForestMode] } It 'Converts an Microsoft.ActiveDirectory.Management.ForestMode to the correct Microsoft.DirectoryServices.Deployment.Types.ForestMode' { - ConvertTo-DeploymentForestMode -Mode Windows2012Forest | Should Be ([Microsoft.DirectoryServices.Deployment.Types.ForestMode]::Win2012) + ConvertTo-DeploymentForestMode -Mode Windows2012Forest | Should -Be ([Microsoft.DirectoryServices.Deployment.Types.ForestMode]::Win2012) } It 'Converts valid integer to Microsoft.DirectoryServices.Deployment.Types.ForestMode' { - ConvertTo-DeploymentForestMode -ModeId 5 | Should BeOfType [Microsoft.DirectoryServices.Deployment.Types.ForestMode] + ConvertTo-DeploymentForestMode -ModeId 5 | Should -BeOfType [Microsoft.DirectoryServices.Deployment.Types.ForestMode] } It 'Converts a valid integer to the correct Microsoft.DirectoryServices.Deployment.Types.ForestMode' { - ConvertTo-DeploymentForestMode -ModeId 5 | Should Be ([Microsoft.DirectoryServices.Deployment.Types.ForestMode]::Win2012) + ConvertTo-DeploymentForestMode -ModeId 5 | Should -Be ([Microsoft.DirectoryServices.Deployment.Types.ForestMode]::Win2012) } It 'Throws an exception when an invalid forest mode is selected' { - { ConvertTo-DeploymentForestMode -Mode Nonexistant } | Should Throw + { ConvertTo-DeploymentForestMode -Mode Nonexistant } | Should -Throw } It 'Throws no exception when a null value is passed' { - { ConvertTo-DeploymentForestMode -Mode $null } | Should Not Throw + { ConvertTo-DeploymentForestMode -Mode $null } | Should -Not -Throw } It 'Throws no exception when an invalid mode id is selected' { - { ConvertTo-DeploymentForestMode -ModeId 666 } | Should Not Throw + { ConvertTo-DeploymentForestMode -ModeId 666 } | Should -Not -Throw } It 'Returns $null when a null value is passed' { - ConvertTo-DeploymentForestMode -Mode $null | Should Be $null + ConvertTo-DeploymentForestMode -Mode $null | Should -Be $null } It 'Returns $null when an invalid mode id is selected' { - ConvertTo-DeploymentForestMode -ModeId 666 | Should Be $null + ConvertTo-DeploymentForestMode -ModeId 666 | Should -Be $null } } Describe 'xActiveDirectory.Common\ConvertTo-DeploymentDomainMode' { It 'Converts an Microsoft.ActiveDirectory.Management.DomainMode to Microsoft.DirectoryServices.Deployment.Types.DomainMode' { - ConvertTo-DeploymentDomainMode -Mode Windows2012Domain | Should BeOfType [Microsoft.DirectoryServices.Deployment.Types.DomainMode] + ConvertTo-DeploymentDomainMode -Mode Windows2012Domain | Should -BeOfType [Microsoft.DirectoryServices.Deployment.Types.DomainMode] } It 'Converts an Microsoft.ActiveDirectory.Management.DomainMode to the correct Microsoft.DirectoryServices.Deployment.Types.DomainMode' { - ConvertTo-DeploymentDomainMode -Mode Windows2012Domain | Should Be ([Microsoft.DirectoryServices.Deployment.Types.DomainMode]::Win2012) + ConvertTo-DeploymentDomainMode -Mode Windows2012Domain | Should -Be ([Microsoft.DirectoryServices.Deployment.Types.DomainMode]::Win2012) } It 'Converts valid integer to Microsoft.DirectoryServices.Deployment.Types.DomainMode' { - ConvertTo-DeploymentDomainMode -ModeId 5 | Should BeOfType [Microsoft.DirectoryServices.Deployment.Types.DomainMode] + ConvertTo-DeploymentDomainMode -ModeId 5 | Should -BeOfType [Microsoft.DirectoryServices.Deployment.Types.DomainMode] } It 'Converts a valid integer to the correct Microsoft.DirectoryServices.Deployment.Types.DomainMode' { - ConvertTo-DeploymentDomainMode -ModeId 5 | Should Be ([Microsoft.DirectoryServices.Deployment.Types.DomainMode]::Win2012) + ConvertTo-DeploymentDomainMode -ModeId 5 | Should -Be ([Microsoft.DirectoryServices.Deployment.Types.DomainMode]::Win2012) } It 'Throws an exception when an invalid domain mode is selected' { - { ConvertTo-DeploymentDomainMode -Mode Nonexistant } | Should Throw + { ConvertTo-DeploymentDomainMode -Mode Nonexistant } | Should -Throw } It 'Throws no exception when a null value is passed' { - { ConvertTo-DeploymentDomainMode -Mode $null } | Should Not Throw + { ConvertTo-DeploymentDomainMode -Mode $null } | Should -Not -Throw } It 'Throws no exception when an invalid mode id is selected' { - { ConvertTo-DeploymentDomainMode -ModeId 666 } | Should Not Throw + { ConvertTo-DeploymentDomainMode -ModeId 666 } | Should -Not -Throw } It 'Returns $null when a null value is passed' { - ConvertTo-DeploymentDomainMode -Mode $null | Should Be $null + ConvertTo-DeploymentDomainMode -Mode $null | Should -Be $null } It 'Returns $null when an invalid mode id is selected' { - ConvertTo-DeploymentDomainMode -ModeId 666 | Should Be $null + ConvertTo-DeploymentDomainMode -ModeId 666 | Should -Be $null } } From d4b25a01400dd2b3b85bbde1e8a957d7f70baff1 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 10:07:16 +0200 Subject: [PATCH 04/29] Removed `-MockWith {}` in unit tests. --- CHANGELOG.md | 1 + Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 | 8 ++++---- Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b57a84cf2..766b88de2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ - Cleanup of code - Removed semicolon throughout where it is not needed. - Migrate tests to Pester syntax v4.x ([issue #322](https://github.com/PowerShell/xActiveDirectory/issues/322)). + - Removed `-MockWith {}` in unit tests. - Changes to xADComputer - Refactored the resource and the unit tests. - BREAKING CHANGE: The `Enabled` property is **DEPRECATED** and is no diff --git a/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 b/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 index 7c1cad7c2..30f71bff9 100644 --- a/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 +++ b/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 @@ -94,7 +94,7 @@ try #region Function Get-TargetResource Describe 'xADObjectPermissionEntry\Get-TargetResource' { - Mock -CommandName 'Assert-ADPSDrive' -MockWith { } + Mock -CommandName 'Assert-ADPSDrive' Context 'When the desired ace is present' { @@ -214,12 +214,12 @@ try #region Function Set-TargetResource Describe 'xADObjectPermissionEntry\Set-TargetResource' { - Mock -CommandName 'Assert-ADPSDrive' -MockWith { } + Mock -CommandName 'Assert-ADPSDrive' Context 'When the desired ace is present' { Mock -CommandName 'Get-Acl' -MockWith $mockGetAclPresent - Mock -CommandName 'Set-Acl' -MockWith { } -Verifiable + Mock -CommandName 'Set-Acl' Verifiable It 'Should call "Assert-ADPSDrive" to check AD PS Drive is created' { $targetResource = Get-TargetResource @testDefaultParameters -Verbose @@ -238,7 +238,7 @@ try Context 'When the desired ace is absent' { Mock -CommandName 'Get-Acl' -MockWith $mockGetAclAbsent - Mock -CommandName 'Set-Acl' -MockWith { } -Verifiable + Mock -CommandName 'Set-Acl' -Verifiable It 'Should call "Assert-ADPSDrive" to check AD PS Drive is created' { $targetResource = Get-TargetResource @testDefaultParameters -Verbose diff --git a/Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 b/Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 index 13425c32c..e983dbe40 100644 --- a/Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 +++ b/Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 @@ -180,7 +180,7 @@ try } Describe 'MSFT_xADRecycleBin\Set-TargetResource' { - Mock -CommandName Enable-ADOptionalFeature -MockWith { } + Mock -CommandName Enable-ADOptionalFeature Context 'When minimum forest level is too low' { Mock -CommandName Get-ADForest -MockWith { $mockADForestLevel3 } From 93fb0d2de149b2825328544d0e3e77f3674734e2 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 10:38:28 +0200 Subject: [PATCH 05/29] Changes to xADRecycleBin - Cleanup of code - It now set back the `$ErrorActionPreference` that was set prior to setting it to `'Stop'`. --- CHANGELOG.md | 4 + .../MSFT_xADRecycleBin.psm1 | 143 ++++++++---------- Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 | 24 +-- 3 files changed, 77 insertions(+), 94 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 766b88de2..2dbc7a080 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,10 @@ which were causing corruption in the Wiki documentation. - Changes to xWaitForADDomain - Added missing property schema descriptions ([issue #369](https://github.com/PowerShell/xActiveDirectory/issues/369)). +- Changes to xADRecycleBin + - Cleanup of code + - It now set back the `$ErrorActionPreference` that was set prior to + setting it to `'Stop'`. ## 2.26.0.0 diff --git a/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 b/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 index ced04758e..a34fd5bd6 100644 --- a/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 +++ b/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 @@ -21,56 +21,56 @@ function Get-TargetResource $EnterpriseAdministratorCredential ) - Try + $previousErrorActionPreference = $ErrorActionPreference + + try { # AD cmdlets generate non-terminating errors. $ErrorActionPreference = 'Stop' - $RootDSE = Get-ADRootDSE -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential - $RecycleBinPath = "CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,$($RootDSE.configurationNamingContext)" - $msDSEnabledFeature = Get-ADObject -Identity "CN=Partitions,$($RootDSE.configurationNamingContext)" -Property msDS-EnabledFeature -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential | - Select-Object -ExpandProperty msDS-EnabledFeature + $rootDSE = Get-ADRootDSE -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential + $recycleBinPath = "CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,$($rootDSE.configurationNamingContext)" + $msDSEnabledFeature = Get-ADObject -Identity "CN=Partitions,$($rootDSE.configurationNamingContext)" -Property 'msDS-EnabledFeature' -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential | + Select-Object -ExpandProperty 'msDS-EnabledFeature' - If ($msDSEnabledFeature -contains $RecycleBinPath) + if ($msDSEnabledFeature -contains $recycleBinPath) { Write-Verbose -Message $script:localizedData.RecycleBinEnabled - $RecycleBinEnabled = $True - } Else { + $recycleBinEnabled = $true + } + else + { Write-Verbose -Message $script:localizedData.RecycleBinNotEnabled - $RecycleBinEnabled = $False + $recycleBinEnabled = $false } } - - Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] + catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] { Write-Error -Message ($script:localizedData.ForestNotFound -f $ForestFQDN) - Throw $_ + throw $_ } - Catch [System.Security.Authentication.AuthenticationException] + catch [System.Security.Authentication.AuthenticationException] { Write-Error -Message $script:localizedData.CredentialError - Throw $_ + throw $_ } - Catch + catch { Write-Error -Message ($script:localizedData.GetUnhandledException -f $ForestFQDN) - Throw $_ + throw $_ } - - Finally { - $ErrorActionPreference = 'Continue' + finally + { + $ErrorActionPreference = $previousErrorActionPreference } - $returnValue = @{ + return @{ ForestFQDN = $ForestFQDN - RecycleBinEnabled = $RecycleBinEnabled - ForestMode = $RootDSE.forestFunctionality.ToString() + RecycleBinEnabled = $recycleBinEnabled + ForestMode = $rootDSE.forestFunctionality.ToString() } - - $returnValue } - function Set-TargetResource { [CmdletBinding(SupportsShouldProcess=$true)] @@ -85,54 +85,50 @@ function Set-TargetResource $EnterpriseAdministratorCredential ) + $previousErrorActionPreference = $ErrorActionPreference - Try + try { # AD cmdlets generate non-terminating errors. $ErrorActionPreference = 'Stop' - $Forest = Get-ADForest -Identity $ForestFQDN -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential + $forest = Get-ADForest -Identity $ForestFQDN -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential # Check minimum forest level and throw if not - If (($Forest.ForestMode -as [int]) -lt 4) + if (($forest.ForestMode -as [int]) -lt 4) { - Write-Verbose -Message ($script:localizedData.ForestFunctionalLevelError -f $Forest.ForestMode) - Throw ($script:localizedData.ForestFunctionalLevelError -f $Forest.ForestMode) + throw ($script:localizedData.ForestFunctionalLevelError -f $forest.ForestMode) } - If ($PSCmdlet.ShouldProcess($Forest.RootDomain, "Enable Active Directory Recycle Bin")) + if ($PSCmdlet.ShouldProcess($forest.RootDomain, "Enable Active Directory Recycle Bin")) { Enable-ADOptionalFeature 'Recycle Bin Feature' -Scope ForestOrConfigurationSet ` - -Target $Forest.RootDomain -Server $Forest.DomainNamingMaster ` + -Target $forest.RootDomain -Server $forest.DomainNamingMaster ` -Credential $EnterpriseAdministratorCredential ` -Verbose } } - - Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] + catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] { Write-Error -Message ($script:localizedData.ForestNotFound -f $ForestFQDN) - Throw $_ + throw $_ } - Catch [System.Security.Authentication.AuthenticationException] + catch [System.Security.Authentication.AuthenticationException] { Write-Error -Message $script:localizedData.CredentialError - Throw $_ + throw $_ } - Catch + catch { Write-Error -Message ($script:localizedData.SetUnhandledException -f $ForestFQDN) - Throw $_ + throw $_ } - - Finally + finally { - $ErrorActionPreference = 'Continue' + $ErrorActionPreference = $previousErrorActionPreference } - } - function Test-TargetResource { [CmdletBinding()] @@ -148,65 +144,48 @@ function Test-TargetResource $EnterpriseAdministratorCredential ) - Try + $previousErrorActionPreference = $ErrorActionPreference + + try { # AD cmdlets generate non-terminating errors. $ErrorActionPreference = 'Stop' - $RootDSE = Get-ADRootDSE -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential - $RecycleBinPath = "CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,$($RootDSE.configurationNamingContext)" - $msDSEnabledFeature = Get-ADObject -Identity "CN=Partitions,$($RootDSE.configurationNamingContext)" -Property msDS-EnabledFeature -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential | - Select-Object -ExpandProperty msDS-EnabledFeature + $rootDSE = Get-ADRootDSE -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential + $recycleBinPath = "CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,$($rootDSE.configurationNamingContext)" + $msDSEnabledFeature = Get-ADObject -Identity "CN=Partitions,$($rootDSE.configurationNamingContext)" -Property 'msDS-EnabledFeature' -Server $ForestFQDN -Credential $EnterpriseAdministratorCredential | + Select-Object -ExpandProperty 'msDS-EnabledFeature' - If ($msDSEnabledFeature -contains $RecycleBinPath) + if ($msDSEnabledFeature -contains $recycleBinPath) { Write-Verbose $script:localizedData.RecycleBinEnabled - Return $True - } Else { + return $true + } + else + { Write-Verbose $script:localizedData.RecycleBinNotEnabled - Return $False + return $false } } - - Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] + catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] { Write-Error -Message ($script:localizedData.ForestNotFound -f $ForestFQDN) - Throw $_ + throw $_ } - Catch [System.Security.Authentication.AuthenticationException] + catch [System.Security.Authentication.AuthenticationException] { Write-Error -Message $script:localizedData.CredentialError - Throw $_ + throw $_ } - Catch + catch { Write-Error -Message ($script:localizedData.TestUnhandledException -f $ForestFQDN) - Throw $_ + throw $_ } - - Finally + finally { - $ErrorActionPreference = 'Continue' + $ErrorActionPreference = $previousErrorActionPreference } - - } - Export-ModuleMember -Function *-TargetResource - -<# -Test syntax: - -$cred = Get-Credential contoso\administrator - -# Valid Domain -Get-TargetResource -ForestFQDN contoso.com -EnterpriseAdministratorCredential $cred -Test-TargetResource -ForestFQDN contoso.com -EnterpriseAdministratorCredential $cred -Set-TargetResource -ForestFQDN contoso.com -EnterpriseAdministratorCredential $cred -WhatIf - -# Invalid Domain -Get-TargetResource -ForestFQDN contoso.cm -EnterpriseAdministratorCredential $cred -Test-TargetResource -ForestFQDN contoso.cm -EnterpriseAdministratorCredential $cred -Set-TargetResource -ForestFQDN contoso.cm -EnterpriseAdministratorCredential $cred -WhatIf -#> diff --git a/Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 b/Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 index e983dbe40..c91a44536 100644 --- a/Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 +++ b/Tests/Unit/MSFT_xADRecycleBin.Tests.ps1 @@ -114,22 +114,22 @@ try Mock -CommandName Write-Error It 'Should throw ADIdentityNotFoundException' { - Mock -CommandName Get-ADObject -MockWith { Throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) } + Mock -CommandName Get-ADObject -MockWith { throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) } { Get-TargetResource @targetResourceParameters } | Should -Throw Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } It 'Should throw ADServerDownException' { - Mock -CommandName Get-ADObject -MockWith { Throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADServerDownException) } + Mock -CommandName Get-ADObject -MockWith { throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADServerDownException) } { Get-TargetResource @targetResourceParameters } | Should -Throw Microsoft.ActiveDirectory.Management.ADServerDownException } It 'Should throw AuthenticationException' { - Mock -CommandName Get-ADObject -MockWith { Throw (New-Object -TypeName System.Security.Authentication.AuthenticationException) } + Mock -CommandName Get-ADObject -MockWith { throw (New-Object -TypeName System.Security.Authentication.AuthenticationException) } { Get-TargetResource @targetResourceParameters } | Should -Throw 'System error' } It 'Should throw UnhandledException' { - Mock -CommandName Get-ADObject -MockWith { Throw Unhandled.Exception } + Mock -CommandName Get-ADObject -MockWith { throw Unhandled.Exception } { Get-TargetResource @targetResourceParameters } | Should -Throw Unhandled.Exception } } @@ -158,22 +158,22 @@ try Mock -CommandName Write-Error It 'Should throw ADIdentityNotFoundException' { - Mock -CommandName Get-ADObject -MockWith { Throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) } + Mock -CommandName Get-ADObject -MockWith { throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) } { Test-TargetResource @targetResourceParameters } | Should -Throw Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } It 'Should throw ADServerDownException' { - Mock -CommandName Get-ADObject -MockWith { Throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADServerDownException) } + Mock -CommandName Get-ADObject -MockWith { throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADServerDownException) } { Test-TargetResource @targetResourceParameters } | Should -Throw Microsoft.ActiveDirectory.Management.ADServerDownException } It 'Should throw AuthenticationException' { - Mock -CommandName Get-ADObject -MockWith { Throw (New-Object -TypeName System.Security.Authentication.AuthenticationException) } + Mock -CommandName Get-ADObject -MockWith { throw (New-Object -TypeName System.Security.Authentication.AuthenticationException) } { Test-TargetResource @targetResourceParameters } | Should -Throw 'System error' } It 'Should throw UnhandledException' { - Mock -CommandName Get-ADObject -MockWith { Throw Unhandled.Exception } + Mock -CommandName Get-ADObject -MockWith { throw Unhandled.Exception } { Test-TargetResource @targetResourceParameters } | Should -Throw Unhandled.Exception } } @@ -210,22 +210,22 @@ try Mock -CommandName Write-Error It 'Should throw ADIdentityNotFoundException' { - Mock -CommandName Get-ADForest -MockWith { Throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) } + Mock -CommandName Get-ADForest -MockWith { throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException) } { Set-TargetResource @targetResourceParameters } | Should -Throw Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } It 'Should throw ADServerDownException' { - Mock -CommandName Get-ADForest -MockWith { Throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADServerDownException) } + Mock -CommandName Get-ADForest -MockWith { throw (New-Object -TypeName Microsoft.ActiveDirectory.Management.ADServerDownException) } { Set-TargetResource @targetResourceParameters } | Should -Throw Microsoft.ActiveDirectory.Management.ADServerDownException } It 'Should throw AuthenticationException' { - Mock -CommandName Get-ADForest -MockWith { Throw (New-Object -TypeName System.Security.Authentication.AuthenticationException) } + Mock -CommandName Get-ADForest -MockWith { throw (New-Object -TypeName System.Security.Authentication.AuthenticationException) } { Set-TargetResource @targetResourceParameters } | Should -Throw 'System error' } It 'Should throw UnhandledException' { - Mock -CommandName Get-ADForest -MockWith { Throw Unhandled.Exception } + Mock -CommandName Get-ADForest -MockWith { throw Unhandled.Exception } { Set-TargetResource @targetResourceParameters } | Should -Throw Unhandled.Exception } } From 6b766555b0bde56f2beb032742204764d3091a1f Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 11:01:15 +0200 Subject: [PATCH 06/29] Changes to xADRecycleBin - Cleanup of code. --- CHANGELOG.md | 3 +- .../MSFT_xADDomain/MSFT_xADDomain.psm1 | 304 +++++++++++------- 2 files changed, 186 insertions(+), 121 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dbc7a080..47f67e820 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,6 +77,7 @@ a reboot. - Changes to xADDomainTrust - Replaced New-TerminatingError with Standard Function. + - Cleanup of code. - Changes to xWaitForADDomain - Suppressing the Script Analyzer rule `PSAvoidGlobalVars` since the resource is using the `$global:DSCMachineStatus` variable to trigger @@ -98,7 +99,7 @@ - Changes to xWaitForADDomain - Added missing property schema descriptions ([issue #369](https://github.com/PowerShell/xActiveDirectory/issues/369)). - Changes to xADRecycleBin - - Cleanup of code + - Cleanup of code. - It now set back the `$ErrorActionPreference` that was set prior to setting it to `'Stop'`. diff --git a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 index 4fdd2f47f..a5a74d630 100644 --- a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 +++ b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 @@ -36,7 +36,8 @@ function Get-TrackingFilename { [OutputType([String])] [CmdletBinding()] - param( + param + ( [Parameter(Mandatory = $true)] [String] $DomainName @@ -51,37 +52,56 @@ function Get-TargetResource param ( [Parameter(Mandatory = $true)] - [String] $DomainName, + [String] + $DomainName, [Parameter(Mandatory = $true)] - [PSCredential] $DomainAdministratorCredential, + [PSCredential] + $DomainAdministratorCredential, [Parameter(Mandatory = $true)] - [PSCredential] $SafemodeAdministratorPassword, + [PSCredential] + $SafemodeAdministratorPassword, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $ParentDomainName, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $ParentDomainName, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $DomainNetBIOSName, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $DomainNetBIOSName, - [Parameter()] [ValidateNotNullOrEmpty()] - [PSCredential] $DnsDelegationCredential, + [Parameter()] + [ValidateNotNullOrEmpty()] + [PSCredential] + $DnsDelegationCredential, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $DatabasePath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $DatabasePath, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $LogPath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $LogPath, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $SysvolPath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $SysvolPath, - [Parameter()] [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] - [String] $ForestMode, + [Parameter()] + [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] + [String] + $ForestMode, - [Parameter()] [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] - [String] $DomainMode + [Parameter()] + [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] + [String] + $DomainMode ) Assert-Module -ModuleName 'ADDSDeployment' -ImportModule @@ -94,75 +114,78 @@ function Get-TargetResource $domainShouldExist = (Test-Path (Get-TrackingFilename -DomainName $DomainName)) do { - try - { - if ($isDomainMember) + try { - ## We're already a domain member, so take the credentials out of the equation - Write-Verbose ($script:localizedData.QueryDomainWithLocalCredential -f $domainFQDN) - $domain = Get-ADDomain -Identity $domainFQDN -ErrorAction Stop - $forest = Get-ADForest -Identity $domain.Forest -ErrorAction Stop + if ($isDomainMember) + { + ## We're already a domain member, so take the credentials out of the equation + Write-Verbose ($script:localizedData.QueryDomainWithLocalCredential -f $domainFQDN) + $domain = Get-ADDomain -Identity $domainFQDN -ErrorAction Stop + $forest = Get-ADForest -Identity $domain.Forest -ErrorAction Stop + } + else { + Write-Verbose ($script:localizedData.QueryDomainWithCredential -f $domainFQDN) + $domain = Get-ADDomain -Identity $domainFQDN -Credential $DomainAdministratorCredential -ErrorAction Stop + $forest = Get-ADForest -Identity $domain.Forest -Credential $DomainAdministratorCredential -ErrorAction Stop + } + + ## No need to check whether the node is actually a domain controller. If we don't throw an exception, + ## the domain is already UP - and this resource shouldn't run. Domain controller functionality + ## should be checked by the xADDomainController resource? + Write-Verbose ($script:localizedData.DomainFound -f $domain.DnsRoot) + + $targetResource = @{ + DomainName = $domain.DnsRoot + ParentDomainName = $domain.ParentDomain + DomainNetBIOSName = $domain.NetBIOSName + ForestMode = (ConvertTo-DeploymentForestMode -Mode $forest.ForestMode) -as [String] + DomainMode = (ConvertTo-DeploymentDomainMode -Mode $domain.DomainMode) -as [String] + } + + return $targetResource } - else { - Write-Verbose ($script:localizedData.QueryDomainWithCredential -f $domainFQDN) - $domain = Get-ADDomain -Identity $domainFQDN -Credential $DomainAdministratorCredential -ErrorAction Stop - $forest = Get-ADForest -Identity $domain.Forest -Credential $DomainAdministratorCredential -ErrorAction Stop + catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] + { + $errorMessage = $script:localizedData.ExistingDomainMemberError -f $DomainName + ThrowInvalidOperationError -ErrorId 'xADDomain_DomainMember' -ErrorMessage $errorMessage } - - ## No need to check whether the node is actually a domain controller. If we don't throw an exception, - ## the domain is already UP - and this resource shouldn't run. Domain controller functionality - ## should be checked by the xADDomainController resource? - Write-Verbose ($script:localizedData.DomainFound -f $domain.DnsRoot) - - $targetResource = @{ - DomainName = $domain.DnsRoot - ParentDomainName = $domain.ParentDomain - DomainNetBIOSName = $domain.NetBIOSName - ForestMode = (ConvertTo-DeploymentForestMode -Mode $forest.ForestMode) -as [String] - DomainMode = (ConvertTo-DeploymentDomainMode -Mode $domain.DomainMode) -as [String] + catch [Microsoft.ActiveDirectory.Management.ADServerDownException] + { + Write-Verbose ($script:localizedData.DomainNotFound -f $domainFQDN) + $domain = @{ } + # will fall into retry mechanism } + catch [System.Security.Authentication.AuthenticationException] + { + $errorMessage = $script:localizedData.InvalidCredentialError -f $DomainName + ThrowInvalidOperationError -ErrorId 'xADDomain_InvalidCredential' -ErrorMessage $errorMessage + } + catch + { + $errorMessage = $script:localizedData.UnhandledError -f ($_.Exception | Format-List -Force | Out-String) + Write-Verbose $errorMessage - return $targetResource - } - catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] - { - $errorMessage = $script:localizedData.ExistingDomainMemberError -f $DomainName - ThrowInvalidOperationError -ErrorId 'xADDomain_DomainMember' -ErrorMessage $errorMessage - } - catch [Microsoft.ActiveDirectory.Management.ADServerDownException] - { - Write-Verbose ($script:localizedData.DomainNotFound -f $domainFQDN) - $domain = @{ } - # will fall into retry mechanism - } - catch [System.Security.Authentication.AuthenticationException] - { - $errorMessage = $script:localizedData.InvalidCredentialError -f $DomainName - ThrowInvalidOperationError -ErrorId 'xADDomain_InvalidCredential' -ErrorMessage $errorMessage - } - catch - { - $errorMessage = $script:localizedData.UnhandledError -f ($_.Exception | Format-List -Force | Out-String) - Write-Verbose $errorMessage + if ($domainShouldExist -and ($_.Exception.InnerException -is [System.ServiceModel.FaultException])) + { + Write-Verbose $script:localizedData.FaultExceptionAndDomainShouldExist + # will fall into retry mechanism + } + else + { + ## Not sure what's gone on here! + throw $_ + } + } - if ($domainShouldExist -and ($_.Exception.InnerException -is [System.ServiceModel.FaultException])) + if ($domainShouldExist) { - Write-Verbose $script:localizedData.FaultExceptionAndDomainShouldExist - # will fall into retry mechanism - } else { - ## Not sure what's gone on here! - throw $_ - } - } + $retries++ - if($domainShouldExist) - { - $retries++ - Write-Verbose ($script:localizedData.RetryingGetADDomain -f $retries, $maxRetries, $retryIntervalInSeconds) - Start-Sleep -Seconds ($retries * $retryIntervalInSeconds) - } + Write-Verbose ($script:localizedData.RetryingGetADDomain -f $retries, $maxRetries, $retryIntervalInSeconds) - } while ($domainShouldExist -and ($retries -le $maxRetries) ) + Start-Sleep -Seconds ($retries * $retryIntervalInSeconds) + } + } while ($domainShouldExist -and ($retries -le $maxRetries)) } #end function Get-TargetResource @@ -172,37 +195,56 @@ function Test-TargetResource param ( [Parameter(Mandatory = $true)] - [String] $DomainName, + [String] + $DomainName, [Parameter(Mandatory = $true)] - [PSCredential] $DomainAdministratorCredential, + [PSCredential] + $DomainAdministratorCredential, [Parameter(Mandatory = $true)] - [PSCredential] $SafemodeAdministratorPassword, + [PSCredential] + $SafemodeAdministratorPassword, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $ParentDomainName, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $ParentDomainName, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $DomainNetBIOSName, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $DomainNetBIOSName, - [Parameter()] [ValidateNotNullOrEmpty()] - [PSCredential] $DnsDelegationCredential, + [Parameter()] + [ValidateNotNullOrEmpty()] + [PSCredential] + $DnsDelegationCredential, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $DatabasePath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $DatabasePath, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $LogPath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $LogPath, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $SysvolPath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $SysvolPath, - [Parameter()] [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] - [String] $ForestMode, + [Parameter()] + [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] + [String] + $ForestMode, - [Parameter()] [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] - [String] $DomainMode + [Parameter()] + [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] + [String] + $DomainMode ) $targetResource = Get-TargetResource @PSBoundParameters @@ -224,6 +266,7 @@ function Test-TargetResource if ($PSBoundParameters.ContainsKey($propertyName)) { $propertyValue = (Get-Variable -Name $propertyName).Value + if ($targetResource.$propertyName -ne $propertyValue) { $message = $script:localizedData.ResourcePropertyValueIncorrect -f $propertyName, $propertyValue, $targetResource.$propertyName @@ -243,7 +286,6 @@ function Test-TargetResource Write-Verbose -Message ($script:localizedData.ResourceNotInDesiredState -f $domainFQDN) return $false } - } #end function Test-TargetResource function Set-TargetResource @@ -263,37 +305,56 @@ function Set-TargetResource param ( [Parameter(Mandatory = $true)] - [String] $DomainName, + [String] + $DomainName, [Parameter(Mandatory = $true)] - [PSCredential] $DomainAdministratorCredential, + [PSCredential] + $DomainAdministratorCredential, [Parameter(Mandatory = $true)] - [PSCredential] $SafemodeAdministratorPassword, + [PSCredential] + $SafemodeAdministratorPassword, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $ParentDomainName, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $ParentDomainName, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $DomainNetBIOSName, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $DomainNetBIOSName, - [Parameter()] [ValidateNotNullOrEmpty()] - [PSCredential] $DnsDelegationCredential, + [Parameter()] + [ValidateNotNullOrEmpty()] + [PSCredential] + $DnsDelegationCredential, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $DatabasePath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $DatabasePath, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $LogPath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $LogPath, - [Parameter()] [ValidateNotNullOrEmpty()] - [String] $SysvolPath, + [Parameter()] + [ValidateNotNullOrEmpty()] + [String] + $SysvolPath, - [Parameter()] [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] - [String] $ForestMode, + [Parameter()] + [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] + [String] + $ForestMode, - [Parameter()] [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] - [String] $DomainMode + [Parameter()] + [ValidateSet('Win2008', 'Win2008R2', 'Win2012', 'Win2012R2', 'WinThreshold')] + [String] + $DomainMode ) # Debug can pause Install-ADDSForest/Install-ADDSDomain, so we remove it. @@ -340,7 +401,9 @@ function Set-TargetResource { $installADDSParams['NewDomainNetbiosName'] = $DomainNetBIOSName } + Install-ADDSDomain @installADDSParams + Write-Verbose -Message ($script:localizedData.CreatedChildDomain) } else @@ -355,7 +418,9 @@ function Set-TargetResource { $installADDSParams['ForestMode'] = $ForestMode } + Install-ADDSForest @installADDSParams + Write-Verbose -Message ($script:localizedData.CreatedForest -f $DomainName) } @@ -364,7 +429,6 @@ function Set-TargetResource # Signal to the LCM to reboot the node to compensate for the one we # suppressed from Install-ADDSForest/Install-ADDSDomain $global:DSCMachineStatus = 1 - } #end function Set-TargetResource Export-ModuleMember -Function *-TargetResource From 75d0b93441fda53413f82ea79c41490cf715412a Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 11:05:40 +0200 Subject: [PATCH 07/29] Changes to xADDomainDefaultPasswordPolicy - Cleanup of code. --- CHANGELOG.md | 2 + .../MSFT_xADDomainDefaultPasswordPolicy.psm1 | 151 +++++++++++++----- 2 files changed, 109 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47f67e820..51b23a1c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,8 @@ - Cleanup of code. - It now set back the `$ErrorActionPreference` that was set prior to setting it to `'Stop'`. +- Changes to xADDomainDefaultPasswordPolicy + - Cleanup of code. ## 2.26.0.0 diff --git a/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 b/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 index 4006db3e9..f5a3694b0 100644 --- a/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 +++ b/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 @@ -8,15 +8,37 @@ $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_xADDomainDefaultPa ## List of changeable policy properties $mutablePropertyMap = @( - @{ Name = 'ComplexityEnabled'; } - @{ Name = 'LockoutDuration'; IsTimeSpan = $true; } - @{ Name = 'LockoutObservationWindow'; IsTimeSpan = $true; } - @{ Name = 'LockoutThreshold'; } - @{ Name = 'MinPasswordAge'; IsTimeSpan = $true; } - @{ Name = 'MaxPasswordAge'; IsTimeSpan = $true; } - @{ Name = 'MinPasswordLength'; } - @{ Name = 'PasswordHistoryCount'; } - @{ Name = 'ReversibleEncryptionEnabled'; } + @{ + Name = 'ComplexityEnabled' + } + @{ + Name = 'LockoutDuration' + IsTimeSpan = $true + } + @{ + Name = 'LockoutObservationWindow' + IsTimeSpan = $true + } + @{ + Name = 'LockoutThreshold' + } + @{ + Name = 'MinPasswordAge' + IsTimeSpan = $true + } + @{ + Name = 'MaxPasswordAge' + IsTimeSpan = $true + } + @{ + Name = 'MinPasswordLength' + } + @{ + Name = 'PasswordHistoryCount' + } + @{ + Name = 'ReversibleEncryptionEnabled' + } ) function Get-TargetResource @@ -26,11 +48,13 @@ function Get-TargetResource param ( [Parameter(Mandatory = $true)] - [System.String] $DomainName, + [System.String] + $DomainName, [Parameter()] [ValidateNotNullOrEmpty()] - [System.String] $DomainController, + [System.String] + $DomainController, [Parameter()] [System.Management.Automation.PSCredential] @@ -40,22 +64,25 @@ function Get-TargetResource Assert-Module -ModuleName 'ActiveDirectory' $PSBoundParameters['Identity'] = $DomainName + $getADDefaultDomainPasswordPolicyParams = Get-ADCommonParameters @PSBoundParameters + Write-Verbose -Message ($script:localizedData.QueryingDomainPasswordPolicy -f $DomainName) + $policy = Get-ADDefaultDomainPasswordPolicy @getADDefaultDomainPasswordPolicyParams - $targetResource = @{ - DomainName = $DomainName - ComplexityEnabled = $policy.ComplexityEnabled - LockoutDuration = ConvertFrom-Timespan -Timespan $policy.LockoutDuration -TimeSpanType Minutes - LockoutObservationWindow = ConvertFrom-Timespan -Timespan $policy.LockoutObservationWindow -TimeSpanType Minutes - LockoutThreshold = $policy.LockoutThreshold - MinPasswordAge = ConvertFrom-Timespan -Timespan $policy.MinPasswordAge -TimeSpanType Minutes - MaxPasswordAge = ConvertFrom-Timespan -Timespan $policy.MaxPasswordAge -TimeSpanType Minutes - MinPasswordLength = $policy.MinPasswordLength - PasswordHistoryCount = $policy.PasswordHistoryCount + + return @{ + DomainName = $DomainName + ComplexityEnabled = $policy.ComplexityEnabled + LockoutDuration = ConvertFrom-Timespan -Timespan $policy.LockoutDuration -TimeSpanType Minutes + LockoutObservationWindow = ConvertFrom-Timespan -Timespan $policy.LockoutObservationWindow -TimeSpanType Minutes + LockoutThreshold = $policy.LockoutThreshold + MinPasswordAge = ConvertFrom-Timespan -Timespan $policy.MinPasswordAge -TimeSpanType Minutes + MaxPasswordAge = ConvertFrom-Timespan -Timespan $policy.MaxPasswordAge -TimeSpanType Minutes + MinPasswordLength = $policy.MinPasswordLength + PasswordHistoryCount = $policy.PasswordHistoryCount ReversibleEncryptionEnabled = $policy.ReversibleEncryptionEnabled } - return $targetResource } #end Get-TargetResource function Test-TargetResource @@ -65,65 +92,82 @@ function Test-TargetResource param ( [Parameter(Mandatory = $true)] - [System.String] $DomainName, + [System.String] + $DomainName, [Parameter()] - [System.Boolean] $ComplexityEnabled, + [System.Boolean] + $ComplexityEnabled, [Parameter()] - [System.UInt32] $LockoutDuration, + [System.UInt32] + $LockoutDuration, [Parameter()] - [System.UInt32] $LockoutObservationWindow, + [System.UInt32] + $LockoutObservationWindow, [Parameter()] - [System.UInt32] $LockoutThreshold, + [System.UInt32] + $LockoutThreshold, [Parameter()] - [System.UInt32] $MinPasswordAge, + [System.UInt32] + $MinPasswordAge, [Parameter()] - [System.UInt32] $MaxPasswordAge, + [System.UInt32] + $MaxPasswordAge, [Parameter()] - [System.UInt32] $MinPasswordLength, + [System.UInt32] + $MinPasswordLength, [Parameter()] - [System.UInt32] $PasswordHistoryCount, + [System.UInt32] + $PasswordHistoryCount, [Parameter()] - [System.Boolean] $ReversibleEncryptionEnabled, + [System.Boolean] + $ReversibleEncryptionEnabled, [Parameter()] [ValidateNotNullOrEmpty()] - [System.String] $DomainController, + [System.String] + $DomainController, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential ) + $getTargetResourceParams = @{ DomainName = $DomainName } + if ($PSBoundParameters.ContainsKey('Credential')) { $getTargetResourceParams['Credential'] = $Credential } + if ($PSBoundParameters.ContainsKey('DomainController')) { $getTargetResourceParams['DomainController'] = $DomainController } + $targetResource = Get-TargetResource @getTargetResourceParams $inDesiredState = $true foreach ($property in $mutablePropertyMap) { $propertyName = $property.Name + if ($PSBoundParameters.ContainsKey($propertyName)) { $expectedValue = $PSBoundParameters[$propertyName] $actualValue = $targetResource[$propertyName] + if ($expectedValue -ne $actualValue) { $valueIncorrectMessage = $script:localizedData.ResourcePropertyValueIncorrect -f $propertyName, $expectedValue, $actualValue @@ -151,64 +195,83 @@ function Set-TargetResource param ( [Parameter(Mandatory = $true)] - [System.String] $DomainName, + [System.String] + $DomainName, [Parameter()] - [System.Boolean] $ComplexityEnabled, + [System.Boolean] + $ComplexityEnabled, [Parameter()] - [System.UInt32] $LockoutDuration, + [System.UInt32] + $LockoutDuration, [Parameter()] - [System.UInt32] $LockoutObservationWindow, + [System.UInt32] + $LockoutObservationWindow, [Parameter()] - [System.UInt32] $LockoutThreshold, + [System.UInt32] + $LockoutThreshold, [Parameter()] - [System.UInt32] $MinPasswordAge, + [System.UInt32] + $MinPasswordAge, [Parameter()] - [System.UInt32] $MaxPasswordAge, + [System.UInt32] + $MaxPasswordAge, [Parameter()] - [System.UInt32] $MinPasswordLength, + [System.UInt32] + $MinPasswordLength, [Parameter()] - [System.UInt32] $PasswordHistoryCount, + [System.UInt32] + $PasswordHistoryCount, [Parameter()] - [System.Boolean] $ReversibleEncryptionEnabled, + [System.Boolean] + $ReversibleEncryptionEnabled, [Parameter()] [ValidateNotNullOrEmpty()] - [System.String] $DomainController, + [System.String] + $DomainController, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential ) + Assert-Module -ModuleName 'ActiveDirectory' + $PSBoundParameters['Identity'] = $DomainName + $setADDefaultDomainPasswordPolicyParams = Get-ADCommonParameters @PSBoundParameters foreach ($property in $mutablePropertyMap) { $propertyName = $property.Name + if ($PSBoundParameters.ContainsKey($propertyName)) { $propertyValue = $PSBoundParameters[$propertyName] + if ($property.IsTimeSpan -eq $true) { $propertyValue = ConvertTo-TimeSpan -TimeSpan $propertyValue -TimeSpanType Minutes } + $setADDefaultDomainPasswordPolicyParams[$propertyName] = $propertyValue + Write-Verbose -Message ($script:localizedData.SettingPasswordPolicyValue -f $propertyName, $propertyValue) } } Write-Verbose -Message ($script:localizedData.UpdatingDomainPasswordPolicy -f $DomainName) + [ref] $null = Set-ADDefaultDomainPasswordPolicy @setADDefaultDomainPasswordPolicyParams } #end Set-TargetResource From 5a0df708c193a51204167f7fb2f1be2fe044dfd5 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 11:20:21 +0200 Subject: [PATCH 08/29] Changes to xADDomainTrust - Cleanup of code. --- CHANGELOG.md | 2 + .../MSFT_xADDomainTrust.psm1 | 266 ++++++++++-------- 2 files changed, 157 insertions(+), 111 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51b23a1c5..70de15b49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -104,6 +104,8 @@ setting it to `'Stop'`. - Changes to xADDomainDefaultPasswordPolicy - Cleanup of code. +- Changes to xADDomainTrust + - Cleanup of code. ## 2.26.0.0 diff --git a/DSCResources/MSFT_xADDomainTrust/MSFT_xADDomainTrust.psm1 b/DSCResources/MSFT_xADDomainTrust/MSFT_xADDomainTrust.psm1 index 1b1e9101c..8c859659d 100644 --- a/DSCResources/MSFT_xADDomainTrust/MSFT_xADDomainTrust.psm1 +++ b/DSCResources/MSFT_xADDomainTrust/MSFT_xADDomainTrust.psm1 @@ -13,29 +13,33 @@ function Get-TargetResource param ( [Parameter(Mandatory = $true)] - [String]$SourceDomainName, + [String] + $SourceDomainName, [Parameter(Mandatory = $true)] - [String]$TargetDomainName, + [String] + $TargetDomainName, [Parameter(Mandatory = $true)] - [PSCredential]$TargetDomainAdministratorCredential, + [PSCredential] + $TargetDomainAdministratorCredential, [Parameter(Mandatory = $true)] - [ValidateSet("External","Forest")] - [String]$TrustType, + [ValidateSet('External', 'Forest')] + [String] + $TrustType, [Parameter(Mandatory = $true)] - [ValidateSet("Bidirectional","Inbound","Outbound")] - [String]$TrustDirection, + [ValidateSet('Bidirectional', 'Inbound', 'Outbound')] + [String] + $TrustDirection, [Parameter()] - [ValidateSet("Present","Absent")] - [String]$Ensure = 'Present' + [ValidateSet('Present', 'Absent')] + [String] + $Ensure = 'Present' ) -#region Input Validation - # Load the .NET assembly try { @@ -48,52 +52,58 @@ function Get-TargetResource New-ObjectNotFoundException -Message $missingRoleMessage -ErrorRecord $_ } -#endregion - try { switch ($TrustType) { - 'External' {$DomainOrForest = 'Domain'} - 'Forest' {$DomainOrForest = 'Forest'} + 'External' + { + $DomainOrForest = 'Domain' + } + + 'Forest' + { + $DomainOrForest = 'Forest' + } } + # Create the target object - $trgDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest,$TargetDomainName, $TargetDomainAdministratorCredential.UserName, $TargetDomainAdministratorCredential.GetNetworkCredential().Password) + $trgDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest, $TargetDomainName, $TargetDomainAdministratorCredential.UserName, $TargetDomainAdministratorCredential.GetNetworkCredential().Password) $trgDomain = ([type]"System.DirectoryServices.ActiveDirectory.$DomainOrForest")::"Get$DomainOrForest"($trgDirectoryContext) + # Create the source object - $srcDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest,$SourceDomainName) + $srcDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest, $SourceDomainName) $srcDomain = ([type]"System.DirectoryServices.ActiveDirectory.$DomainOrForest")::"Get$DomainOrForest"($srcDirectoryContext) # Find trust between source & destination. Write-Verbose -Message ($script:localizedData.CheckingTrustMessage -f $SourceDomainName, $TargetDomainName) $trust = $srcDomain.GetTrustRelationship($trgDomain) - Write-Verbose -Message ($script:localizedData.TrustPresentMessage -f $SourceDomainName, $TargetDomainName) + Write-Verbose -Message ($script:localizedData.TrustPresentMessage -f $SourceDomainName, $TargetDomainName) $Ensure = 'Present' } catch { - Write-Verbose -Message ($script:localizedData.TrustAbsentMessage -f $SourceDomainName, $TargetDomainName) + Write-Verbose -Message ($script:localizedData.TrustAbsentMessage -f $SourceDomainName, $TargetDomainName) $Ensure = 'Absent' } # return a credential object without password $CIMCredential = New-CimInstance -ClassName MSFT_Credential -ClientOnly ` - -Namespace root/microsoft/windows/desiredstateconfiguration ` - -Property @{ - UserName = [string]$TargetDomainAdministratorCredential.UserName - Password = [string]$null - } - - @{ - SourceDomainName = $SourceDomainName - TargetDomainName = $TargetDomainName - Ensure = $Ensure - TrustType = $trust.TrustType - TrustDirection = $trust.TrustDirection - TargetDomainAdministratorCredential = $CIMCredential + -Namespace 'root/microsoft/windows/desiredstateconfiguration' ` + -Property @{ + UserName = [string] $TargetDomainAdministratorCredential.UserName + Password = [string] $null } + return @{ + SourceDomainName = $SourceDomainName + TargetDomainName = $TargetDomainName + Ensure = $Ensure + TrustType = $trust.TrustType + TrustDirection = $trust.TrustDirection + TargetDomainAdministratorCredential = $CIMCredential + } } function Set-TargetResource @@ -104,28 +114,38 @@ function Set-TargetResource param ( [Parameter(Mandatory = $true)] - [String]$SourceDomainName, + [String] + $SourceDomainName, [Parameter(Mandatory = $true)] - [String]$TargetDomainName, + [String] + $TargetDomainName, [Parameter(Mandatory = $true)] - [PSCredential]$TargetDomainAdministratorCredential, + [PSCredential] + $TargetDomainAdministratorCredential, [Parameter(Mandatory = $true)] - [ValidateSet("External","Forest")] - [String]$TrustType, + [ValidateSet('External', 'Forest')] + [String] + $TrustType, [Parameter(Mandatory = $true)] - [ValidateSet("Bidirectional","Inbound","Outbound")] - [String]$TrustDirection, + [ValidateSet('Bidirectional', 'Inbound', 'Outbound')] + [String] + $TrustDirection, [Parameter()] - [ValidateSet("Present","Absent")] - [String]$Ensure = 'Present' + [ValidateSet('Present', 'Absent')] + [String] + $Ensure = 'Present' ) - if($PSBoundParameters.ContainsKey('Debug')){$null = $PSBoundParameters.Remove('Debug')} + if ($PSBoundParameters.ContainsKey('Debug')) + { + $null = $PSBoundParameters.Remove('Debug') + } + Confirm-ResourceProperties @PSBoundParameters -Apply } @@ -138,28 +158,34 @@ function Test-TargetResource param ( [Parameter(Mandatory = $true)] - [String]$SourceDomainName, + [String] + $SourceDomainName, [Parameter(Mandatory = $true)] - [String]$TargetDomainName, + [String] + $TargetDomainName, [Parameter(Mandatory = $true)] - [PSCredential]$TargetDomainAdministratorCredential, + [PSCredential] + $TargetDomainAdministratorCredential, [Parameter(Mandatory = $true)] - [ValidateSet("External","Forest")] - [String]$TrustType, + [ValidateSet('External', 'Forest')] + [String] + $TrustType, [Parameter(Mandatory = $true)] - [ValidateSet("Bidirectional","Inbound","Outbound")] - [String]$TrustDirection, + [ValidateSet('Bidirectional', 'Inbound', 'Outbound')] + [String] + $TrustDirection, [Parameter()] - [ValidateSet("Present","Absent")] - [String]$Ensure = 'Present' + [ValidateSet('Present', 'Absent')] + [String] + $Ensure = 'Present' ) -#region Input Validation + #region Input Validation # Load the .NET assembly try @@ -173,88 +199,107 @@ function Test-TargetResource New-ObjectNotFoundException -Message $missingRoleMessage -ErrorRecord $_ } -#endregion + #endregion + + if ($PSBoundParameters.ContainsKey('Debug')) + { + $null = $PSBoundParameters.Remove('Debug') + } - if($PSBoundParameters.ContainsKey('Debug')){$null = $PSBoundParameters.Remove('Debug')} Confirm-ResourceProperties @PSBoundParameters } -#region Helper Functions function Confirm-ResourceProperties { - [Cmdletbinding()] + [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] - [String]$SourceDomainName, + [String] + $SourceDomainName, [Parameter(Mandatory = $true)] - [String]$TargetDomainName, + [String] + $TargetDomainName, [Parameter(Mandatory = $true)] - [PSCredential]$TargetDomainAdministratorCredential, + [PSCredential] + $TargetDomainAdministratorCredential, [Parameter(Mandatory = $true)] - [ValidateSet("External","Forest")] - [String]$TrustType, + [ValidateSet('External', 'Forest')] + [String] + $TrustType, [Parameter(Mandatory = $true)] - [ValidateSet("Bidirectional","Inbound","Outbound")] - [String]$TrustDirection, + [ValidateSet('Bidirectional', 'Inbound', 'Outbound')] + [String] + $TrustDirection, [Parameter()] - [ValidateSet("Present","Absent")] - [String]$Ensure = 'Present', + [ValidateSet('Present', 'Absent')] + [String] + $Ensure = 'Present', [Parameter()] - [Switch]$Apply + [Switch] + $Apply ) try { - $checkingTrustMessage = $($script:localizedData.CheckingTrustMessage) -f $SourceDomainName,$TargetDomainName + $checkingTrustMessage = $script:localizedData.CheckingTrustMessage -f $SourceDomainName, $TargetDomainName Write-Verbose -Message $checkingTrustMessage switch ($TrustType) { - 'External' {$DomainOrForest = 'Domain'} - 'Forest' {$DomainOrForest = 'Forest'} + 'External' + { + $DomainOrForest = 'Domain' + } + + 'Forest' + { + $DomainOrForest = 'Forest' + } } + # Create the target object - $trgDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest,$TargetDomainName, $TargetDomainAdministratorCredential.UserName, $TargetDomainAdministratorCredential.GetNetworkCredential().Password) + $trgDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest, $TargetDomainName, $TargetDomainAdministratorCredential.UserName, $TargetDomainAdministratorCredential.GetNetworkCredential().Password) $trgDomain = ([type]"System.DirectoryServices.ActiveDirectory.$DomainOrForest")::"Get$DomainOrForest"($trgDirectoryContext) + # Create the source object - $srcDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest,$SourceDomainName) + $srcDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest, $SourceDomainName) $srcDomain = ([type]"System.DirectoryServices.ActiveDirectory.$DomainOrForest")::"Get$DomainOrForest"($srcDirectoryContext) # Find trust try { - # Find trust betwen source & destination. + # Find trust between source & destination. $trust = $srcDomain.GetTrustRelationship($TargetDomainName) - $TestTrustMessage = $($script:localizedData.TestTrustMessage) -f 'present',$Ensure + $TestTrustMessage = $script:localizedData.TestTrustMessage -f 'present', $Ensure Write-Verbose -Message $TestTrustMessage - if($Ensure -eq 'Present') + if ($Ensure -eq 'Present') { #region Test for trust direction - - $CheckPropertyMessage = $($script:localizedData.CheckPropertyMessage) -f 'trust direction' + $CheckPropertyMessage = $script:localizedData.CheckPropertyMessage -f 'trust direction' Write-Verbose -Message $CheckPropertyMessage - # Set the trust direction if not correct - if($trust.TrustDirection -ne $TrustDirection) + if ($trust.TrustDirection -ne $TrustDirection) { - $notDesiredPropertyMessage = $($script:localizedData.NotDesiredPropertyMessage) -f 'Trust direction',$TrustDirection,$trust.TrustDirection + # Set the trust direction if not correct + + $notDesiredPropertyMessage = $script:localizedData.NotDesiredPropertyMessage -f 'Trust direction', $TrustDirection, $trust.TrustDirection Write-Verbose -Message $notDesiredPropertyMessage - if($Apply) + if ($Apply) { - $srcDomain.UpdateTrustRelationship($trgDomain,$TrustDirection) + $srcDomain.UpdateTrustRelationship($trgDomain, $TrustDirection) - $setPropertyMessage = $($script:localizedData.SetPropertyMessage) -f 'Trust direction' + $setPropertyMessage = $script:localizedData.SetPropertyMessage -f 'Trust direction' Write-Verbose -Message $setPropertyMessage } else @@ -262,34 +307,34 @@ function Confirm-ResourceProperties return $false } } # end trust direction is not correct - - # Trust direction is correct else { - $desiredPropertyMessage = $($script:localizedData.DesiredPropertyMessage) -f 'Trust direction' + # Trust direction is correct + + $desiredPropertyMessage = $script:localizedData.DesiredPropertyMessage -f 'Trust direction' Write-Verbose -Message $desiredPropertyMessage } #endregion trust direction #region Test for trust type - - $CheckPropertyMessage = $($script:localizedData.CheckPropertyMessage) -f 'trust type' + $CheckPropertyMessage = $script:localizedData.CheckPropertyMessage -f 'trust type' Write-Verbose -Message $CheckPropertyMessage - # Set the trust type if not correct - if($trust.TrustType-ne $TrustType) + if ($trust.TrustType -ne $TrustType) { - $notDesiredPropertyMessage = $($script:localizedData.NotDesiredPropertyMessage) -f 'Trust type',$TrustType,$trust.TrustType + # Set the trust type if not correct + + $notDesiredPropertyMessage = $script:localizedData.NotDesiredPropertyMessage -f 'Trust type', $TrustType, $trust.TrustType Write-Verbose -Message $notDesiredPropertyMessage - if($Apply) + if ($Apply) { # Only way to fix the trust direction is to delete it and create again # TODO: Add a property to ask user permission to delete an existing trust $srcDomain.DeleteTrustRelationship($trgDomain) - $srcDomain.CreateTrustRelationship($trgDomain,$TrustDirection) + $srcDomain.CreateTrustRelationship($trgDomain, $TrustDirection) - $setPropertyMessage = $($script:localizedData.SetPropertyMessage) -f 'Trust type' + $setPropertyMessage = $script:localizedData.SetPropertyMessage -f 'Trust type' Write-Verbose -Message $setPropertyMessage } else @@ -297,29 +342,28 @@ function Confirm-ResourceProperties return $false } } # end trust type is not correct - - # Trust type is correct else { - $desiredPropertyMessage = $($script:localizedData.DesiredPropertyMessage) -f 'Trust type' + # Trust type is correct + + $desiredPropertyMessage = $script:localizedData.DesiredPropertyMessage -f 'Trust type' Write-Verbose -Message $desiredPropertyMessage } - #endregion Test for trust type # If both trust type and trust direction are correct, return true - if(-not $Apply) + if (-not $Apply) { return $true } } # end Ensure -eq present - - # If the trust should be absent, remove the trust else { - if($Apply) + # If the trust should be absent, remove the trust + + if ($Apply) { - $removingTrustMessage = $($script:localizedData.RemovingTrustMessage) -f $SourceDomainName,$TargetDomainName + $removingTrustMessage = $script:localizedData.RemovingTrustMessage -f $SourceDomainName, $TargetDomainName Write-Verbose -Message $removingTrustMessage $srcDomain.DeleteTrustRelationship($trgDomain) @@ -333,21 +377,21 @@ function Confirm-ResourceProperties } } # end Ensure -eq absent } # end find trust - - # Trust does not exist between source and destination catch [System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectNotFoundException] { - $TestTrustMessage = $($script:localizedData.TestTrustMessage) -f 'absent',$Ensure + # Trust does not exist between source and destination + + $TestTrustMessage = $script:localizedData.TestTrustMessage -f 'absent', $Ensure Write-Verbose -Message $TestTrustMessage - if($Ensure -eq 'Present') + if ($Ensure -eq 'Present') { - if($Apply) + if ($Apply) { - $addingTrustMessage = $($script:localizedData.AddingTrustMessage) -f $SourceDomainName,$TargetDomainName + $addingTrustMessage = $script:localizedData.AddingTrustMessage -f $SourceDomainName, $TargetDomainName Write-Verbose -Message $addingTrustMessage - $srcDomain.CreateTrustRelationship($trgDomain,$TrustDirection) + $srcDomain.CreateTrustRelationship($trgDomain, $TrustDirection) $setTrustMessage = $script:localizedData.SetTrustMessage Write-Verbose -Message $setTrustMessage @@ -359,13 +403,13 @@ function Confirm-ResourceProperties } # end Ensure -eq Present else { - if(-not $Apply) + if (-not $Apply) { return $true } } } # end no trust - }# end getting directory object + } # end getting directory object catch [System.DirectoryServices.ActiveDirectory.ActiveDirectoryObjectNotFoundException] { throw From 0530c55983ca22abd49a7910e3ad9720f69d4dc1 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 11:25:05 +0200 Subject: [PATCH 09/29] Changes to xADForestProperties - Minor style cleanup. --- CHANGELOG.md | 2 + .../MSFT_xADForestProperties.psm1 | 140 ++++++++++-------- 2 files changed, 78 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70de15b49..dbbbe5162 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -106,6 +106,8 @@ - Cleanup of code. - Changes to xADDomainTrust - Cleanup of code. +- Changes to xADForestProperties + - Minor style cleanup. ## 2.26.0.0 diff --git a/DSCResources/MSFT_xADForestProperties/MSFT_xADForestProperties.psm1 b/DSCResources/MSFT_xADForestProperties/MSFT_xADForestProperties.psm1 index 9616ea770..a164e8c48 100644 --- a/DSCResources/MSFT_xADForestProperties/MSFT_xADForestProperties.psm1 +++ b/DSCResources/MSFT_xADForestProperties/MSFT_xADForestProperties.psm1 @@ -7,34 +7,34 @@ Import-Module -Name (Join-Path -Path $script:localizationModulePath -ChildPath ' $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_xADForestProperties' <# -.SYNOPSIS - Gets the current state of user principal name and service principal name suffixes in the forest. + .SYNOPSIS + Gets the current state of user principal name and service principal name suffixes in the forest. -.PARAMETER Credential - The user account credentials to use to perform this task. + .PARAMETER Credential + The user account credentials to use to perform this task. -.PARAMETER ForestName - The target Active Directory forest for the change. + .PARAMETER ForestName + The target Active Directory forest for the change. -.PARAMETER ServicePrincipalNameSuffix - The Service Principal Name Suffix(es) to be explicitly defined in the forest and replace existing - members. Cannot be used with ServicePrincipalNameSuffixToAdd or ServicePrincipalNameSuffixToRemove. + .PARAMETER ServicePrincipalNameSuffix + The Service Principal Name Suffix(es) to be explicitly defined in the forest and replace existing + members. Cannot be used with ServicePrincipalNameSuffixToAdd or ServicePrincipalNameSuffixToRemove. -.PARAMETER ServicePrincipalNameSuffixToAdd - The Service Principal Name Suffix(es) to add in the forest. Cannot be used with ServicePrincipalNameSuffix. + .PARAMETER ServicePrincipalNameSuffixToAdd + The Service Principal Name Suffix(es) to add in the forest. Cannot be used with ServicePrincipalNameSuffix. -.PARAMETER ServicePrincipalNameSuffixToRemove - The Service Principal Name Suffix(es) to remove in the forest. Cannot be used with ServicePrincipalNameSuffix. + .PARAMETER ServicePrincipalNameSuffixToRemove + The Service Principal Name Suffix(es) to remove in the forest. Cannot be used with ServicePrincipalNameSuffix. -.PARAMETER UserPrincipalNameSuffix - The User Principal Name Suffix(es) to be explicitly defined in the forest and replace existing - members. Cannot be used with UserPrincipalNameSuffixToAdd or UserPrincipalNameSuffixToRemove. + .PARAMETER UserPrincipalNameSuffix + The User Principal Name Suffix(es) to be explicitly defined in the forest and replace existing + members. Cannot be used with UserPrincipalNameSuffixToAdd or UserPrincipalNameSuffixToRemove. -.PARAMETER UserPrincipalNameSuffixToAdd - The User Principal Name Suffix(es) to add in the forest. Cannot be used with UserPrincipalNameSuffix. + .PARAMETER UserPrincipalNameSuffixToAdd + The User Principal Name Suffix(es) to add in the forest. Cannot be used with UserPrincipalNameSuffix. -.PARAMETER UserPrincipalNameSuffixToRemove - The User Principal Name Suffix(es) to remove in the forest. Cannot be used with UserPrincipalNameSuffix. + .PARAMETER UserPrincipalNameSuffixToRemove + The User Principal Name Suffix(es) to remove in the forest. Cannot be used with UserPrincipalNameSuffix. #> function Get-TargetResource { @@ -90,7 +90,7 @@ function Get-TargetResource Write-Verbose -Message ($script:localizedData.GetForest -f $ForestName) $forest = Get-ADForest -Identity $ForestName - $targetResource = @{ + return @{ Credential = '' ForestName = $forest.Name ServicePrincipalNameSuffix = [Array] $forest.SpnSuffixes @@ -100,39 +100,37 @@ function Get-TargetResource UserPrincipalNameSuffixToAdd = [Array] $UserPrincipalNameSuffixToAdd UserPrincipalNameSuffixToRemove = [Array] $UserPrincipalNameSuffixToRemove } - - return $targetResource } <# -.SYNOPSIS - Tests the current state of user principal name and service principal name suffixes in the forest. + .SYNOPSIS + Tests the current state of user principal name and service principal name suffixes in the forest. -.PARAMETER Credential - The user account credentials to use to perform this task. + .PARAMETER Credential + The user account credentials to use to perform this task. -.PARAMETER ForestName - The target Active Directory forest for the change. + .PARAMETER ForestName + The target Active Directory forest for the change. -.PARAMETER ServicePrincipalNameSuffix - The Service Principal Name Suffix(es) to be explicitly defined in the forest and replace existing - members. Cannot be used with ServicePrincipalNameSuffixToAdd or ServicePrincipalNameSuffixToRemove. + .PARAMETER ServicePrincipalNameSuffix + The Service Principal Name Suffix(es) to be explicitly defined in the forest and replace existing + members. Cannot be used with ServicePrincipalNameSuffixToAdd or ServicePrincipalNameSuffixToRemove. -.PARAMETER ServicePrincipalNameSuffixToAdd - The Service Principal Name Suffix(es) to add in the forest. Cannot be used with ServicePrincipalNameSuffix. + .PARAMETER ServicePrincipalNameSuffixToAdd + The Service Principal Name Suffix(es) to add in the forest. Cannot be used with ServicePrincipalNameSuffix. -.PARAMETER ServicePrincipalNameSuffixToRemove - The Service Principal Name Suffix(es) to remove in the forest. Cannot be used with ServicePrincipalNameSuffix. + .PARAMETER ServicePrincipalNameSuffixToRemove + The Service Principal Name Suffix(es) to remove in the forest. Cannot be used with ServicePrincipalNameSuffix. -.PARAMETER UserPrincipalNameSuffix - The User Principal Name Suffix(es) to be explicitly defined in the forest and replace existing - members. Cannot be used with UserPrincipalNameSuffixToAdd or UserPrincipalNameSuffixToRemove. + .PARAMETER UserPrincipalNameSuffix + The User Principal Name Suffix(es) to be explicitly defined in the forest and replace existing + members. Cannot be used with UserPrincipalNameSuffixToAdd or UserPrincipalNameSuffixToRemove. -.PARAMETER UserPrincipalNameSuffixToAdd - The User Principal Name Suffix(es) to add in the forest. Cannot be used with UserPrincipalNameSuffix. + .PARAMETER UserPrincipalNameSuffixToAdd + The User Principal Name Suffix(es) to add in the forest. Cannot be used with UserPrincipalNameSuffix. -.PARAMETER UserPrincipalNameSuffixToRemove - The User Principal Name Suffix(es) to remove in the forest. Cannot be used with UserPrincipalNameSuffix. + .PARAMETER UserPrincipalNameSuffixToRemove + The User Principal Name Suffix(es) to remove in the forest. Cannot be used with UserPrincipalNameSuffix. #> function Test-TargetResource { @@ -180,16 +178,19 @@ function Test-TargetResource $forest = Get-ADForest -Identity $ForestName - ## Validate parameters before we even attempt to retrieve anything + # Validate parameters before we even attempt to retrieve anything $assertMemberParameters = @{} + if ($PSBoundParameters.ContainsKey('ServicePrincipalNameSuffix') -and -not [system.string]::IsNullOrEmpty($ServicePrincipalNameSuffix)) { $assertMemberParameters['Members'] = $ServicePrincipalNameSuffix } + if ($PSBoundParameters.ContainsKey('ServicePrincipalNameSuffixToAdd') -and -not [system.string]::IsNullOrEmpty($ServicePrincipalNameSuffixToAdd)) { $assertMemberParameters['MembersToInclude'] = $ServicePrincipalNameSuffixToAdd } + if ($PSBoundParameters.ContainsKey('ServicePrincipalNameSuffixToRemove') -and -not [system.string]::IsNullOrEmpty($ServicePrincipalNameSuffixToRemove)) { $assertMemberParameters['MembersToExclude'] = $ServicePrincipalNameSuffixToRemove @@ -204,14 +205,17 @@ function Test-TargetResource } $assertMemberParameters = @{} + if ($PSBoundParameters.ContainsKey('UserPrincipalNameSuffix') -and -not [system.string]::IsNullOrEmpty($UserPrincipalNameSuffix)) { $assertMemberParameters['Members'] = $UserPrincipalNameSuffix } + if ($PSBoundParameters.ContainsKey('UserPrincipalNameSuffixToAdd') -and -not [system.string]::IsNullOrEmpty($UserPrincipalNameSuffixToAdd)) { $assertMemberParameters['MembersToInclude'] = $UserPrincipalNameSuffixToAdd } + if ($PSBoundParameters.ContainsKey('UserPrincipalNameSuffixToRemove') -and -not [system.string]::IsNullOrEmpty($UserPrincipalNameSuffixToRemove)) { $assertMemberParameters['MembersToExclude'] = $UserPrincipalNameSuffixToRemove @@ -229,34 +233,34 @@ function Test-TargetResource } <# -.SYNOPSIS - Sets the user principal name and service principal name suffixes in the forest. + .SYNOPSIS + Sets the user principal name and service principal name suffixes in the forest. -.PARAMETER Credential - The user account credentials to use to perform this task. + .PARAMETER Credential + The user account credentials to use to perform this task. -.PARAMETER ForestName - The target Active Directory forest for the change. + .PARAMETER ForestName + The target Active Directory forest for the change. -.PARAMETER ServicePrincipalNameSuffix - The Service Principal Name Suffix(es) to be explicitly defined in the forest and replace existing - members. Cannot be used with ServicePrincipalNameSuffixToAdd or ServicePrincipalNameSuffixToRemove. + .PARAMETER ServicePrincipalNameSuffix + The Service Principal Name Suffix(es) to be explicitly defined in the forest and replace existing + members. Cannot be used with ServicePrincipalNameSuffixToAdd or ServicePrincipalNameSuffixToRemove. -.PARAMETER ServicePrincipalNameSuffixToAdd - The Service Principal Name Suffix(es) to add in the forest. Cannot be used with ServicePrincipalNameSuffix. + .PARAMETER ServicePrincipalNameSuffixToAdd + The Service Principal Name Suffix(es) to add in the forest. Cannot be used with ServicePrincipalNameSuffix. -.PARAMETER ServicePrincipalNameSuffixToRemove - The Service Principal Name Suffix(es) to remove in the forest. Cannot be used with ServicePrincipalNameSuffix. + .PARAMETER ServicePrincipalNameSuffixToRemove + The Service Principal Name Suffix(es) to remove in the forest. Cannot be used with ServicePrincipalNameSuffix. -.PARAMETER UserPrincipalNameSuffix - The User Principal Name Suffix(es) to be explicitly defined in the forest and replace existing - members. Cannot be used with UserPrincipalNameSuffixToAdd or UserPrincipalNameSuffixToRemove. + .PARAMETER UserPrincipalNameSuffix + The User Principal Name Suffix(es) to be explicitly defined in the forest and replace existing + members. Cannot be used with UserPrincipalNameSuffixToAdd or UserPrincipalNameSuffixToRemove. -.PARAMETER UserPrincipalNameSuffixToAdd - The User Principal Name Suffix(es) to add in the forest. Cannot be used with UserPrincipalNameSuffix. + .PARAMETER UserPrincipalNameSuffixToAdd + The User Principal Name Suffix(es) to add in the forest. Cannot be used with UserPrincipalNameSuffix. -.PARAMETER UserPrincipalNameSuffixToRemove - The User Principal Name Suffix(es) to remove in the forest. Cannot be used with UserPrincipalNameSuffix. + .PARAMETER UserPrincipalNameSuffixToRemove + The User Principal Name Suffix(es) to remove in the forest. Cannot be used with UserPrincipalNameSuffix. #> function Set-TargetResource { @@ -318,6 +322,7 @@ function Set-TargetResource Write-Verbose -Message ($script:localizedData.ReplaceSpnSuffix -f $replaceServicePrincipalNameSuffix) } + if ($PSBoundParameters.ContainsKey('ServicePrincipalNameSuffixToAdd') -and -not [system.string]::IsNullOrEmpty($ServicePrincipalNameSuffixToAdd)) { $addServicePrincipalNameSuffix = $ServicePrincipalNameSuffixToAdd -join ',' @@ -327,9 +332,11 @@ function Set-TargetResource Write-Verbose -Message ($script:localizedData.AddSpnSuffix -f $addServicePrincipalNameSuffix) } + if ($PSBoundParameters.ContainsKey('ServicePrincipalNameSuffixToRemove') -and -not [system.string]::IsNullOrEmpty($ServicePrincipalNameSuffixToRemove)) { $removeServicePrincipalNameSuffix = $ServicePrincipalNameSuffixToRemove -join ',' + if ($setADForestParameters['SpnSuffixes']) { $setADForestParameters['SpnSuffixes']['remove'] = $($ServicePrincipalNameSuffixToRemove) @@ -348,24 +355,29 @@ function Set-TargetResource if ($PSBoundParameters.ContainsKey('UserPrincipalNameSuffix') -and -not [system.string]::IsNullOrEmpty($UserPrincipalNameSuffix)) { $replaceUserPrincipalNameSuffix = $UserPrincipalNameSuffix -join ',' + $setADForestParameters['UpnSuffixes'] = @{ replace = $($UserPrincipalNameSuffix) } Write-Verbose -Message ($script:localizedData.ReplaceUpnSuffix -f $replaceUserPrincipalNameSuffix) } + if ($PSBoundParameters.ContainsKey('UserPrincipalNameSuffixToAdd') -and -not [system.string]::IsNullOrEmpty($UserPrincipalNameSuffixToAdd)) { $addUserPrincipalNameSuffix = $UserPrincipalNameSuffixToAdd -join ',' + $setADForestParameters['UpnSuffixes'] = @{ add = $($UserPrincipalNameSuffixToAdd) } Write-Verbose -Message ($script:localizedData.AddUpnSuffix -f $addUserPrincipalNameSuffix) } + if ($PSBoundParameters.ContainsKey('UserPrincipalNameSuffixToRemove') -and -not [system.string]::IsNullOrEmpty($UserPrincipalNameSuffixToRemove)) { $removeUserPrincipalNameSuffix = $UserPrincipalNameSuffixToRemove -join ',' + if ($setADForestParameters['UpnSuffixes']) { $setADForestParameters['UpnSuffixes']['remove'] = $($UserPrincipalNameSuffixToRemove) From 9e9bcaccbee2c8d00244e9eaeabb0a8e9d5fb922 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 11:32:52 +0200 Subject: [PATCH 10/29] Changes to xADGroup - Minor style cleanup. --- CHANGELOG.md | 20 ++-- DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 | 98 ++++++++++++++++--- 2 files changed, 91 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbbbe5162..f37537532 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,8 +57,11 @@ - Fix unnecessary cast in `Test-TargetResource` ([Issue #295](https://github.com/PowerShell/xActiveDirectory/issues/295)) - Changes to xADGroup - Change the description of the property RestoreFromRecycleBin. + - Cleanup of code. - Changes to xADObjectPermissionEntry - Change the description of the property IdentityReference. + - Fix failure when applied in the same configuration as xADDomain + - Localize and Improve verbose messaging - Changes to xADOrganizationalUnit - Change the description of the property RestoreFromRecycleBin. - Changes to xADUser @@ -82,30 +85,23 @@ - Suppressing the Script Analyzer rule `PSAvoidGlobalVars` since the resource is using the `$global:DSCMachineStatus` variable to trigger a reboot. -- Changes to xADObjectPermissionEntry - - Fix failure when applied in the same configuration as xADDomain - - Localize and Improve verbose messaging + - Added missing property schema descriptions ([issue #369](https://github.com/PowerShell/xActiveDirectory/issues/369)). - Changes to xADRecycleBin - Remove unneeded example and resource designer files. - Added missing property schema descriptions ([issue #368](https://github.com/PowerShell/xActiveDirectory/issues/368)). + - Cleanup of code. + - It now set back the `$ErrorActionPreference` that was set prior to + setting it to `'Stop'`. - Changes to xADReplicationSiteLink - - Fix ADIdentityNotFoundException When Creating a New Site Link. + - Fix ADIdentityNotFoundException when creating a new site link. - Changes to xADReplicationSubnet - Remove `{ *Present* | Absent }` from the property schema descriptions which were causing corruption in the Wiki documentation. - Changes to xADServicePrincipalNames - Remove `{ *Present* | Absent }` from the property schema descriptions which were causing corruption in the Wiki documentation. -- Changes to xWaitForADDomain - - Added missing property schema descriptions ([issue #369](https://github.com/PowerShell/xActiveDirectory/issues/369)). -- Changes to xADRecycleBin - - Cleanup of code. - - It now set back the `$ErrorActionPreference` that was set prior to - setting it to `'Stop'`. - Changes to xADDomainDefaultPasswordPolicy - Cleanup of code. -- Changes to xADDomainTrust - - Cleanup of code. - Changes to xADForestProperties - Minor style cleanup. diff --git a/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 b/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 index 2f9fab407..2274048b3 100644 --- a/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 +++ b/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 @@ -91,14 +91,20 @@ function Get-TargetResource [System.Boolean] $RestoreFromRecycleBin ) + Assert-Module -ModuleName 'ActiveDirectory' + $adGroupParams = Get-ADCommonParameters @PSBoundParameters + try { $adGroup = Get-ADGroup @adGroupParams -Property Name,GroupScope,GroupCategory,DistinguishedName,Description,DisplayName,ManagedBy,Info + Write-Verbose -Message ($script:localizedData.RetrievingGroupMembers -f $MembershipAttribute) + # Retrieve the current list of members, returning the specified membership attribute [System.Array]$adGroupMembers = (Get-ADGroupMember @adGroupParams).$MembershipAttribute + $targetResource = @{ GroupName = $adGroup.Name GroupScope = $adGroup.GroupScope @@ -114,6 +120,7 @@ function Get-TargetResource Notes = $adGroup.Info Ensure = 'Absent' } + if ($adGroup) { $targetResource['Ensure'] = 'Present' @@ -122,6 +129,7 @@ function Get-TargetResource catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { Write-Verbose -Message ($script:localizedData.GroupNotFound -f $GroupName) + $targetResource = @{ GroupName = $GroupName GroupScope = $GroupScope @@ -138,6 +146,7 @@ function Get-TargetResource Ensure = 'Absent' } } + return $targetResource } #end function Get-TargetResource @@ -225,70 +234,86 @@ function Test-TargetResource [System.Boolean] $RestoreFromRecycleBin ) + # Validate parameters before we even attempt to retrieve anything $assertMemberParameters = @{} + if ($PSBoundParameters.ContainsKey('Members') -and -not [system.string]::IsNullOrEmpty($Members)) { $assertMemberParameters['Members'] = $Members } + if ($PSBoundParameters.ContainsKey('MembersToInclude') -and -not [system.string]::IsNullOrEmpty($MembersToInclude)) { $assertMemberParameters['MembersToInclude'] = $MembersToInclude } + if ($PSBoundParameters.ContainsKey('MembersToExclude') -and -not [system.string]::IsNullOrEmpty($MembersToExclude)) { $assertMemberParameters['MembersToExclude'] = $MembersToExclude } + Assert-MemberParameters @assertMemberParameters -ModuleName 'xADDomain' -ErrorAction Stop $targetResource = Get-TargetResource @PSBoundParameters + $targetResourceInCompliance = $true + if ($PSBoundParameters.ContainsKey('GroupScope') -and $targetResource.GroupScope -ne $GroupScope) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f 'GroupScope', $GroupScope, $targetResource.GroupScope) $targetResourceInCompliance = $false } + if ($PSBoundParameters.ContainsKey('Category') -and $targetResource.Category -ne $Category) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f 'Category', $Category, $targetResource.Category) $targetResourceInCompliance = $false } + if ($Path -and ($targetResource.Path -ne $Path)) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f 'Path', $Path, $targetResource.Path) $targetResourceInCompliance = $false } + if ($Description -and ($targetResource.Description -ne $Description)) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f 'Description', $Description, $targetResource.Description) $targetResourceInCompliance = $false } + if ($DisplayName -and ($targetResource.DisplayName -ne $DisplayName)) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f 'DisplayName', $DisplayName, $targetResource.DisplayName) $targetResourceInCompliance = $false } + if ($ManagedBy -and ($targetResource.ManagedBy -ne $ManagedBy)) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f 'ManagedBy', $ManagedBy, $targetResource.ManagedBy) $targetResourceInCompliance = $false } + if ($Notes -and ($targetResource.Notes -ne $Notes)) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f 'Notes', $Notes, $targetResource.Notes) $targetResourceInCompliance = $false } + # Test group members match passed membership parameters if (-not (Test-Members @assertMemberParameters -ExistingMembers $targetResource.Members)) { Write-Verbose -Message $script:localizedData.GroupMembershipNotDesiredState $targetResourceInCompliance = $false } + if ($targetResource.Ensure -ne $Ensure) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f 'Ensure', $Ensure, $targetResource.Ensure) $targetResourceInCompliance = $false } + return $targetResourceInCompliance } #end function Test-TargetResource @@ -377,21 +402,27 @@ function Set-TargetResource $RestoreFromRecycleBin ) + Assert-Module -ModuleName 'ActiveDirectory' + $adGroupParams = Get-ADCommonParameters @PSBoundParameters try { if ($MembershipAttribute -eq 'DistinguishedName') { - $AllMembers = $Members + $MembersToInclude + $MembersToExclude - $GroupMemberDomains = @() - foreach($member in $AllMembers) + $allMembers = $Members + $MembersToInclude + $MembersToExclude + + $groupMemberDomains = @() + + foreach ($member in $allMembers) { - $GroupMemberDomains += Get-ADDomainNameFromDistinguishedName -DistinguishedName $member + $groupMemberDomains += Get-ADDomainNameFromDistinguishedName -DistinguishedName $member } - $GroupMemberDomainCount = ($GroupMemberDomains | Select-Object -Unique).count - if( $GroupMemberDomainCount -gt 1 -or ($GroupMemberDomains -ine (Get-DomainName)).Count -gt 0 ) + + $GroupMemberDomainCount = ($groupMemberDomains | Select-Object -Unique).count + + if ($GroupMemberDomainCount -gt 1 -or ($groupMemberDomains -ine (Get-DomainName)).Count -gt 0) { Write-Verbose -Message ($script:localizedData.GroupMembershipMultipleDomains -f $GroupMemberDomainCount) $MembersInMultipleDomains = $true @@ -411,6 +442,7 @@ function Set-TargetResource Write-Verbose -Message ($script:localizedData.UpdatingGroupProperty -f 'Category', $Category) $setADGroupParams['GroupCategory'] = $Category } + if ($PSBoundParameters.ContainsKey('GroupScope') -and $GroupScope -ne $adGroup.GroupScope) { # Cannot change DomainLocal to Global or vice versa directly. Need to change them to a Universal group first! @@ -418,67 +450,90 @@ function Set-TargetResource Write-Verbose -Message ($script:localizedData.UpdatingGroupProperty -f 'GroupScope', $GroupScope) $setADGroupParams['GroupScope'] = $GroupScope } + if ($Description -and ($Description -ne $adGroup.Description)) { Write-Verbose -Message ($script:localizedData.UpdatingGroupProperty -f 'Description', $Description) $setADGroupParams['Description'] = $Description } + if ($DisplayName -and ($DisplayName -ne $adGroup.DisplayName)) { Write-Verbose -Message ($script:localizedData.UpdatingGroupProperty -f 'DisplayName', $DisplayName) $setADGroupParams['DisplayName'] = $DisplayName } + if ($ManagedBy -and ($ManagedBy -ne $adGroup.ManagedBy)) { Write-Verbose -Message ($script:localizedData.UpdatingGroupProperty -f 'ManagedBy', $ManagedBy) $setADGroupParams['ManagedBy'] = $ManagedBy } + if ($Notes -and ($Notes -ne $adGroup.Info)) { Write-Verbose -Message ($script:localizedData.UpdatingGroupProperty -f 'Notes', $Notes) $setADGroupParams['Replace'] = @{ Info = $Notes } } + Write-Verbose -Message ($script:localizedData.UpdatingGroup -f $GroupName) + Set-ADGroup @setADGroupParams # Move group if the path is not correct if ($Path -and ($Path -ne (Get-ADObjectParentDN -DN $adGroup.DistinguishedName))) { Write-Verbose -Message ($script:localizedData.MovingGroup -f $GroupName, $Path) + $moveADObjectParams = $adGroupParams.Clone() $moveADObjectParams['Identity'] = $adGroup.DistinguishedName + Move-ADObject @moveADObjectParams -TargetPath $Path } Write-Verbose -Message ($script:localizedData.RetrievingGroupMembers -f $MembershipAttribute) + $adGroupMembers = (Get-ADGroupMember @adGroupParams).$MembershipAttribute + if (-not (Test-Members -ExistingMembers $adGroupMembers -Members $Members -MembersToInclude $MembersToInclude -MembersToExclude $MembersToExclude)) { - # The fact that we're in the Set method, there is no need to validate the parameter - # combination as this was performed in the Test method + <# + The fact that we're in the Set method, there is no need to + validate the parameter combination as this was performed in + the Test method. + #> if ($PSBoundParameters.ContainsKey('Members') -and -not [system.string]::IsNullOrEmpty($Members)) { # Remove all existing first and add explicit members $Members = Remove-DuplicateMembers -Members $Members + # We can only remove members if there are members already in the group! if ($adGroupMembers.Count -gt 0) { Write-Verbose -Message ($script:localizedData.RemovingGroupMembers -f $adGroupMembers.Count, $GroupName) + Remove-ADGroupMember @adGroupParams -Members $adGroupMembers -Confirm:$false } + Write-Verbose -Message ($script:localizedData.AddingGroupMembers -f $Members.Count, $GroupName) + Add-ADCommonGroupMember -Parameter $adGroupParams -Members $Members -MembersInMultipleDomains:$MembersInMultipleDomains } + if ($PSBoundParameters.ContainsKey('MembersToInclude') -and -not [system.string]::IsNullOrEmpty($MembersToInclude)) { $MembersToInclude = Remove-DuplicateMembers -Members $MembersToInclude + Write-Verbose -Message ($script:localizedData.AddingGroupMembers -f $MembersToInclude.Count, $GroupName) + Add-ADCommonGroupMember -Parameter $adGroupParams -Members $MembersToInclude -MembersInMultipleDomains:$MembersInMultipleDomains } + if ($PSBoundParameters.ContainsKey('MembersToExclude') -and -not [system.string]::IsNullOrEmpty($MembersToExclude)) { $MembersToExclude = Remove-DuplicateMembers -Members $MembersToExclude + Write-Verbose -Message ($script:localizedData.RemovingGroupMembers -f $MembersToExclude.Count, $GroupName) + Remove-ADGroupMember @adGroupParams -Members $MembersToExclude -Confirm:$false } } @@ -487,6 +542,7 @@ function Set-TargetResource { # Remove existing group Write-Verbose -Message ($script:localizedData.RemovingGroup -f $GroupName) + Remove-ADGroup @adGroupParams -Confirm:$false } } @@ -498,50 +554,58 @@ function Set-TargetResource Write-Verbose -Message ($script:localizedData.GroupNotFound -f $GroupName) $adGroupParams = Get-ADCommonParameters @PSBoundParameters -UseNameParameter + if ($Description) { $adGroupParams['Description'] = $Description } + if ($DisplayName) { $adGroupParams['DisplayName'] = $DisplayName } + if ($ManagedBy) { $adGroupParams['ManagedBy'] = $ManagedBy } + if ($Path) { $adGroupParams['Path'] = $Path } - <# - Create group - Try to restore account first if it exists - #> - if($RestoreFromRecycleBin) + # Create group. Try to restore account first if it exists. + if ($RestoreFromRecycleBin) { Write-Verbose -Message ($script:localizedData.RestoringGroup -f $GroupName) + $restoreParams = Get-ADCommonParameters @PSBoundParameters + $adGroup = Restore-ADCommonObject @restoreParams -ObjectClass Group -ErrorAction Stop } if (-not $adGroup) { Write-Verbose -Message ($script:localizedData.AddingGroup -f $GroupName) + $adGroup = New-ADGroup @adGroupParams -GroupCategory $Category -GroupScope $GroupScope -PassThru } - # Only the New-ADGroup cmdlet takes a -Name parameter. Refresh - # the parameters with the -Identity parameter rather than -Name + <# + Only the New-ADGroup cmdlet takes a -Name parameter. Refresh + the parameters with the -Identity parameter rather than -Name. + #> $adGroupParams = Get-ADCommonParameters @PSBoundParameters if ($Notes) { # Can't set the Notes field when creating the group Write-Verbose -Message ($script:localizedData.UpdatingGroupProperty -f 'Notes', $Notes) + $setADGroupParams = $adGroupParams.Clone() $setADGroupParams['Identity'] = $adGroup.DistinguishedName + Set-ADGroup @setADGroupParams -Add @{ Info = $Notes } } @@ -549,13 +613,17 @@ function Set-TargetResource if ($PSBoundParameters.ContainsKey('Members') -and -not [system.string]::IsNullOrEmpty($Members)) { $Members = Remove-DuplicateMembers -Members $Members + Write-Verbose -Message ($script:localizedData.AddingGroupMembers -f $Members.Count, $GroupName) + Add-ADCommonGroupMember -Parameter $adGroupParams -Members $Members -MembersInMultipleDomains:$MembersInMultipleDomains } elseif ($PSBoundParameters.ContainsKey('MembersToInclude') -and -not [system.string]::IsNullOrEmpty($MembersToInclude)) { $MembersToInclude = Remove-DuplicateMembers -Members $MembersToInclude + Write-Verbose -Message ($script:localizedData.AddingGroupMembers -f $MembersToInclude.Count, $GroupName) + Add-ADCommonGroupMember -Parameter $adGroupParams -Members $MembersToInclude -MembersInMultipleDomains:$MembersInMultipleDomains } From 8560659652e05493479d0910721ea50682169f42 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 11:39:18 +0200 Subject: [PATCH 11/29] Changes to xADOrganizationalUnit - Code cleanup. --- CHANGELOG.md | 12 ++- .../MSFT_xADOrganizationalUnit.psm1 | 93 +++++++++++++------ 2 files changed, 71 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f37537532..dfcb36272 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ - Fix unnecessary cast in `Test-TargetResource` ([Issue #295](https://github.com/PowerShell/xActiveDirectory/issues/295)) - Changes to xADGroup - Change the description of the property RestoreFromRecycleBin. - - Cleanup of code. + - Code cleanup. - Changes to xADObjectPermissionEntry - Change the description of the property IdentityReference. - Fix failure when applied in the same configuration as xADDomain @@ -80,7 +80,7 @@ a reboot. - Changes to xADDomainTrust - Replaced New-TerminatingError with Standard Function. - - Cleanup of code. + - Code cleanup. - Changes to xWaitForADDomain - Suppressing the Script Analyzer rule `PSAvoidGlobalVars` since the resource is using the `$global:DSCMachineStatus` variable to trigger @@ -89,7 +89,7 @@ - Changes to xADRecycleBin - Remove unneeded example and resource designer files. - Added missing property schema descriptions ([issue #368](https://github.com/PowerShell/xActiveDirectory/issues/368)). - - Cleanup of code. + - Code cleanup. - It now set back the `$ErrorActionPreference` that was set prior to setting it to `'Stop'`. - Changes to xADReplicationSiteLink @@ -101,9 +101,13 @@ - Remove `{ *Present* | Absent }` from the property schema descriptions which were causing corruption in the Wiki documentation. - Changes to xADDomainDefaultPasswordPolicy - - Cleanup of code. + - Code cleanup. +- Changes to xADDomainTrust + - Code cleanup. - Changes to xADForestProperties - Minor style cleanup. +- Changes to xADOrganizationalUnit + - Code cleanup. ## 2.26.0.0 diff --git a/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 b/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 index 06a8d7d48..38d5f67cd 100644 --- a/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 +++ b/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 @@ -13,25 +13,36 @@ function Get-TargetResource param ( [Parameter(Mandatory = $true)] - [System.String] $Name, + [System.String] + $Name, [Parameter(Mandatory = $true)] - [System.String] $Path + [System.String] + $Path ) Assert-Module -ModuleName 'ActiveDirectory' + Write-Verbose ($script:localizedData.RetrievingOU -f $Name) + $ou = Get-ADOrganizationalUnit -Filter { Name -eq $Name } -SearchBase $Path -SearchScope OneLevel -Properties ProtectedFromAccidentalDeletion, Description - $targetResource = @{ - Name = $Name - Path = $Path - Ensure = if ($null -eq $ou) { 'Absent' } else { 'Present' } - ProtectedFromAccidentalDeletion = $ou.ProtectedFromAccidentalDeletion - Description = $ou.Description + if ($null -eq $ou) + { + $ensureState = 'Absent' + } + else + { + $ensureState = 'Present' } - return $targetResource + return @{ + Name = $Name + Path = $Path + Ensure = $ensureState + ProtectedFromAccidentalDeletion = $ou.ProtectedFromAccidentalDeletion + Description = $ou.Description + } } # end function Get-TargetResource function Test-TargetResource @@ -41,10 +52,12 @@ function Test-TargetResource param ( [Parameter(Mandatory = $true)] - [System.String] $Name, + [System.String] + $Name, [Parameter(Mandatory = $true)] - [System.String] $Path, + [System.String] + $Path, [Parameter()] [ValidateSet('Present', 'Absent')] @@ -59,11 +72,13 @@ function Test-TargetResource [Parameter()] [ValidateNotNull()] - [System.Boolean] $ProtectedFromAccidentalDeletion = $true, + [System.Boolean] + $ProtectedFromAccidentalDeletion = $true, [Parameter()] [ValidateNotNull()] - [System.String] $Description = '', + [System.String] + $Description = '', [Parameter()] [ValidateNotNull()] @@ -81,15 +96,15 @@ function Test-TargetResource if ([System.String]::IsNullOrEmpty($Description)) { $isCompliant = (($targetResource.Name -eq $Name) -and - ($targetResource.Path -eq $Path) -and - ($targetResource.ProtectedFromAccidentalDeletion -eq $ProtectedFromAccidentalDeletion)) + ($targetResource.Path -eq $Path) -and + ($targetResource.ProtectedFromAccidentalDeletion -eq $ProtectedFromAccidentalDeletion)) } else { $isCompliant = (($targetResource.Name -eq $Name) -and - ($targetResource.Path -eq $Path) -and - ($targetResource.ProtectedFromAccidentalDeletion -eq $ProtectedFromAccidentalDeletion) -and - ($targetResource.Description -eq $Description)) + ($targetResource.Path -eq $Path) -and + ($targetResource.ProtectedFromAccidentalDeletion -eq $ProtectedFromAccidentalDeletion) -and + ($targetResource.Description -eq $Description)) } if ($isCompliant) @@ -132,10 +147,12 @@ function Set-TargetResource param ( [Parameter(Mandatory = $true)] - [System.String] $Name, + [System.String] + $Name, [Parameter(Mandatory = $true)] - [System.String] $Path, + [System.String] + $Path, [Parameter()] [ValidateSet('Present', 'Absent')] @@ -150,11 +167,13 @@ function Set-TargetResource [Parameter()] [ValidateNotNull()] - [System.Boolean] $ProtectedFromAccidentalDeletion = $true, + [System.Boolean] + $ProtectedFromAccidentalDeletion = $true, [Parameter()] [ValidateNotNull()] - [System.String] $Description = '', + [System.String] + $Description = '', [Parameter()] [ValidateNotNull()] @@ -163,58 +182,69 @@ function Set-TargetResource ) Assert-Module -ModuleName 'ActiveDirectory' + $targetResource = Get-TargetResource -Name $Name -Path $Path if ($targetResource.Ensure -eq 'Present') { $ou = Get-ADOrganizationalUnit -Filter { Name -eq $Name } -SearchBase $Path -SearchScope OneLevel + if ($Ensure -eq 'Present') { Write-Verbose ($script:localizedData.UpdatingOU -f $targetResource.Name) + $setADOrganizationalUnitParams = @{ - Identity = $ou - Description = $Description + Identity = $ou + Description = $Description ProtectedFromAccidentalDeletion = $ProtectedFromAccidentalDeletion } + if ($Credential) { $setADOrganizationalUnitParams['Credential'] = $Credential } + Set-ADOrganizationalUnit @setADOrganizationalUnitParams } else { Write-Verbose ($script:localizedData.DeletingOU -f $targetResource.Name) + if ($targetResource.ProtectedFromAccidentalDeletion) { $setADOrganizationalUnitParams = @{ - Identity = $ou + Identity = $ou ProtectedFromAccidentalDeletion = $ProtectedFromAccidentalDeletion } + if ($Credential) { $setADOrganizationalUnitParams['Credential'] = $Credential } + Set-ADOrganizationalUnit @setADOrganizationalUnitParams } $removeADOrganizationalUnitParams = @{ Identity = $ou } + if ($Credential) { $removeADOrganizationalUnitParams['Credential'] = $Credential } + Remove-ADOrganizationalUnit @removeADOrganizationalUnitParams } - return # return from Set method to make it easier to test for a succesful restore + return # return from Set method to make it easier to test for a successful restore } else { - if ($RestoreFromRecycleBin) + if ($RestoreFromRecycleBin) { Write-Verbose -Message ($script:localizedData.RestoringOu -f $Name) + $restoreParams = @{ Identity = $Name ObjectClass = 'OrganizationalUnit' @@ -232,16 +262,19 @@ function Set-TargetResource if (-not $RestoreFromRecycleBin -or ($RestoreFromRecycleBin -and -not $restoreSuccessful)) { Write-Verbose ($script:localizedData.CreatingOU -f $targetResource.Name) + $newADOrganizationalUnitParams = @{ - Name = $Name - Path = $Path - Description = $Description + Name = $Name + Path = $Path + Description = $Description ProtectedFromAccidentalDeletion = $ProtectedFromAccidentalDeletion } + if ($Credential) { $newADOrganizationalUnitParams['Credential'] = $Credential } + New-ADOrganizationalUnit @newADOrganizationalUnitParams } } From a4d033a9ca6ff36bf07100e4a8ac651693ff465e Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 11:55:02 +0200 Subject: [PATCH 12/29] Changes to xADUser - Code cleanup. --- CHANGELOG.md | 1 + DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 | 242 +++++++++++++++----- 2 files changed, 191 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dfcb36272..197df831b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,7 @@ - Change the description of the property RestoreFromRecycleBin. - Added ServicePrincipalNames property ([issue #153](https://github.com/PowerShell/xActiveDirectory/issues/153)). - Added ChangePasswordAtLogon property ([issue #246](https://github.com/PowerShell/xActiveDirectory/issues/246)). + - Code cleanup. - Changes to xADDomainController - Change the `#Requires` statement in the Examples to require the correct module. diff --git a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 index dedbc6890..6f619b700 100644 --- a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 +++ b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 @@ -13,47 +13,148 @@ $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_xADUser' # Create a property map that maps the DSC resource parameters to the # Active Directory user attributes. $adPropertyMap = @( - @{ Parameter = 'CommonName'; ADProperty = 'cn'; } - @{ Parameter = 'UserPrincipalName'; } - @{ Parameter = 'DisplayName'; } - @{ Parameter = 'Path'; ADProperty = 'distinguishedName'; } - @{ Parameter = 'GivenName'; } - @{ Parameter = 'Initials'; } - @{ Parameter = 'Surname'; ADProperty = 'sn'; } - @{ Parameter = 'Description'; } - @{ Parameter = 'StreetAddress'; } - @{ Parameter = 'POBox'; } - @{ Parameter = 'City'; ADProperty = 'l'; } - @{ Parameter = 'State'; ADProperty = 'st'; } - @{ Parameter = 'PostalCode'; } - @{ Parameter = 'Country'; ADProperty = 'c'; } - @{ Parameter = 'Department'; } - @{ Parameter = 'Division'; } - @{ Parameter = 'Company'; } - @{ Parameter = 'Office'; ADProperty = 'physicalDeliveryOfficeName'; } - @{ Parameter = 'JobTitle'; ADProperty = 'title'; } - @{ Parameter = 'EmailAddress'; ADProperty = 'mail'; } - @{ Parameter = 'EmployeeID'; } - @{ Parameter = 'EmployeeNumber'; } - @{ Parameter = 'HomeDirectory'; } - @{ Parameter = 'HomeDrive'; } - @{ Parameter = 'HomePage'; ADProperty = 'wWWHomePage'; } - @{ Parameter = 'ProfilePath'; } - @{ Parameter = 'LogonScript'; ADProperty = 'scriptPath'; } - @{ Parameter = 'Notes'; ADProperty = 'info'; } - @{ Parameter = 'OfficePhone'; ADProperty = 'telephoneNumber'; } - @{ Parameter = 'MobilePhone'; ADProperty = 'mobile'; } - @{ Parameter = 'Fax'; ADProperty = 'facsimileTelephoneNumber'; } - @{ Parameter = 'Pager'; } - @{ Parameter = 'IPPhone'; } - @{ Parameter = 'HomePhone'; } - @{ Parameter = 'Enabled'; } - @{ Parameter = 'Manager'; } - @{ Parameter = 'PasswordNeverExpires'; UseCmdletParameter = $true; } - @{ Parameter = 'CannotChangePassword'; UseCmdletParameter = $true; } - @{ Parameter = 'ChangePasswordAtLogon'; UseCmdletParameter = $true; } - @{ Parameter = 'TrustedForDelegation'; UseCmdletParameter = $true; } - @{ Parameter = 'ServicePrincipalNames'; } + @{ + Parameter = 'CommonName' + ADProperty = 'cn' + } + @{ + Parameter = 'UserPrincipalName' + } + @{ + Parameter = 'DisplayName' + } + @{ + Parameter = 'Path' + ADProperty = 'distinguishedName' + } + @{ + Parameter = 'GivenName' + } + @{ + Parameter = 'Initials' + } + @{ + Parameter = 'Surname' + ADProperty = 'sn' + } + @{ + Parameter = 'Description' + } + @{ + Parameter = 'StreetAddress' + } + @{ + Parameter = 'POBox' + } + @{ + Parameter = 'City' + ADProperty = 'l' + } + @{ + Parameter = 'State' + ADProperty = 'st' + } + @{ + Parameter = 'PostalCode' + } + @{ + Parameter = 'Country' + ADProperty = 'c' + } + @{ + Parameter = 'Department' + } + @{ + Parameter = 'Division' + } + @{ + Parameter = 'Company' + } + @{ + Parameter = 'Office' + ADProperty = 'physicalDeliveryOfficeName' + } + @{ + Parameter = 'JobTitle' + ADProperty = 'title' + } + @{ + Parameter = 'EmailAddress' + ADProperty = 'mail' + } + @{ + Parameter = 'EmployeeID' + } + @{ + Parameter = 'EmployeeNumber' + } + @{ + Parameter = 'HomeDirectory' + } + @{ + Parameter = 'HomeDrive' + } + @{ + Parameter = 'HomePage' + ADProperty = 'wWWHomePage' + } + @{ + Parameter = 'ProfilePath' + } + @{ + Parameter = 'LogonScript' + ADProperty = 'scriptPath' + } + @{ + Parameter = 'Notes' + ADProperty = 'info' + } + @{ + Parameter = 'OfficePhone' + ADProperty = 'telephoneNumber' + } + @{ + Parameter = 'MobilePhone' + ADProperty = 'mobile' + } + @{ + Parameter = 'Fax' + ADProperty = 'facsimileTelephoneNumber' + } + @{ + Parameter = 'Pager' + } + @{ + Parameter = 'IPPhone' + } + @{ + Parameter = 'HomePhone' + } + @{ + Parameter = 'Enabled' + } + @{ + Parameter = 'Manager' + } + @{ + Parameter = 'PasswordNeverExpires' + UseCmdletParameter = $true + } + @{ + Parameter = 'CannotChangePassword' + UseCmdletParameter = $true + } + @{ + Parameter = 'ChangePasswordAtLogon' + UseCmdletParameter = $true + } + @{ + Parameter = 'TrustedForDelegation' + UseCmdletParameter = $true + } + @{ + Parameter = 'ServicePrincipalNames' + } ) function Get-TargetResource @@ -85,7 +186,7 @@ function Get-TargetResource [System.String] $Ensure = 'Present', - # Specifies the common nane assigned to the user account (ldapDisplayName 'cn') + # Specifies the common name assigned to the user account (ldapDisplayName 'cn') [Parameter()] [ValidateNotNull()] [System.String] @@ -247,7 +348,7 @@ function Get-TargetResource [System.String] $LogonScript, - # Specifies the notes attached to the user's accoutn (ldapDisplayName 'info') + # Specifies the notes attached to the user's account (ldapDisplayName 'info') [Parameter()] [ValidateNotNull()] [System.String] @@ -370,6 +471,7 @@ function Get-TargetResource $adCommonParameters = Get-ADCommonParameters @PSBoundParameters $adProperties = @() + # Create an array of the AD propertie names to retrieve from the property map foreach ($property in $adPropertyMap) { @@ -384,13 +486,17 @@ function Get-TargetResource } Write-Verbose -Message ($script:localizedData.RetrievingADUser -f $UserName, $DomainName) + $adUser = Get-ADUser @adCommonParameters -Properties $adProperties + Write-Verbose -Message ($script:localizedData.ADUserIsPresent -f $UserName, $DomainName) + $Ensure = 'Present' } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { Write-Verbose -Message ($script:localizedData.ADUserNotPresent -f $UserName, $DomainName) + $Ensure = 'Absent' } catch @@ -442,8 +548,8 @@ function Get-TargetResource $targetResource[$property.Parameter] = $adUser.($property.Parameter) } } - return $targetResource + return $targetResource } #end function Get-TargetResource function Test-TargetResource @@ -475,7 +581,7 @@ function Test-TargetResource [System.String] $Ensure = 'Present', - # Specifies the common nane assigned to the user account (ldapDisplayName 'cn') + # Specifies the common name assigned to the user account (ldapDisplayName 'cn') [Parameter()] [ValidateNotNull()] [System.String] @@ -637,7 +743,7 @@ function Test-TargetResource [System.String] $LogonScript, - # Specifies the notes attached to the user's accoutn (ldapDisplayName 'info') + # Specifies the notes attached to the user's account (ldapDisplayName 'info') [Parameter()] [ValidateNotNull()] [System.String] @@ -754,7 +860,9 @@ function Test-TargetResource ) Assert-Parameters @PSBoundParameters + $targetResource = Get-TargetResource @PSBoundParameters + $isCompliant = $true if ($Ensure -eq 'Absent') @@ -781,10 +889,12 @@ function Test-TargetResource DomainName = $DomainName PasswordAuthentication = $PasswordAuthentication } + if ($DomainAdministratorCredential) { $testPasswordParams['DomainAdministratorCredential'] = $DomainAdministratorCredential } + if (-not (Test-Password @testPasswordParams)) { Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f 'Password', '', '') @@ -805,12 +915,15 @@ function Test-TargetResource ExistingMembers = $targetResource.ServicePrincipalNames -as [System.String[]] Members = $ServicePrincipalNames } + if (-not (Test-Members @testMembersParams)) { $existingSPNs = $testMembersParams['ExistingMembers'] -join ',' $desiredSPNs = $ServicePrincipalNames -join ',' + Write-Verbose -Message ($script:localizedData.ADUserNotDesiredPropertyState -f ` 'ServicePrincipalNames', $desiredSPNs, $existingSPNs) + $isCompliant = $false } } @@ -824,7 +937,6 @@ function Test-TargetResource } return $isCompliant - } #end function Test-TargetResource function Set-TargetResource @@ -855,7 +967,7 @@ function Set-TargetResource [System.String] $Ensure = 'Present', - # Specifies the common nane assigned to the user account (ldapDisplayName 'cn') + # Specifies the common name assigned to the user account (ldapDisplayName 'cn') [Parameter()] [ValidateNotNull()] [System.String] @@ -1017,7 +1129,7 @@ function Set-TargetResource [System.String] $LogonScript, - # Specifies the notes attached to the user's accoutn (ldapDisplayName 'info') + # Specifies the notes attached to the user's account (ldapDisplayName 'info') [Parameter()] [ValidateNotNull()] [System.String] @@ -1134,6 +1246,7 @@ function Set-TargetResource ) Assert-Parameters @PSBoundParameters + $targetResource = Get-TargetResource @PSBoundParameters # Add common name, ensure and enabled as they may not be explicitly passed @@ -1156,25 +1269,32 @@ function Set-TargetResource { # User does not exist and needs creating $newADUserParams = Get-ADCommonParameters @PSBoundParameters -UseNameParameter + if ($PSBoundParameters.ContainsKey('Path')) { $newADUserParams['Path'] = $Path } + # Populate the AccountPassword parameter of New-ADUser if password declared if ($PSBoundParameters.ContainsKey('Password')) { $newADUserParams['AccountPassword'] = $Password.Password } + Write-Verbose -Message ($script:localizedData.AddingADUser -f $UserName) + New-ADUser @newADUserParams -SamAccountName $UserName + # Now retrieve the newly created user $targetResource = Get-TargetResource @PSBoundParameters } } $setADUserParams = Get-ADCommonParameters @PSBoundParameters + $replaceUserProperties = @{ } $removeUserProperties = @{ } + foreach ($parameter in $PSBoundParameters.Keys) { # Only check/action properties specified/declared parameters that match one of the function's @@ -1185,30 +1305,40 @@ function Set-TargetResource { # Cannot move users by updating the DistinguishedName property $adCommonParameters = Get-ADCommonParameters @PSBoundParameters + # Using the SamAccountName for identity with Move-ADObject does not work, use the DN instead $adCommonParameters['Identity'] = $targetResource.DistinguishedName + Write-Verbose -Message ($script:localizedData.MovingADUser -f $targetResource.Path, $PSBoundParameters.Path) + Move-ADObject @adCommonParameters -TargetPath $PSBoundParameters.Path } elseif ($parameter -eq 'CommonName' -and ($PSBoundParameters.CommonName -ne $targetResource.CommonName)) { # Cannot rename users by updating the CN property directly $adCommonParameters = Get-ADCommonParameters @PSBoundParameters + # Using the SamAccountName for identity with Rename-ADObject does not work, use the DN instead $adCommonParameters['Identity'] = $targetResource.DistinguishedName + Write-Verbose -Message ($script:localizedData.RenamingADUser -f $targetResource.CommonName, $PSBoundParameters.CommonName) + Rename-ADObject @adCommonParameters -NewName $PSBoundParameters.CommonName } elseif ($parameter -eq 'Password' -and $PasswordNeverResets -eq $false) { $adCommonParameters = Get-ADCommonParameters @PSBoundParameters + Write-Verbose -Message ($script:localizedData.SettingADUserPassword -f $UserName) + Set-ADAccountPassword @adCommonParameters -Reset -NewPassword $Password.Password } elseif ($parameter -eq 'Enabled' -and ($PSBoundParameters.$parameter -ne $targetResource.$parameter)) { - # We cannot enable/disable an account with -Add or -Replace parameters, but inform that - # we will change this as it is out of compliance (it always gets set anyway) + <# + We cannot enable/disable an account with -Add or -Replace parameters, but inform that + we will change this as it is out of compliance (it always gets set anyway). + #> Write-Verbose -Message ($script:localizedData.UpdatingADUserProperty -f $parameter, $PSBoundParameters.$parameter) } elseif ($parameter -eq 'ServicePrincipalNames') @@ -1233,6 +1363,7 @@ function Set-TargetResource if (-not ([System.String]::IsNullOrEmpty($targetResource.$parameter))) { Write-Verbose -Message ($script:localizedData.RemovingADUserProperty -f $parameter, $PSBoundParameters.$parameter) + if ($adProperty.UseCmdletParameter -eq $true) { # We need to pass the parameter explicitly to Set-ADUser, not via -Remove @@ -1252,6 +1383,7 @@ function Set-TargetResource { # We are replacing the existing value Write-Verbose -Message ($script:localizedData.UpdatingADUserProperty -f $parameter, $PSBoundParameters.$parameter) + if ($adProperty.UseCmdletParameter -eq $true) { # We need to pass the parameter explicitly to Set-ADUser, not via -Replace @@ -1276,19 +1408,23 @@ function Set-TargetResource { $setADUserParams['Replace'] = $replaceUserProperties } + if ($removeUserProperties.Count -gt 0) { $setADUserParams['Remove'] = $removeUserProperties } Write-Verbose -Message ($script:localizedData.UpdatingADUser -f $UserName) + [ref] $null = Set-ADUser @setADUserParams -Enabled $Enabled } elseif (($Ensure -eq 'Absent') -and ($targetResource.Ensure -eq 'Present')) { # User exists and needs removing Write-Verbose ($script:localizedData.RemovingADUser -f $UserName) + $adCommonParameters = Get-ADCommonParameters @PSBoundParameters + [ref] $null = Remove-ADUser @adCommonParameters -Confirm:$false } @@ -1331,6 +1467,7 @@ function Assert-Parameters ErrorId = 'xADUser_DisabledAccountPasswordConflict' ErrorMessage = $script:localizedData.PasswordParameterConflictError -f 'Enabled', $false, 'Password' } + ThrowInvalidArgumentError @throwInvalidArgumentErrorParams } @@ -1380,6 +1517,7 @@ function Test-Password ) Write-Verbose -Message ($script:localizedData.CreatingADDomainConnection -f $DomainName) + Add-Type -AssemblyName 'System.DirectoryServices.AccountManagement' if ($DomainAdministratorCredential) @@ -1400,6 +1538,7 @@ function Test-Password $null ) } + Write-Verbose -Message ($script:localizedData.CheckingADUserPassword -f $UserName) if ($PasswordAuthentication -eq 'Negotiate') @@ -1420,7 +1559,6 @@ function Test-Password $Password.GetNetworkCredential().Password ) } - } #end function Test-Password Export-ModuleMember -Function *-TargetResource From 028f8ac247ec06c0c401e9a957e4aaf8be255a55 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 12:11:52 +0200 Subject: [PATCH 13/29] Changes to xWaitForADDomain - Code cleanup. --- CHANGELOG.md | 3 +- .../MSFT_xWaitForADDomain.psm1 | 93 +++++++++++-------- 2 files changed, 54 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 197df831b..324645493 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,7 @@ resource is using the `$global:DSCMachineStatus` variable to trigger a reboot. - Added missing property schema descriptions ([issue #369](https://github.com/PowerShell/xActiveDirectory/issues/369)). + - Code cleanup. - Changes to xADRecycleBin - Remove unneeded example and resource designer files. - Added missing property schema descriptions ([issue #368](https://github.com/PowerShell/xActiveDirectory/issues/368)). @@ -103,8 +104,6 @@ which were causing corruption in the Wiki documentation. - Changes to xADDomainDefaultPasswordPolicy - Code cleanup. -- Changes to xADDomainTrust - - Code cleanup. - Changes to xADForestProperties - Minor style cleanup. - Changes to xADOrganizationalUnit diff --git a/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 b/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 index a72664ec2..24e89309d 100644 --- a/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 +++ b/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 @@ -12,25 +12,32 @@ function Get-TargetResource param ( [Parameter(Mandatory = $true)] - [String]$DomainName, + [String] + $DomainName, [Parameter()] - [PSCredential]$DomainUserCredential, + [PSCredential] + $DomainUserCredential, [Parameter()] - [UInt64]$RetryIntervalSec = 60, + [UInt64] + $RetryIntervalSec = 60, [Parameter()] - [UInt32]$RetryCount = 10, + [UInt32] + $RetryCount = 10, [Parameter()] - [UInt32]$RebootRetryCount = 0 - + [UInt32] + $RebootRetryCount = 0 ) - if($DomainUserCredential) + if ($DomainUserCredential) { - $convertToCimCredential = New-CimInstance -ClassName MSFT_Credential -Property @{Username=[string]$DomainUserCredential.UserName; Password=[string]$null} -Namespace root/microsoft/windows/desiredstateconfiguration -ClientOnly + $convertToCimCredential = New-CimInstance -ClassName MSFT_Credential -Namespace 'root/microsoft/windows/desiredstateconfiguration' -ClientOnly -Property @{ + Username = [System.String] $DomainUserCredential.UserName + Password = [System.String] $null + } } else { @@ -38,21 +45,18 @@ function Get-TargetResource } Write-Verbose -Message ($script:localizedData.GetDomain -f $DomainName) - $domain = Get-Domain -DomainName $DomainName -DomainUserCredential $DomainUserCredential + $domain = Get-Domain -DomainName $DomainName -DomainUserCredential $DomainUserCredential - $returnValue = @{ + return @{ DomainName = $domain.Name DomainUserCredential = $convertToCimCredential RetryIntervalSec = $RetryIntervalSec RetryCount = $RetryCount RebootRetryCount = $RebootRetryCount } - - $returnValue } - function Set-TargetResource { <# @@ -69,31 +73,36 @@ function Set-TargetResource param ( [Parameter(Mandatory = $true)] - [String]$DomainName, + [String] + $DomainName, [Parameter()] - [PSCredential]$DomainUserCredential, + [PSCredential] + $DomainUserCredential, [Parameter()] - [UInt64]$RetryIntervalSec = 60, + [UInt64] + $RetryIntervalSec = 60, [Parameter()] - [UInt32]$RetryCount = 10, + [UInt32] + $RetryCount = 10, [Parameter()] - [UInt32]$RebootRetryCount = 0 + [UInt32] + $RebootRetryCount = 0 ) $rebootLogFile = "$env:temp\xWaitForADDomain_Reboot.tmp" - for($count = 0; $count -lt $RetryCount; $count++) + for ($count = 0; $count -lt $RetryCount; $count++) { $domain = Get-Domain -DomainName $DomainName -DomainUserCredential $DomainUserCredential - if($domain) + if ($domain) { - if($RebootRetryCount -gt 0) + if ($RebootRetryCount -gt 0) { Remove-Item $rebootLogFile -ErrorAction SilentlyContinue } @@ -103,30 +112,33 @@ function Set-TargetResource else { Write-Verbose -Message ($script:localizedData.DomainNotFoundRetrying -f $DomainName, $RetryIntervalSec) + Start-Sleep -Seconds $RetryIntervalSec + Clear-DnsClientCache } } - if(-not $domain) + if (-not $domain) { - if($RebootRetryCount -gt 0) + if ($RebootRetryCount -gt 0) { - [UInt32]$rebootCount = Get-Content $RebootLogFile -ErrorAction SilentlyContinue + [UInt32] $rebootCount = Get-Content $RebootLogFile -ErrorAction SilentlyContinue - if($rebootCount -lt $RebootRetryCount) + if ($rebootCount -lt $RebootRetryCount) { $rebootCount = $rebootCount + 1 + Write-Verbose -Message ($script:localizedData.DomainNotFoundRebooting -f $DomainName, $count, $RetryIntervalSec, $rebootCount, $RebootRetryCount) + Set-Content -Path $RebootLogFile -Value $rebootCount + $global:DSCMachineStatus = 1 } else { throw ($script:localizedData.DomainNotFoundAfterReboot -f $DomainName, $RebootRetryCount) } - - } else { @@ -161,40 +173,41 @@ function Test-TargetResource $domain = Get-Domain -DomainName $DomainName -DomainUserCredential $DomainUserCredential - if($domain) + if ($domain) { - if($RebootRetryCount -gt 0) + if ($RebootRetryCount -gt 0) { Remove-Item $rebootLogFile -ErrorAction SilentlyContinue } Write-Verbose -Message ($script:localizedData.DomainInDesiredState -f $DomainName) - $true + + return $true } else { Write-Verbose -Message ($script:localizedData.DomainNotInDesiredState -f $DomainName) - $false + return $false } } - - function Get-Domain { [OutputType([PSObject])] param ( [Parameter(Mandatory = $true)] - [String]$DomainName, + [String] + $DomainName, [Parameter()] - [PSCredential]$DomainUserCredential - + [PSCredential] + $DomainUserCredential ) + Write-Verbose -Message ($script:localizedData.CheckDomain -f $DomainName) - if($DomainUserCredential) + if ($DomainUserCredential) { $context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $DomainName, $DomainUserCredential.UserName, $DomainUserCredential.GetNetworkCredential().Password) } @@ -206,12 +219,12 @@ function Get-Domain try { $domain = ([System.DirectoryServices.ActiveDirectory.DomainController]::FindOne($context)).domain.ToString() + Write-Verbose -Message ($script:localizedData.FoundDomain -f $DomainName) - $returnValue = @{ + + return @{ Name = $domain } - - $returnValue } catch { From 334ce724e5d6127c21a5e54b207547219fe384ad Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 13:22:25 +0200 Subject: [PATCH 14/29] Add VSCode code formatting --- CHANGELOG.md | 11 + .../MSFT_xADComputer/MSFT_xADComputer.psm1 | 71 ++++-- .../MSFT_xADForestProperties.psm1 | 4 +- DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 | 78 ++++--- .../MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 | 61 +++-- .../MSFT_xADManagedServiceAccount.psm1 | 155 ++++++++----- .../MSFT_xADObjectPermissionEntry.psm1 | 22 +- .../MSFT_xADRecycleBin.psm1 | 12 +- .../MSFT_xADReplicationSiteLink.psm1 | 44 ++-- .../MSFT_xADReplicationSubnet.psm1 | 42 ++-- .../MSFT_xADServicePrincipalName.psm1 | 28 ++- DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 | 45 ++-- .../xActiveDirectory.Common.psm1 | 217 +++++++++--------- 13 files changed, 466 insertions(+), 324 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 324645493..58c85480b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,7 @@ - Change the description of the property IdentityReference. - Fix failure when applied in the same configuration as xADDomain - Localize and Improve verbose messaging + - Code cleanup. - Changes to xADOrganizationalUnit - Change the description of the property RestoreFromRecycleBin. - Changes to xADUser @@ -108,6 +109,16 @@ - Minor style cleanup. - Changes to xADOrganizationalUnit - Code cleanup. +- Changes to xADReplicationSiteLink + - Code cleanup. +- Changes to xADReplicationSubnet + - Code cleanup. +- Changes to xADKDSKey + - Code cleanup. +- Changes to xADManagedServiceAccount + - Code cleanup. +- Changes to xADServicePrincipalName + - Code cleanup. ## 2.26.0.0 diff --git a/DSCResources/MSFT_xADComputer/MSFT_xADComputer.psm1 b/DSCResources/MSFT_xADComputer/MSFT_xADComputer.psm1 index 3bd5e1485..449ce4496 100644 --- a/DSCResources/MSFT_xADComputer/MSFT_xADComputer.psm1 +++ b/DSCResources/MSFT_xADComputer/MSFT_xADComputer.psm1 @@ -190,9 +190,10 @@ function Get-TargetResource written with Set-ADComputer the property name must be 'ServicePrincipalName'. This difference is handled here. #> - $computerObjectProperties = @($computerObjectProperties | Where-Object -FilterScript { - $_ -ne 'ServicePrincipalName' - }) + $computerObjectProperties = @($computerObjectProperties | + Where-Object -FilterScript { + $_ -ne 'ServicePrincipalName' + }) $computerObjectProperties += @('ServicePrincipalNames') @@ -413,12 +414,13 @@ function Test-TargetResource } # Need the @() around this to get a new array to enumerate. - @($getTargetResourceParameters.Keys) | ForEach-Object { - if (-not $PSBoundParameters.ContainsKey($_)) - { - $getTargetResourceParameters.Remove($_) + @($getTargetResourceParameters.Keys) | + ForEach-Object { + if (-not $PSBoundParameters.ContainsKey($_)) + { + $getTargetResourceParameters.Remove($_) + } } - } $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters @@ -668,12 +670,13 @@ function Set-TargetResource } # Need the @() around this to get a new array to enumerate. - @($getTargetResourceParameters.Keys) | ForEach-Object { - if (-not $PSBoundParameters.ContainsKey($_)) - { - $getTargetResourceParameters.Remove($_) + @($getTargetResourceParameters.Keys) | + ForEach-Object { + if (-not $PSBoundParameters.ContainsKey($_)) + { + $getTargetResourceParameters.Remove($_) + } } - } $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters @@ -880,15 +883,17 @@ function Set-TargetResource $removeComputerProperties = @{ } # Get all properties, other than Path, that is not in desired state. - $propertiesNotInDesiredState = $compareTargetResourceStateResult | Where-Object -FilterScript { - $_.ParameterName -ne 'Path' -and -not $_.InDesiredState - } + $propertiesNotInDesiredState = $compareTargetResourceStateResult | + Where-Object -FilterScript { + $_.ParameterName -ne 'Path' -and -not $_.InDesiredState + } foreach ($property in $propertiesNotInDesiredState) { - $computerAccountPropertyName = ($script:computerObjectPropertyMap | Where-Object -FilterScript { - $_.ParameterName -eq $property.ParameterName - }).PropertyName + $computerAccountPropertyName = ($script:computerObjectPropertyMap | + Where-Object -FilterScript { + $_.ParameterName -eq $property.ParameterName + }).PropertyName if (-not $computerAccountPropertyName) { @@ -946,10 +951,36 @@ function Set-TargetResource $removeADComputerParameters = Get-ADCommonParameters @PSBoundParameters $removeADComputerParameters['Confirm'] = $false - Remove-ADComputer @removeADComputerParameters | Out-Null + Remove-ADComputer @removeADComputerParameters | + Out-Null } } +<# + .SYNOPSIS + This is a wrapper for Set-ADComputer. + + .PARAMETER Parameters + A hash table containing all parameters that will be passed trough to + Set-ADComputer. + + .NOTES + This is needed because of how Pester is unable to handle mocking the + cmdlet Set-ADComputer. +#> +function Set-DscADComputer +{ + param + ( + [Parameter(Mandatory = $true)] + [System.Collections.Hashtable] + $Parameters + ) + + Set-ADComputer @Parameters | + Out-Null +} + <# .SYNOPSIS This evaluates the service principal names current state against the diff --git a/DSCResources/MSFT_xADForestProperties/MSFT_xADForestProperties.psm1 b/DSCResources/MSFT_xADForestProperties/MSFT_xADForestProperties.psm1 index a164e8c48..f84e6394f 100644 --- a/DSCResources/MSFT_xADForestProperties/MSFT_xADForestProperties.psm1 +++ b/DSCResources/MSFT_xADForestProperties/MSFT_xADForestProperties.psm1 @@ -179,7 +179,7 @@ function Test-TargetResource $forest = Get-ADForest -Identity $ForestName # Validate parameters before we even attempt to retrieve anything - $assertMemberParameters = @{} + $assertMemberParameters = @{ } if ($PSBoundParameters.ContainsKey('ServicePrincipalNameSuffix') -and -not [system.string]::IsNullOrEmpty($ServicePrincipalNameSuffix)) { @@ -204,7 +204,7 @@ function Test-TargetResource $inDesiredState = $false } - $assertMemberParameters = @{} + $assertMemberParameters = @{ } if ($PSBoundParameters.ContainsKey('UserPrincipalNameSuffix') -and -not [system.string]::IsNullOrEmpty($UserPrincipalNameSuffix)) { diff --git a/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 b/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 index 2274048b3..ed64354a8 100644 --- a/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 +++ b/DSCResources/MSFT_xADGroup/MSFT_xADGroup.psm1 @@ -18,12 +18,12 @@ function Get-TargetResource $GroupName, [Parameter()] - [ValidateSet('DomainLocal','Global','Universal')] + [ValidateSet('DomainLocal', 'Global', 'Universal')] [System.String] $GroupScope = 'Global', [Parameter()] - [ValidateSet('Security','Distribution')] + [ValidateSet('Security', 'Distribution')] [System.String] $Category = 'Security', @@ -71,7 +71,7 @@ function Get-TargetResource $MembersToExclude, [Parameter()] - [ValidateSet('SamAccountName','DistinguishedName','SID','ObjectGUID')] + [ValidateSet('SamAccountName', 'DistinguishedName', 'SID', 'ObjectGUID')] [System.String] $MembershipAttribute = 'SamAccountName', @@ -98,7 +98,7 @@ function Get-TargetResource try { - $adGroup = Get-ADGroup @adGroupParams -Property Name,GroupScope,GroupCategory,DistinguishedName,Description,DisplayName,ManagedBy,Info + $adGroup = Get-ADGroup @adGroupParams -Property Name, GroupScope, GroupCategory, DistinguishedName, Description, DisplayName, ManagedBy, Info Write-Verbose -Message ($script:localizedData.RetrievingGroupMembers -f $MembershipAttribute) @@ -106,19 +106,19 @@ function Get-TargetResource [System.Array]$adGroupMembers = (Get-ADGroupMember @adGroupParams).$MembershipAttribute $targetResource = @{ - GroupName = $adGroup.Name - GroupScope = $adGroup.GroupScope - Category = $adGroup.GroupCategory - Path = Get-ADObjectParentDN -DN $adGroup.DistinguishedName - Description = $adGroup.Description - DisplayName = $adGroup.DisplayName - Members = $adGroupMembers - MembersToInclude = $MembersToInclude - MembersToExclude = $MembersToExclude + GroupName = $adGroup.Name + GroupScope = $adGroup.GroupScope + Category = $adGroup.GroupCategory + Path = Get-ADObjectParentDN -DN $adGroup.DistinguishedName + Description = $adGroup.Description + DisplayName = $adGroup.DisplayName + Members = $adGroupMembers + MembersToInclude = $MembersToInclude + MembersToExclude = $MembersToExclude MembershipAttribute = $MembershipAttribute - ManagedBy = $adGroup.ManagedBy - Notes = $adGroup.Info - Ensure = 'Absent' + ManagedBy = $adGroup.ManagedBy + Notes = $adGroup.Info + Ensure = 'Absent' } if ($adGroup) @@ -131,19 +131,19 @@ function Get-TargetResource Write-Verbose -Message ($script:localizedData.GroupNotFound -f $GroupName) $targetResource = @{ - GroupName = $GroupName - GroupScope = $GroupScope - Category = $Category - Path = $Path - Description = $Description - DisplayName = $DisplayName - Members = @() - MembersToInclude = $MembersToInclude - MembersToExclude = $MembersToExclude + GroupName = $GroupName + GroupScope = $GroupScope + Category = $Category + Path = $Path + Description = $Description + DisplayName = $DisplayName + Members = @() + MembersToInclude = $MembersToInclude + MembersToExclude = $MembersToExclude MembershipAttribute = $MembershipAttribute - ManagedBy = $ManagedBy - Notes = $Notes - Ensure = 'Absent' + ManagedBy = $ManagedBy + Notes = $Notes + Ensure = 'Absent' } } @@ -161,12 +161,12 @@ function Test-TargetResource $GroupName, [Parameter()] - [ValidateSet('DomainLocal','Global','Universal')] + [ValidateSet('DomainLocal', 'Global', 'Universal')] [System.String] $GroupScope = 'Global', [Parameter()] - [ValidateSet('Security','Distribution')] + [ValidateSet('Security', 'Distribution')] [System.String] $Category = 'Security', @@ -214,7 +214,7 @@ function Test-TargetResource $MembersToExclude, [Parameter()] - [ValidateSet('SamAccountName','DistinguishedName','SID','ObjectGUID')] + [ValidateSet('SamAccountName', 'DistinguishedName', 'SID', 'ObjectGUID')] [System.String] $MembershipAttribute = 'SamAccountName', @@ -236,7 +236,7 @@ function Test-TargetResource ) # Validate parameters before we even attempt to retrieve anything - $assertMemberParameters = @{} + $assertMemberParameters = @{ } if ($PSBoundParameters.ContainsKey('Members') -and -not [system.string]::IsNullOrEmpty($Members)) { @@ -328,12 +328,12 @@ function Set-TargetResource $GroupName, [Parameter()] - [ValidateSet('DomainLocal','Global','Universal')] + [ValidateSet('DomainLocal', 'Global', 'Universal')] [System.String] $GroupScope = 'Global', [Parameter()] - [ValidateSet('Security','Distribution')] + [ValidateSet('Security', 'Distribution')] [System.String] $Category = 'Security', @@ -381,7 +381,7 @@ function Set-TargetResource $MembersToExclude, [Parameter()] - [ValidateSet('SamAccountName','DistinguishedName','SID','ObjectGUID')] + [ValidateSet('SamAccountName', 'DistinguishedName', 'SID', 'ObjectGUID')] [System.String] $MembershipAttribute = 'SamAccountName', @@ -420,7 +420,10 @@ function Set-TargetResource $groupMemberDomains += Get-ADDomainNameFromDistinguishedName -DistinguishedName $member } - $GroupMemberDomainCount = ($groupMemberDomains | Select-Object -Unique).count + $uniqueGroupMemberDomainCount = $groupMemberDomains | + Select-Object -Unique + + $GroupMemberDomainCount = $uniqueGroupMemberDomainCount.count if ($GroupMemberDomainCount -gt 1 -or ($groupMemberDomains -ine (Get-DomainName)).Count -gt 0) { @@ -429,7 +432,7 @@ function Set-TargetResource } } - $adGroup = Get-ADGroup @adGroupParams -Property Name,GroupScope,GroupCategory,DistinguishedName,Description,DisplayName,ManagedBy,Info + $adGroup = Get-ADGroup @adGroupParams -Property Name, GroupScope, GroupCategory, DistinguishedName, Description, DisplayName, ManagedBy, Info if ($Ensure -eq 'Present') { @@ -626,7 +629,6 @@ function Set-TargetResource Add-ADCommonGroupMember -Parameter $adGroupParams -Members $MembersToInclude -MembersInMultipleDomains:$MembersInMultipleDomains } - } } #end catch } #end function Set-TargetResource diff --git a/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 b/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 index 5a5fd28d9..2725a1f6d 100644 --- a/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 +++ b/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 @@ -78,9 +78,10 @@ function Get-TargetResource $kdsRootKey = $null if ($kdsRootKeys) { - $kdsRootKey = $kdsRootKeys.GetEnumerator() | Where-Object -FilterScript { - [DateTime]::Parse($_.EffectiveTime) -eq $effectiveTimeObject - } + $kdsRootKey = $kdsRootKeys.GetEnumerator() | + Where-Object -FilterScript { + [DateTime]::Parse($_.EffectiveTime) -eq $effectiveTimeObject + } } if (-not $kdsRootKey) @@ -102,12 +103,12 @@ function Get-TargetResource } elseif ($kdsRootKey) { - $targetResource['Ensure'] = 'Present' - $targetResource['EffectiveTime'] = ([DateTime]::Parse($kdsRootKey.EffectiveTime)).ToString() - $targetResource['CreationTime'] = $kdsRootKey.CreationTime - $targetResource['KeyId'] = $kdsRootKey.KeyId + $targetResource['Ensure'] = 'Present' + $targetResource['EffectiveTime'] = ([DateTime]::Parse($kdsRootKey.EffectiveTime)).ToString() + $targetResource['CreationTime'] = $kdsRootKey.CreationTime + $targetResource['KeyId'] = $kdsRootKey.KeyId $targetResource['DistinguishedName'] = 'CN={0},CN=Master Root Keys,CN=Group Key Distribution Service,CN=Services,CN=Configuration,{1}' -f - $kdsRootKey.KeyId, (Get-ADRootDomainDN) + $kdsRootKey.KeyId, (Get-ADRootDomainDN) } } @@ -182,14 +183,19 @@ function Test-TargetResource } $compareTargetResourceNonCompliant = Compare-TargetResourceState @getTargetResourceParameters | - Where-Object -FilterScript {$_.Pass -eq $false} + Where-Object -FilterScript { + $_.Pass -eq $false + } - $ensureState = $compareTargetResourceNonCompliant | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} + $ensureState = $compareTargetResourceNonCompliant | + Where-Object -FilterScript { + $_.Parameter -eq 'Ensure' + } if ($ensureState) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f - 'Ensure', $EffectiveTime, $ensureState.Expected, $ensureState.Actual) + 'Ensure', $EffectiveTime, $ensureState.Expected, $ensureState.Actual) Write-Verbose -Message ($script:localizedData.KDSRootKeyNotInDesiredState -f $EffectiveTime) return $false } @@ -267,7 +273,10 @@ function Set-TargetResource } $compareTargetResource = Compare-TargetResourceState @getTargetResourceParameters - $ensureState = $compareTargetResource | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} + $ensureState = $compareTargetResource | + Where-Object -FilterScript { + $_.Parameter -eq 'Ensure' + } # Ensure is not in proper state if ($ensureState.Pass -eq $false) @@ -288,7 +297,7 @@ function Set-TargetResource # We want the key to be present, but it currently does not exist if ($effectiveTimeObject -le $currentDateTimeObject -and - $PSBoundParameters.ContainsKey('AllowUnsafeEffectiveTime') -and $AllowUnsafeEffectiveTime) + $PSBoundParameters.ContainsKey('AllowUnsafeEffectiveTime') -and $AllowUnsafeEffectiveTime) { Write-Warning -Message ($script:localizedData.AddingKDSRootKeyDateInPast -f $EffectiveTime) } @@ -342,7 +351,9 @@ function Set-TargetResource } } - $distinguishedName = $compareTargetResource | Where-Object -FilterScript {$_.Parameter -eq 'DistinguishedName'} + $distinguishedName = $compareTargetResource | + Where-Object -FilterScript { $_.Parameter -eq 'DistinguishedName' } + try { Remove-ADObject -Identity $distinguishedName.Actual -Confirm:$false @@ -395,7 +406,7 @@ function Compare-TargetResourceState ) $getTargetResourceParameters = @{ - EffectiveTime = $EffectiveTime + EffectiveTime = $EffectiveTime } $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters @@ -405,7 +416,7 @@ function Compare-TargetResourceState $PSBoundParameters['DistinguishedName'] = $getTargetResourceResult['DistinguishedName'] # Convert EffectiveTime to DateTime object for comparison - $PSBoundParameters['EffectiveTime'] = [DateTime]::Parse($EffectiveTime) + $PSBoundParameters['EffectiveTime'] = [DateTime]::Parse($EffectiveTime) $getTargetResourceResult['EffectiveTime'] = [DateTime]::Parse($getTargetResourceResult.EffectiveTime) foreach ($parameter in $PSBoundParameters.Keys) @@ -451,6 +462,10 @@ function Compare-TargetResourceState .PARAMETER User The user to check permissions against + + .NOTES + Get-KdsRootKey will return $null instead of a permission error if it can't retrieve the keys + so we need manually check #> function Assert-HasDomainAdminRights { @@ -464,12 +479,6 @@ function Assert-HasDomainAdminRights $User ) - <# - Get-KdsRootKey will return $null instead of a permission error if it can't retrieve the keys - so we need manually check - #> - - $windowsPrincipal = New-Object -TypeName System.Security.Principal.WindowsPrincipal($User) $osInfo = Get-CimInstance -ClassName Win32_OperatingSystem @@ -477,8 +486,8 @@ function Assert-HasDomainAdminRights Write-Verbose -Message ($script:localizedData.CheckingDomainAdminComputerRights -f $osInfo.CSName, $osInfo.ProductType) return $windowsPrincipal.IsInRole("Domain Admins") -or - $windowsPrincipal.IsInRole("Enterprise Admins") -or - $osInfo.ProductType -eq 2 + $windowsPrincipal.IsInRole("Enterprise Admins") -or + $osInfo.ProductType -eq 2 } <# @@ -497,7 +506,9 @@ function Get-ADRootDomainDN { [CmdletBinding()] [OutputType([System.String])] - param() + param + ( + ) $rootDomainDN = (New-Object -TypeName System.DirectoryServices.DirectoryEntry('LDAP://RootDSE')).Get('rootDomainNamingContext') Write-Verbose -Message ($script:localizedData.RetrievedRootDomainDN -f $rootDomainDN) diff --git a/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 b/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 index 1d1b6a57e..e89bbbc62 100644 --- a/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 +++ b/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 @@ -43,7 +43,7 @@ function Get-TargetResource $ServiceAccountName, [Parameter()] - [ValidateSet('SamAccountName','DistinguishedName','SID','ObjectGUID')] + [ValidateSet('SamAccountName', 'DistinguishedName', 'SID', 'ObjectGUID')] [System.String] $MembershipAttribute = 'SamAccountName', @@ -101,11 +101,11 @@ function Get-TargetResource 'ObjectGUID' ) - $targetResource['Ensure'] = 'Present' - $targetResource['Path'] = Get-ADObjectParentDN -DN $adServiceAccount.DistinguishedName - $targetResource['Description'] = $adServiceAccount.Description - $targetResource['DisplayName'] = $adServiceAccount.DisplayName - $targetResource['Enabled'] = [System.Boolean] $adServiceAccount.Enabled + $targetResource['Ensure'] = 'Present' + $targetResource['Path'] = Get-ADObjectParentDN -DN $adServiceAccount.DistinguishedName + $targetResource['Description'] = $adServiceAccount.Description + $targetResource['DisplayName'] = $adServiceAccount.DisplayName + $targetResource['Enabled'] = [System.Boolean] $adServiceAccount.Enabled $targetResource['DistinguishedName'] = $adServiceAccount.DistinguishedName if ( $adServiceAccount.ObjectClass -eq 'msDS-ManagedServiceAccount' ) @@ -115,10 +115,11 @@ function Get-TargetResource elseif ( $adServiceAccount.ObjectClass -eq 'msDS-GroupManagedServiceAccount' ) { Write-Verbose -Message ($script:localizedData.RetrievingPrincipalMembers -f $MembershipAttribute) - $adServiceAccount.PrincipalsAllowedToRetrieveManagedPassword | ForEach-Object { - $member = (Get-ADObject -Identity $_ -Property $MembershipAttribute).$MembershipAttribute - $targetResource['Members'] += $member - } + $adServiceAccount.PrincipalsAllowedToRetrieveManagedPassword | + ForEach-Object { + $member = (Get-ADObject -Identity $_ -Property $MembershipAttribute).$MembershipAttribute + $targetResource['Members'] += $member + } $targetResource['AccountType'] = 'Group' } @@ -133,6 +134,7 @@ function Get-TargetResource $errorMessage = $script:localizedData.RetrievingServiceAccountError -f $ServiceAccountName New-InvalidOperationException -Message $errorMessage -ErrorRecord $_ } + return $targetResource } #end function Get-TargetResource @@ -225,7 +227,7 @@ function Test-TargetResource $Members, [Parameter()] - [ValidateSet('SamAccountName','DistinguishedName','SID','ObjectGUID')] + [ValidateSet('SamAccountName', 'DistinguishedName', 'SID', 'ObjectGUID')] [System.String] $MembershipAttribute = 'SamAccountName', @@ -242,20 +244,23 @@ function Test-TargetResource ) # Need to set these parameters to compare if users are using the default parameter values - $PSBoundParameters['Ensure'] = $Ensure - $PSBoundParameters['AccountType'] = $AccountType + $PSBoundParameters['Ensure'] = $Ensure + $PSBoundParameters['AccountType'] = $AccountType $PSBoundParameters['MembershipAttribute'] = $MembershipAttribute - $compareTargetResourceNonCompliant = Compare-TargetResourceState @PSBoundParameters | Where-Object {$_.Pass -eq $false} + $compareTargetResourceNonCompliant = Compare-TargetResourceState @PSBoundParameters | + Where-Object { $_.Pass -eq $false } # Check if Absent, if so then we don't need to propagate any other parameters if ($Ensure -eq 'Absent') { - $ensureState = $compareTargetResourceNonCompliant | Where-Object {$_.Parameter -eq 'Ensure'} + $ensureState = $compareTargetResourceNonCompliant | + Where-Object { $_.Parameter -eq 'Ensure' } + if ($ensureState) { Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f ` - 'Ensure', $ensureState.Expected, $ensureState.Actual) + 'Ensure', $ensureState.Expected, $ensureState.Actual) } else { @@ -265,10 +270,11 @@ function Test-TargetResource } else { - $compareTargetResourceNonCompliant | ForEach-Object { - Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f ` - $_.Parameter, $_.Expected, $_.Actual) - } + $compareTargetResourceNonCompliant | + ForEach-Object { + Write-Verbose -Message ($script:localizedData.NotDesiredPropertyState -f ` + $_.Parameter, $_.Expected, $_.Actual) + } } if ($compareTargetResourceNonCompliant) @@ -373,7 +379,7 @@ function Set-TargetResource $Members, [Parameter()] - [ValidateSet('SamAccountName','DistinguishedName','SID','ObjectGUID')] + [ValidateSet('SamAccountName', 'DistinguishedName', 'SID', 'ObjectGUID')] [System.String] $MembershipAttribute = 'SamAccountName', @@ -390,12 +396,13 @@ function Set-TargetResource ) # Need to set these to compare if not specified since user is using defaults - $PSBoundParameters['Ensure'] = $Ensure - $PSBoundParameters['AccountType'] = $AccountType + $PSBoundParameters['Ensure'] = $Ensure + $PSBoundParameters['AccountType'] = $AccountType $PSBoundParameters['MembershipAttribute'] = $MembershipAttribute $compareTargetResource = Compare-TargetResourceState @PSBoundParameters - $compareTargetResourceNonCompliant = @($compareTargetResource | Where-Object {$_.Pass -eq $false}) + $compareTargetResourceNonCompliant = @($compareTargetResource | + Where-Object { $_.Pass -eq $false }) $adServiceAccountParameters = Get-ADCommonParameters @PSBoundParameters $setServiceAccountParameters = $adServiceAccountParameters.Clone() @@ -406,7 +413,8 @@ function Set-TargetResource if ($Ensure -eq 'Present') { $isEnsureNonCompliant = $false - if ($compareTargetResourceNonCompliant | Where-Object {$_.Parameter -eq 'Ensure'}) + if ($compareTargetResourceNonCompliant | + Where-Object { $_.Parameter -eq 'Ensure' }) { $isEnsureNonCompliant = $true } @@ -420,7 +428,8 @@ function Set-TargetResource else { #region Check if AccountType is compliant - $accountTypeState = $compareTargetResourceNonCompliant | Where-Object {$_.Parameter -eq 'AccountType'} + $accountTypeState = $compareTargetResourceNonCompliant | + Where-Object { $_.Parameter -eq 'AccountType' } # Account already exist, need to update parameters that are not in compliance if ($accountTypeState) @@ -438,13 +447,16 @@ function Set-TargetResource Write-Warning -Message ($script:localizedData.AccountTypeForceNotTrue -f $accountTypeState.Actual, $accountTypeState.Expected) } } + # Remove AccountType since we don't want to enumerate down below - $compareTargetResourceNonCompliant = @($compareTargetResourceNonCompliant | Where-Object {$_.Parameter -ne 'AccountType'}) + $compareTargetResourceNonCompliant = @($compareTargetResourceNonCompliant | + Where-Object { $_.Parameter -ne 'AccountType' }) #endregion Check if AccountType is compliant #region Check if Path is compliant $isPathNonCompliant = $false - if ($compareTargetResourceNonCompliant | Where-Object {$_.Parameter -eq 'Path'}) + if ($compareTargetResourceNonCompliant | + Where-Object { $_.Parameter -eq 'Path' }) { $isPathNonCompliant = $true } @@ -452,35 +464,41 @@ function Set-TargetResource if ($isPathNonCompliant) { Write-Verbose -Message ($script:localizedData.MovingManagedServiceAccount -f $ServiceAccountName, $Path) - $distinguishedNameObject = $compareTargetResource | Where-Object {$_.Parameter -eq 'DistinguishedName'} + $distinguishedNameObject = $compareTargetResource | + Where-Object { $_.Parameter -eq 'DistinguishedName' } + $moveADObjectParameters['Identity'] = $distinguishedNameObject.Actual + Move-ADObject @moveADObjectParameters -TargetPath $Path } - $compareTargetResourceNonCompliant = @($compareTargetResourceNonCompliant | Where-Object {$_.Parameter -ne 'Path'}) + + $compareTargetResourceNonCompliant = @($compareTargetResourceNonCompliant | + Where-Object { $_.Parameter -ne 'Path' }) #endregion Check if Path is compliant #region Check if other parameters are compliant $updateProperties = $false - $compareTargetResourceNonCompliant | ForEach-Object { - $updateProperties = $true - $parameter = $_.Parameter - if ($parameter -eq 'Members' -and $AccountType -eq 'Group') - { - if ([system.string]::IsNullOrEmpty($Members)) + $compareTargetResourceNonCompliant | + ForEach-Object { + $updateProperties = $true + $parameter = $_.Parameter + if ($parameter -eq 'Members' -and $AccountType -eq 'Group') { - $Members = @() + if ([system.string]::IsNullOrEmpty($Members)) + { + $Members = @() + } + $listMembers = $Members -join ',' + + Write-Verbose -Message ($script:localizedData.UpdatingManagedServiceAccountProperty -f 'Members', $listMembers) + $setServiceAccountParameters['PrincipalsAllowedToRetrieveManagedPassword'] = $Members + } + else + { + Write-Verbose -Message ($script:localizedData.UpdatingManagedServiceAccountProperty -f $parameter, $PSBoundParameters.$parameter) + $setServiceAccountParameters[$parameter] = $PSBoundParameters.$parameter } - $listMembers = $Members -join ',' - - Write-Verbose -Message ($script:localizedData.UpdatingManagedServiceAccountProperty -f 'Members', $listMembers) - $setServiceAccountParameters['PrincipalsAllowedToRetrieveManagedPassword'] = $Members - } - else - { - Write-Verbose -Message ($script:localizedData.UpdatingManagedServiceAccountProperty -f $parameter, $PSBoundParameters.$parameter) - $setServiceAccountParameters[$parameter] = $PSBoundParameters.$parameter } - } if ($compareTargetResourceNonCompliant.Count -gt 0) { @@ -492,7 +510,8 @@ function Set-TargetResource elseif ($Ensure -eq 'Absent') { $isEnsureNonCompliant = $false - if ($compareTargetResourceNonCompliant | Where-Object {$_.Parameter -eq 'Ensure'}) + if ($compareTargetResourceNonCompliant | + Where-Object { $_.Parameter -eq 'Ensure' }) { $isEnsureNonCompliant = $true } @@ -596,7 +615,7 @@ function New-ADServiceAccountHelper $Members, [Parameter()] - [ValidateSet('SamAccountName','DistinguishedName','SID','ObjectGUID')] + [ValidateSet('SamAccountName', 'DistinguishedName', 'SID', 'ObjectGUID')] [System.String] $MembershipAttribute = 'SamAccountName', @@ -651,7 +670,6 @@ function New-ADServiceAccountHelper } } #end function New-ADServiceAccountHelper - <# .SYNOPSIS Compares the state of the managed service account. @@ -740,7 +758,7 @@ function Compare-TargetResourceState $Members, [Parameter()] - [ValidateSet('SamAccountName','DistinguishedName','SID','ObjectGUID')] + [ValidateSet('SamAccountName', 'DistinguishedName', 'SID', 'ObjectGUID')] [System.String] $MembershipAttribute, @@ -764,20 +782,25 @@ function Compare-TargetResourceState AccountTypeForce = $AccountTypeForce } - @($getTargetResourceParameters.Keys) | ForEach-Object { - if (-not $PSBoundParameters.ContainsKey($_)) - { - $getTargetResourceParameters.Remove($_) + @($getTargetResourceParameters.Keys) | + ForEach-Object { + if (-not $PSBoundParameters.ContainsKey($_)) + { + $getTargetResourceParameters.Remove($_) + } } - } $getTargetResource = Get-TargetResource @getTargetResourceParameters $compareTargetResource = @() # Add DistinguishedName as it won't be passed as an argument, but we want to get the DN in Set $PSBoundParameters['DistinguishedName'] = $getTargetResource['DistinguishedName'] - # Set MembershipAttribute as it's not required to be compliant. It's only used when setting/getting members for gMSA - # and there is no way to check if it is in compliance since whatever is passed would be compliant itself + + <# + Set MembershipAttribute as it's not required to be compliant. It's only + used when setting/getting members for gMSA and there is no way to check + if it is in compliance since whatever is passed would be compliant itself. + #> $PSBoundParameters['MembershipAttribute'] = $getTargetResource['MembershipAttribute'] foreach ($parameter in $PSBoundParameters.Keys) @@ -799,11 +822,14 @@ function Compare-TargetResourceState { $testMembersParams = @{ ExistingMembers = $getTargetResource.Members -as [System.String[]] - Members = $Members + Members = $Members } - $expectedMembers = ($Members | Sort-Object) -join ',' - $actualMembers = ($testMembersParams['ExistingMembers'] | Sort-Object) -join ',' + $expectedMembers = ($Members | + Sort-Object) -join ',' + + $actualMembers = ($testMembersParams['ExistingMembers'] | + Sort-Object) -join ',' if (-not (Test-Members @testMembersParams)) { @@ -825,11 +851,14 @@ function Compare-TargetResourceState } } } + # Need to check if parameter is part of schema, otherwise ignore all other parameters like verbose elseif ($getTargetResource.ContainsKey($parameter)) { - # We are out of compliance if we get here - # $PSBoundParameters.$parameter -ne $getTargetResource.$parameter + <# + We are out of compliance if we get here + $PSBoundParameters.$parameter -ne $getTargetResource.$parameter + #> $compareTargetResource += [pscustomobject] @{ Parameter = $parameter Expected = $PSBoundParameters.$parameter diff --git a/DSCResources/MSFT_xADObjectPermissionEntry/MSFT_xADObjectPermissionEntry.psm1 b/DSCResources/MSFT_xADObjectPermissionEntry/MSFT_xADObjectPermissionEntry.psm1 index 256a12739..0dcac252c 100644 --- a/DSCResources/MSFT_xADObjectPermissionEntry/MSFT_xADObjectPermissionEntry.psm1 +++ b/DSCResources/MSFT_xADObjectPermissionEntry/MSFT_xADObjectPermissionEntry.psm1 @@ -98,7 +98,7 @@ function Get-TargetResource Write-Verbose -Message ($script:localizedData.ObjectPermissionEntryFound -f $Path) $returnValue['Ensure'] = 'Present' - $returnValue['ActiveDirectoryRights'] = [String[]] $access.ActiveDirectoryRights.ToString().Split(',').ForEach({ $_.Trim() }) + $returnValue['ActiveDirectoryRights'] = [String[]] $access.ActiveDirectoryRights.ToString().Split(',').ForEach( { $_.Trim() }) return $returnValue } @@ -199,11 +199,11 @@ function Set-TargetResource $ntAccount = New-Object -TypeName 'System.Security.Principal.NTAccount' -ArgumentList $IdentityReference $ace = New-Object -TypeName 'System.DirectoryServices.ActiveDirectoryAccessRule' -ArgumentList $ntAccount, - $ActiveDirectoryRights, - $AccessControlType, - $ObjectType, - $ActiveDirectorySecurityInheritance, - $InheritedObjectType + $ActiveDirectoryRights, + $AccessControlType, + $ObjectType, + $ActiveDirectorySecurityInheritance, + $InheritedObjectType $acl.AddAccessRule($ace) } @@ -232,7 +232,8 @@ function Set-TargetResource } # Set the updated acl to the object - $acl | Set-Acl -Path "AD:$Path" + $acl | + Set-Acl -Path "AD:$Path" } <# @@ -330,8 +331,11 @@ function Test-TargetResource if ($Ensure -eq 'Present') { # Convert to array to a string for easy compare - [String] $currentActiveDirectoryRights = ($currentState.ActiveDirectoryRights | Sort-Object) -join ', ' - [String] $desiredActiveDirectoryRights = ($ActiveDirectoryRights | Sort-Object) -join ', ' + [String] $currentActiveDirectoryRights = ($currentState.ActiveDirectoryRights | + Sort-Object) -join ', ' + + [String] $desiredActiveDirectoryRights = ($ActiveDirectoryRights | + Sort-Object) -join ', ' $returnValue = $returnValue -and $currentActiveDirectoryRights -eq $desiredActiveDirectoryRights } diff --git a/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 b/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 index a34fd5bd6..6635c3f24 100644 --- a/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 +++ b/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 @@ -44,7 +44,7 @@ function Get-TargetResource $recycleBinEnabled = $false } } - catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] + catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException], [Microsoft.ActiveDirectory.Management.ADServerDownException] { Write-Error -Message ($script:localizedData.ForestNotFound -f $ForestFQDN) throw $_ @@ -65,15 +65,15 @@ function Get-TargetResource } return @{ - ForestFQDN = $ForestFQDN + ForestFQDN = $ForestFQDN RecycleBinEnabled = $recycleBinEnabled - ForestMode = $rootDSE.forestFunctionality.ToString() + ForestMode = $rootDSE.forestFunctionality.ToString() } } function Set-TargetResource { - [CmdletBinding(SupportsShouldProcess=$true)] + [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] @@ -108,7 +108,7 @@ function Set-TargetResource -Verbose } } - catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] + catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException], [Microsoft.ActiveDirectory.Management.ADServerDownException] { Write-Error -Message ($script:localizedData.ForestNotFound -f $ForestFQDN) throw $_ @@ -167,7 +167,7 @@ function Test-TargetResource return $false } } - catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException],[Microsoft.ActiveDirectory.Management.ADServerDownException] + catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException], [Microsoft.ActiveDirectory.Management.ADServerDownException] { Write-Error -Message ($script:localizedData.ForestNotFound -f $ForestFQDN) throw $_ diff --git a/DSCResources/MSFT_xADReplicationSiteLink/MSFT_xADReplicationSiteLink.psm1 b/DSCResources/MSFT_xADReplicationSiteLink/MSFT_xADReplicationSiteLink.psm1 index c47c8dbbb..a616d3b71 100644 --- a/DSCResources/MSFT_xADReplicationSiteLink/MSFT_xADReplicationSiteLink.psm1 +++ b/DSCResources/MSFT_xADReplicationSiteLink/MSFT_xADReplicationSiteLink.psm1 @@ -61,13 +61,15 @@ function Get-TargetResource if ($siteLink.SitesIncluded) { $siteCommonNames = @() + foreach ($siteDN in $siteLink.SitesIncluded) { $siteCommonNames += Resolve-SiteLinkName -SiteName $siteDn } } - $sitesExcludedEvaluated = $SitesExcluded | Where-Object -FilterScript { $_ -notin $siteCommonNames } + $sitesExcludedEvaluated = $SitesExcluded | + Where-Object -FilterScript { $_ -notin $siteCommonNames } $returnValue = @{ Name = $Name @@ -145,13 +147,17 @@ function Set-TargetResource if ($Ensure -eq 'Present') { - # modify parameters for splatting to New-ADReplicationSiteLink + # Modify parameters for splatting to New-ADReplicationSiteLink. $desiredParameters = $PSBoundParameters $desiredParameters.Remove('Ensure') $desiredParameters.Remove('SitesExcluded') $currentADSiteLink = Get-TargetResource -Name $Name - # since Set and New have different parameters we have to test if the site link exists to determine what cmdlet we need to use + + <# + Since Set and New have different parameters we have to test if the + site link exists to determine what cmdlet we need to use. + #> if ( $currentADSiteLink.Ensure -eq 'Absent' ) { Write-Verbose -Message ($script:localizedData.NewSiteLink -f $Name) @@ -159,26 +165,32 @@ function Set-TargetResource } else { - # now we have to determine if we need to add or remove sites from SitesIncluded + # now we have to determine if we need to add or remove sites from SitesIncluded. $setParameters = @{ Identity = $Name } - # build the SitesIncluded hashtable - $sitesIncludedParameters = @{} + # build the SitesIncluded hashtable. + $sitesIncludedParameters = @{ } if ($SitesExcluded) { Write-Verbose -Message ($script:localizedData.RemovingSites -f $($SiteExcluded -join ', '), $Name) - # wrapped in $() as we were getting some weird results without it, - # results were not being added into Hashtable as strings + + <# + Wrapped in $() as we were getting some weird results without it, + results were not being added into Hashtable as strings. + #> $sitesIncludedParameters.Add('Remove', $($SitesExcluded)) } if ($SitesIncluded) { Write-Verbose -Message ($script:localizedData.AddingSites -f $($SitesIncluded -join ', '), $Name) - # wrapped in $() as we were getting some weird results without it, - # results were not being added into Hashtable as strings + + <# + Wrapped in $() as we were getting some weird results without it, + results were not being added into Hashtable as strings. + #> $sitesIncludedParameters.Add('Add', $($SitesIncluded)) } @@ -187,7 +199,7 @@ function Set-TargetResource $setParameters.Add('SitesIncluded', $sitesIncludedParameters) } - # add the rest of the parameteres + # Add the rest of the parameters. foreach ($parameter in $PSBoundParameters.Keys) { if ($parameter -notmatch 'SitesIncluded|SitesExcluded|Name|Ensure') @@ -202,6 +214,7 @@ function Set-TargetResource else { Write-Verbose -Message ($script:localizedData.RemoveSiteLink -f $Name) + Remove-ADReplicationSiteLink -Identity $Name } } @@ -269,13 +282,14 @@ function Test-TargetResource $isCompliant = $true $currentSiteLink = Get-TargetResource -Name $Name - # test for Ensure + + # Test for Ensure. if ($Ensure -ne $currentSiteLink.Ensure) { return $false } - # test for SitesIncluded + # Test for SitesIncluded. foreach ($desiredIncludedSite in $SitesIncluded) { if ($desiredIncludedSite -notin $currentSiteLink.SitesIncluded) @@ -285,7 +299,7 @@ function Test-TargetResource } } - # test for SitesExcluded + # Test for SitesExcluded. foreach ($desiredExcludedSite in $SitesExcluded) { if ($desiredExcludedSite -in $currentSiteLink.SitesIncluded) @@ -295,7 +309,7 @@ function Test-TargetResource } } - # test for Description|ReplicationFrequencyInMinutes|Cost + # Test for Description|ReplicationFrequencyInMinutes|Cost. foreach ($parameter in $PSBoundParameters.Keys) { if ($parameter -match 'Description|ReplicationFrequencyInMinutes|Cost') diff --git a/DSCResources/MSFT_xADReplicationSubnet/MSFT_xADReplicationSubnet.psm1 b/DSCResources/MSFT_xADReplicationSubnet/MSFT_xADReplicationSubnet.psm1 index 0482b1c73..5aded77fc 100644 --- a/DSCResources/MSFT_xADReplicationSubnet/MSFT_xADReplicationSubnet.psm1 +++ b/DSCResources/MSFT_xADReplicationSubnet/MSFT_xADReplicationSubnet.psm1 @@ -33,15 +33,19 @@ function Get-TargetResource $Site ) - # Get the replication subnet filtered by it's name. If the subnet is not - # present, the command will return $null. + <# + Get the replication subnet filtered by it's name. If the subnet is not + present, the command will return $null. + #> Write-Verbose -Message ($script:localizedData.GetReplicationSubnet -f $Name) + $replicationSubnet = Get-ADReplicationSubnet -Filter { Name -eq $Name } if ($null -eq $replicationSubnet) { # Replication subnet not found, return absent. Write-Verbose -Message ($script:localizedData.ReplicationSubnetAbsent -f $Name) + $returnValue = @{ Ensure = 'Absent' Name = $Name @@ -53,13 +57,16 @@ function Get-TargetResource { # Get the name of the replication site, if it's not empty. $replicationSiteName = '' + if ($null -ne $replicationSubnet.Site) { - $replicationSiteName = Get-ADObject -Identity $replicationSubnet.Site | Select-Object -ExpandProperty 'Name' + $replicationSiteName = Get-ADObject -Identity $replicationSubnet.Site | + Select-Object -ExpandProperty 'Name' } # Replication subnet found, return present. Write-Verbose -Message ($script:localizedData.ReplicationSubnetPresent -f $Name) + $returnValue = @{ Ensure = 'Present' Name = $Name @@ -112,8 +119,10 @@ function Set-TargetResource $Location = '' ) - # Get the replication subnet filtered by it's name. If the subnet is not - # present, the command will return $null. + <# + Get the replication subnet filtered by it's name. If the subnet is not + present, the command will return $null. + #> $replicationSubnet = Get-ADReplicationSubnet -Filter { Name -eq $Name } if ($Ensure -eq 'Present') @@ -126,12 +135,16 @@ function Set-TargetResource $replicationSubnet = New-ADReplicationSubnet -Name $Name -Site $Site -PassThru } - # Get the name of the replication site, if it's not empty and update the - # site if it's not vaild. + <# + Get the name of the replication site, if it's not empty and update the + site if it's not vaild. + #> if ($null -ne $replicationSubnet.Site) { - $replicationSiteName = Get-ADObject -Identity $replicationSubnet.Site | Select-Object -ExpandProperty 'Name' + $replicationSiteName = Get-ADObject -Identity $replicationSubnet.Site | + Select-Object -ExpandProperty 'Name' } + if ($replicationSiteName -ne $Site) { Write-Verbose -Message ($script:localizedData.SetReplicationSubnetSite -f $Name, $Site) @@ -139,14 +152,17 @@ function Set-TargetResource Set-ADReplicationSubnet -Identity $replicationSubnet.DistinguishedName -Site $Site -PassThru } - # Update the location, if it's not valid. Ensure an empty location - # string is converted to $null, because the Set-ADReplicationSubnet does - # not accept an empty string for the location, but $null. + <# + Update the location, if it's not valid. Ensure an empty location + string is converted to $null, because the Set-ADReplicationSubnet + does not accept an empty string for the location, but $null. + #> $nullableLocation = $Location if ([String]::IsNullOrEmpty($Location)) { $nullableLocation = $null } + if ($replicationSubnet.Location -ne $nullableLocation) { Write-Verbose -Message ($script:localizedData.SetReplicationSubnetLocation -f $Name, $nullableLocation) @@ -216,8 +232,8 @@ function Test-TargetResource if ($Ensure -eq 'Present') { $desiredConfigurationMatch = $desiredConfigurationMatch -and - $currentConfiguration.Site -eq $Site -and - $currentConfiguration.Location -eq $Location + $currentConfiguration.Site -eq $Site -and + $currentConfiguration.Location -eq $Location } if ($desiredConfigurationMatch) diff --git a/DSCResources/MSFT_xADServicePrincipalName/MSFT_xADServicePrincipalName.psm1 b/DSCResources/MSFT_xADServicePrincipalName/MSFT_xADServicePrincipalName.psm1 index 3a596173d..a558ac536 100644 --- a/DSCResources/MSFT_xADServicePrincipalName/MSFT_xADServicePrincipalName.psm1 +++ b/DSCResources/MSFT_xADServicePrincipalName/MSFT_xADServicePrincipalName.psm1 @@ -26,13 +26,15 @@ function Get-TargetResource ) Write-Verbose -Message ($script:localizedData.GetServicePrincipalName -f $ServicePrincipalName) + $spnAccounts = Get-ADObject -Filter { ServicePrincipalName -eq $ServicePrincipalName } -Properties 'SamAccountName' | - Select-Object -ExpandProperty 'SamAccountName' + Select-Object -ExpandProperty 'SamAccountName' if ($spnAccounts.Count -eq 0) { # No SPN found Write-Verbose -Message ($script:localizedData.ServicePrincipalNameAbsent -f $ServicePrincipalName) + $returnValue = @{ Ensure = 'Absent' ServicePrincipalName = $ServicePrincipalName @@ -43,6 +45,7 @@ function Get-TargetResource { # One or more SPN(s) found, return the account name(s) Write-Verbose -Message ($script:localizedData.ServicePrincipalNamePresent -f $ServicePrincipalName, ($spnAccounts -join ';')) + $returnValue = @{ Ensure = 'Present' ServicePrincipalName = $ServicePrincipalName @@ -93,8 +96,10 @@ function Set-TargetResource if ($Ensure -eq 'Present') { - # Throw an exception, if no account was specified or the account does - # not exist. + <# + Throw an exception, if no account was specified or the account does + not exist. + #> if ([String]::IsNullOrEmpty($Account) -or ($null -eq (Get-ADObject -Filter { SamAccountName -eq $Account }))) { throw ($script:localizedData.AccountNotFound -f $Account) @@ -106,18 +111,24 @@ function Set-TargetResource if ($spnAccount.SamAccountName -ne $Account) { Write-Verbose -Message ($script:localizedData.RemoveServicePrincipalName -f $ServicePrincipalName, $spnAccount.SamAccountName) + Set-ADObject -Identity $spnAccount.DistinguishedName -Remove @{ ServicePrincipalName = $ServicePrincipalName } } } - # Add the SPN to the target account. Use Get-ADObject to get the target - # object filtered by SamAccountName. Set-ADObject does not support the - # field SamAccountName as Identifier. + <# + Add the SPN to the target account. Use Get-ADObject to get the target + object filtered by SamAccountName. Set-ADObject does not support the + field SamAccountName as Identifier. + #> if ($spnAccounts.SamAccountName -notcontains $Account) { Write-Verbose -Message ($script:localizedData.AddServicePrincipalName -f $ServicePrincipalName, $Account) + Get-ADObject -Filter { SamAccountName -eq $Account } | - Set-ADObject -Add @{ ServicePrincipalName = $ServicePrincipalName } + Set-ADObject -Add @{ + ServicePrincipalName = $ServicePrincipalName + } } } @@ -127,6 +138,7 @@ function Set-TargetResource foreach ($spnAccount in $spnAccounts) { Write-Verbose -Message ($script:localizedData.RemoveServicePrincipalName -f $ServicePrincipalName, $spnAccount.SamAccountName) + Set-ADObject -Identity $spnAccount.DistinguishedName -Remove @{ ServicePrincipalName = $ServicePrincipalName } } } @@ -175,7 +187,7 @@ function Test-TargetResource if ($Ensure -eq 'Present') { $desiredConfigurationMatch = $desiredConfigurationMatch -and - $currentConfiguration.Account -eq $Account + $currentConfiguration.Account -eq $Account } if ($desiredConfigurationMatch) diff --git a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 index 6f619b700..79ecfa568 100644 --- a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 +++ b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 @@ -14,7 +14,7 @@ $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_xADUser' # Active Directory user attributes. $adPropertyMap = @( @{ - Parameter = 'CommonName' + Parameter = 'CommonName' ADProperty = 'cn' } @{ @@ -24,7 +24,7 @@ $adPropertyMap = @( Parameter = 'DisplayName' } @{ - Parameter = 'Path' + Parameter = 'Path' ADProperty = 'distinguishedName' } @{ @@ -34,7 +34,7 @@ $adPropertyMap = @( Parameter = 'Initials' } @{ - Parameter = 'Surname' + Parameter = 'Surname' ADProperty = 'sn' } @{ @@ -47,18 +47,18 @@ $adPropertyMap = @( Parameter = 'POBox' } @{ - Parameter = 'City' + Parameter = 'City' ADProperty = 'l' } @{ - Parameter = 'State' + Parameter = 'State' ADProperty = 'st' } @{ Parameter = 'PostalCode' } @{ - Parameter = 'Country' + Parameter = 'Country' ADProperty = 'c' } @{ @@ -71,15 +71,15 @@ $adPropertyMap = @( Parameter = 'Company' } @{ - Parameter = 'Office' + Parameter = 'Office' ADProperty = 'physicalDeliveryOfficeName' } @{ - Parameter = 'JobTitle' + Parameter = 'JobTitle' ADProperty = 'title' } @{ - Parameter = 'EmailAddress' + Parameter = 'EmailAddress' ADProperty = 'mail' } @{ @@ -95,30 +95,30 @@ $adPropertyMap = @( Parameter = 'HomeDrive' } @{ - Parameter = 'HomePage' + Parameter = 'HomePage' ADProperty = 'wWWHomePage' } @{ Parameter = 'ProfilePath' } @{ - Parameter = 'LogonScript' + Parameter = 'LogonScript' ADProperty = 'scriptPath' } @{ - Parameter = 'Notes' + Parameter = 'Notes' ADProperty = 'info' } @{ - Parameter = 'OfficePhone' + Parameter = 'OfficePhone' ADProperty = 'telephoneNumber' } @{ - Parameter = 'MobilePhone' + Parameter = 'MobilePhone' ADProperty = 'mobile' } @{ - Parameter = 'Fax' + Parameter = 'Fax' ADProperty = 'facsimileTelephoneNumber' } @{ @@ -137,19 +137,20 @@ $adPropertyMap = @( Parameter = 'Manager' } @{ - Parameter = 'PasswordNeverExpires' + Parameter = 'PasswordNeverExpires' UseCmdletParameter = $true } @{ - Parameter = 'CannotChangePassword' + Parameter = 'CannotChangePassword' UseCmdletParameter = $true } @{ - Parameter = 'ChangePasswordAtLogon' + Parameter = 'ChangePasswordAtLogon' UseCmdletParameter = $true } @{ - Parameter = 'TrustedForDelegation' + + Parameter = 'TrustedForDelegation' UseCmdletParameter = $true } @{ @@ -525,7 +526,8 @@ function Get-TargetResource $targetResource['Path'] = Get-ADObjectParentDN -DN $adUser.DistinguishedName } } - elseif (($property.Parameter) -eq 'ServicePrincipalNames') { + elseif (($property.Parameter) -eq 'ServicePrincipalNames') + { $targetResource['ServicePrincipalNames'] = [System.String[]]$adUser.ServicePrincipalNames } elseif (($property.Parameter) -eq 'ChangePasswordAtLogon') { @@ -1350,7 +1352,8 @@ function Set-TargetResource elseif ($PSBoundParameters.$parameter -ne $targetResource.$parameter) { # Find the associated AD property - $adProperty = $adPropertyMap | Where-Object { $_.Parameter -eq $parameter } + $adProperty = $adPropertyMap | + Where-Object { $_.Parameter -eq $parameter } if ([System.String]::IsNullOrEmpty($adProperty)) { diff --git a/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 b/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 index 5039ae90f..1007ee3c0 100644 --- a/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 +++ b/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 @@ -298,124 +298,126 @@ function Test-DscParameterState $keyList = $ValuesToCheck } - $keyList | ForEach-Object -Process { - if (($_ -ne 'Verbose')) - { - if (($CurrentValues.ContainsKey($_) -eq $false) ` - -or ($CurrentValues.$_ -ne $DesiredValues.$_) ` - -or (($DesiredValues.GetType().Name -ne 'CimInstance' -and $DesiredValues.ContainsKey($_) -eq $true) -and ($null -ne $DesiredValues.$_ -and $DesiredValues.$_.GetType().IsArray))) + $keyList | + ForEach-Object -Process { + if (($_ -ne 'Verbose')) { - if ($DesiredValues.GetType().Name -eq 'HashTable' -or ` - $DesiredValues.GetType().Name -eq 'PSBoundParametersDictionary') - { - $checkDesiredValue = $DesiredValues.ContainsKey($_) - } - else + if (($CurrentValues.ContainsKey($_) -eq $false) ` + -or ($CurrentValues.$_ -ne $DesiredValues.$_) ` + -or (($DesiredValues.GetType().Name -ne 'CimInstance' -and $DesiredValues.ContainsKey($_) -eq $true) -and ($null -ne $DesiredValues.$_ -and $DesiredValues.$_.GetType().IsArray))) { - # If DesiredValue is a CimInstance. - $checkDesiredValue = $false - if (([System.Boolean]($DesiredValues.PSObject.Properties.Name -contains $_)) -eq $true) + if ($DesiredValues.GetType().Name -eq 'HashTable' -or ` + $DesiredValues.GetType().Name -eq 'PSBoundParametersDictionary') + { + $checkDesiredValue = $DesiredValues.ContainsKey($_) + } + else { - if ($null -ne $DesiredValues.$_) + # If DesiredValue is a CimInstance. + $checkDesiredValue = $false + if (([System.Boolean]($DesiredValues.PSObject.Properties.Name -contains $_)) -eq $true) { - $checkDesiredValue = $true + if ($null -ne $DesiredValues.$_) + { + $checkDesiredValue = $true + } } } - } - if ($checkDesiredValue) - { - $desiredType = $DesiredValues.$_.GetType() - $fieldName = $_ - if ($desiredType.IsArray -eq $true) + if ($checkDesiredValue) { - if (($CurrentValues.ContainsKey($fieldName) -eq $false) ` - -or ($null -eq $CurrentValues.$fieldName)) + $desiredType = $DesiredValues.$_.GetType() + $fieldName = $_ + if ($desiredType.IsArray -eq $true) { - Write-Verbose -Message ($script:localizedData.PropertyValidationError -f $fieldName) -Verbose - - $returnValue = $false - } - else - { - $arrayCompare = Compare-Object -ReferenceObject $CurrentValues.$fieldName ` - -DifferenceObject $DesiredValues.$fieldName - if ($null -ne $arrayCompare) + if (($CurrentValues.ContainsKey($fieldName) -eq $false) ` + -or ($null -eq $CurrentValues.$fieldName)) { - Write-Verbose -Message ($script:localizedData.PropertiesDoesNotMatch -f $fieldName) -Verbose - - $arrayCompare | ForEach-Object -Process { - Write-Verbose -Message ($script:localizedData.PropertyThatDoesNotMatch -f $_.InputObject, $_.SideIndicator) -Verbose - } + Write-Verbose -Message ($script:localizedData.PropertyValidationError -f $fieldName) -Verbose $returnValue = $false } - } - } - else - { - switch ($desiredType.Name) - { - 'String' + else { - if (-not [System.String]::IsNullOrEmpty($CurrentValues.$fieldName) -or ` - -not [System.String]::IsNullOrEmpty($DesiredValues.$fieldName)) + $arrayCompare = Compare-Object -ReferenceObject $CurrentValues.$fieldName ` + -DifferenceObject $DesiredValues.$fieldName + if ($null -ne $arrayCompare) { - Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` - -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose + Write-Verbose -Message ($script:localizedData.PropertiesDoesNotMatch -f $fieldName) -Verbose + + $arrayCompare | + ForEach-Object -Process { + Write-Verbose -Message ($script:localizedData.PropertyThatDoesNotMatch -f $_.InputObject, $_.SideIndicator) -Verbose + } $returnValue = $false } } - - 'Int32' + } + else + { + switch ($desiredType.Name) { - if (-not ($DesiredValues.$fieldName -eq 0) -or ` - -not ($null -eq $CurrentValues.$fieldName)) + 'String' { - Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` - -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose - - $returnValue = $false + if (-not [System.String]::IsNullOrEmpty($CurrentValues.$fieldName) -or ` + -not [System.String]::IsNullOrEmpty($DesiredValues.$fieldName)) + { + Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` + -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose + + $returnValue = $false + } } - } - { $_ -eq 'Int16' -or $_ -eq 'UInt16' -or $_ -eq 'Single' } - { - if (-not ($DesiredValues.$fieldName -eq 0) -or ` - -not ($null -eq $CurrentValues.$fieldName)) + 'Int32' { - Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` - -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose + if (-not ($DesiredValues.$fieldName -eq 0) -or ` + -not ($null -eq $CurrentValues.$fieldName)) + { + Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` + -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose + + $returnValue = $false + } + } - $returnValue = $false + { $_ -eq 'Int16' -or $_ -eq 'UInt16' -or $_ -eq 'Single' } + { + if (-not ($DesiredValues.$fieldName -eq 0) -or ` + -not ($null -eq $CurrentValues.$fieldName)) + { + Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` + -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose + + $returnValue = $false + } } - } - 'Boolean' - { - if ($CurrentValues.$fieldName -ne $DesiredValues.$fieldName) + 'Boolean' { - Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` - -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose + if ($CurrentValues.$fieldName -ne $DesiredValues.$fieldName) + { + Write-Verbose -Message ($script:localizedData.ValueOfTypeDoesNotMatch ` + -f $desiredType.Name, $fieldName, $($CurrentValues.$fieldName), $($DesiredValues.$fieldName)) -Verbose - $returnValue = $false + $returnValue = $false + } } - } - default - { - Write-Warning -Message ($script:localizedData.UnableToCompareProperty ` - -f $fieldName, $desiredType.Name) + default + { + Write-Warning -Message ($script:localizedData.UnableToCompareProperty ` + -f $fieldName, $desiredType.Name) - $returnValue = $false + $returnValue = $false + } } } } } } } - } return $returnValue } @@ -452,7 +454,7 @@ function Start-ProcessWithTimeout ) $startProcessParameters = @{ - FilePath = $FilePath + FilePath = $FilePath ArgumentList = $ArgumentList PassThru = $true NoNewWindow = $true @@ -1255,7 +1257,7 @@ function Restore-ADCommonObject # If more than one object is returned, we pick the one that was changed last. $restorableObject = Get-ADObject @getAdObjectParams | Sort-Object -Descending -Property 'whenChanged' | - Select-Object -First 1 + Select-Object -First 1 $restoredObject = $null @@ -1575,13 +1577,15 @@ function Compare-ResourcePropertyState if ($PSBoundParameters.ContainsKey('Properties')) { # Filter out the parameters (keys) not specified in Properties - $desiredValuesToRemove = $DesiredValues.Keys | Where-Object -FilterScript { - $_ -notin $Properties - } + $desiredValuesToRemove = $DesiredValues.Keys | + Where-Object -FilterScript { + $_ -notin $Properties + } - $desiredValuesToRemove | ForEach-Object -Process { - $DesiredValues.Remove($_) - } + $desiredValuesToRemove | + ForEach-Object -Process { + $DesiredValues.Remove($_) + } } else { @@ -1589,25 +1593,28 @@ function Compare-ResourcePropertyState Remove any common parameters that might be part of DesiredValues, if it $PSBoundParameters was used to pass the desired values. #> - $commonParametersToRemove = $DesiredValues.Keys | Where-Object -FilterScript { - $_ -in [System.Management.Automation.PSCmdlet]::CommonParameters ` - -or $_ -in [System.Management.Automation.PSCmdlet]::OptionalCommonParameters - } + $commonParametersToRemove = $DesiredValues.Keys | + Where-Object -FilterScript { + $_ -in [System.Management.Automation.PSCmdlet]::CommonParameters ` + -or $_ -in [System.Management.Automation.PSCmdlet]::OptionalCommonParameters + } - $commonParametersToRemove | ForEach-Object -Process { - $DesiredValues.Remove($_) - } + $commonParametersToRemove | + ForEach-Object -Process { + $DesiredValues.Remove($_) + } } # Remove any properties that should be ignored. if ($PSBoundParameters.ContainsKey('IgnoreProperties')) { - $IgnoreProperties | ForEach-Object -Process { - if ($DesiredValues.ContainsKey($_)) - { - $DesiredValues.Remove($_) + $IgnoreProperties | + ForEach-Object -Process { + if ($DesiredValues.ContainsKey($_)) + { + $DesiredValues.Remove($_) + } } - } } $compareTargetResourceStateReturnValue = @() @@ -1699,9 +1706,10 @@ function Test-DscPropertyState { Write-Verbose -Message $script:localizedData.ArrayDoesNotMatch -Verbose - $arrayCompare | ForEach-Object -Process { - Write-Verbose -Message ($script:localizedData.ArrayValueThatDoesNotMatch -f $_.InputObject, $_.SideIndicator) -Verbose - } + $arrayCompare | + ForEach-Object -Process { + Write-Verbose -Message ($script:localizedData.ArrayValueThatDoesNotMatch -f $_.InputObject, $_.SideIndicator) -Verbose + } $returnValue = $false } @@ -1771,7 +1779,8 @@ function Assert-ADPSDrive Write-Verbose -Message $script:localizedData.CreatingNewADPSDrive try { - New-PSDrive -Name AD -PSProvider 'ActiveDirectory' -Root $Root -Scope Script -ErrorAction Stop | Out-Null + New-PSDrive -Name AD -PSProvider 'ActiveDirectory' -Root $Root -Scope Script -ErrorAction 'Stop' | + Out-Null } catch { From f63b18ed4d9d0ed71f6a5c71ecaa0fedf3146e83 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 13:52:43 +0200 Subject: [PATCH 15/29] Add verbose in xADRecycleBin --- DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 | 2 ++ .../MSFT_xADRecycleBin/en-US/MSFT_xADRecycleBin.strings.psd1 | 1 + 2 files changed, 3 insertions(+) diff --git a/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 b/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 index 6635c3f24..f9f5fda45 100644 --- a/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 +++ b/DSCResources/MSFT_xADRecycleBin/MSFT_xADRecycleBin.psm1 @@ -102,6 +102,8 @@ function Set-TargetResource if ($PSCmdlet.ShouldProcess($forest.RootDomain, "Enable Active Directory Recycle Bin")) { + Write-Verbose -Message $script:localizedData.EnablingRecycleBin + Enable-ADOptionalFeature 'Recycle Bin Feature' -Scope ForestOrConfigurationSet ` -Target $forest.RootDomain -Server $forest.DomainNamingMaster ` -Credential $EnterpriseAdministratorCredential ` diff --git a/DSCResources/MSFT_xADRecycleBin/en-US/MSFT_xADRecycleBin.strings.psd1 b/DSCResources/MSFT_xADRecycleBin/en-US/MSFT_xADRecycleBin.strings.psd1 index 21ffe37b0..699344c86 100644 --- a/DSCResources/MSFT_xADRecycleBin/en-US/MSFT_xADRecycleBin.strings.psd1 +++ b/DSCResources/MSFT_xADRecycleBin/en-US/MSFT_xADRecycleBin.strings.psd1 @@ -8,4 +8,5 @@ ConvertFrom-StringData @' ForestFunctionalLevelError = Forest functional level '{0}' does not meet minimum requirement of Windows2008R2Forest or greater. RecycleBinEnabled = Active Directory Recycle Bin is enabled. RecycleBinNotEnabled = Active Directory Recycle Bin is not enabled. + EnablingRecycleBin = Enabling Active Directory Recycle Bin. '@ From d6ea2865c446e4ed302f6dcd9d753fcef1cc6e99 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 13:54:22 +0200 Subject: [PATCH 16/29] Fix typo in xADObjectPermissionEntry.Tests --- Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 b/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 index 30f71bff9..49579e260 100644 --- a/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 +++ b/Tests/Unit/MSFT_xADObjectPermissionEntry.Tests.ps1 @@ -219,7 +219,7 @@ try Context 'When the desired ace is present' { Mock -CommandName 'Get-Acl' -MockWith $mockGetAclPresent - Mock -CommandName 'Set-Acl' Verifiable + Mock -CommandName 'Set-Acl' -Verifiable It 'Should call "Assert-ADPSDrive" to check AD PS Drive is created' { $targetResource = Get-TargetResource @testDefaultParameters -Verbose From 09e41f11d990351c416202afca111debc95678bf Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Fri, 7 Jun 2019 14:19:54 +0200 Subject: [PATCH 17/29] Typ in xWaitForADDomain.Tests --- Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 b/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 index 1a833c8cf..4186f88f2 100644 --- a/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 +++ b/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 @@ -114,7 +114,7 @@ try Mock -CommandName Start-Sleep Mock -CommandName Clear-DnsClientCache {Set-TargetResource @testParams} | Should -Not -Throw - $global:DSCMachineStatus | should -not -be 1 + $global:DSCMachineStatus | Should -Not -Be 1 Assert-MockCalled -CommandName Start-Sleep -Times 0 -Scope It Assert-MockCalled -CommandName Clear-DnsClientCache -Times 0 -Scope It } @@ -122,7 +122,7 @@ try It "Throws exception and does not set `$global:DSCMachineStatus when domain not found after $($testParams.RetryCount) retries when RebootRetryCount is not set" { Mock -CommandName Get-Domain {Set-TargetResource @testParams} | Should -Throw - $global:DSCMachineStatus | should -not -be 1 + $global:DSCMachineStatus | Should -Not -Be 1 } It "Throws exception when domain not found after $($rebootTestParams.RebootRetryCount) reboot retries when RebootRetryCount is exceeded" { @@ -143,7 +143,7 @@ try Mock -CommandName Get-Domain Mock -CommandName Get-Content -MockWith {return 0} {Set-TargetResource @rebootTestParams} | Should -Not -Throw - $global:DSCMachineStatus | should -be 1 + $global:DSCMachineStatus | Should -Be 1 } It "Calls Get-Domain exactly $($testParams.RetryCount) times when domain not found" { From e3646a83fc525dfd114a8d787adf2bcab62047b5 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Thu, 13 Jun 2019 18:46:32 +0200 Subject: [PATCH 18/29] Fix CHANGELOG.md after rebase --- CHANGELOG.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58c85480b..bf38b17b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,7 @@ - Code cleanup. - Changes to xADOrganizationalUnit - Change the description of the property RestoreFromRecycleBin. + - Code cleanup. - Changes to xADUser - Change the description of the property RestoreFromRecycleBin. - Added ServicePrincipalNames property ([issue #153](https://github.com/PowerShell/xActiveDirectory/issues/153)). @@ -97,6 +98,7 @@ setting it to `'Stop'`. - Changes to xADReplicationSiteLink - Fix ADIdentityNotFoundException when creating a new site link. + - Code cleanup. - Changes to xADReplicationSubnet - Remove `{ *Present* | Absent }` from the property schema descriptions which were causing corruption in the Wiki documentation. @@ -107,10 +109,6 @@ - Code cleanup. - Changes to xADForestProperties - Minor style cleanup. -- Changes to xADOrganizationalUnit - - Code cleanup. -- Changes to xADReplicationSiteLink - - Code cleanup. - Changes to xADReplicationSubnet - Code cleanup. - Changes to xADKDSKey From 1c01c35c1f14c4dd779bce25814d350cd91b8afd Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 13:23:15 +0200 Subject: [PATCH 19/29] Fix full stop --- CHANGELOG.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf38b17b7..acb1b362c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,28 +8,28 @@ - Convert-PropertyMapToObjectProperties - Compare-ResourcePropertyState - Test-DscPropertyState - - Move the examples in the README.md to Examples folder - - Fix Script Analyzer rule failures + - Move the examples in the README.md to Examples folder. + - Fix Script Analyzer rule failures. - Opt-in to the following DSC Resource Common Meta Tests: - Common Tests - Custom Script Analyzer Rules - Common Tests - Required Script Analyzer Rules - Common Tests - Flagged Script Analyzer Rules - - Common Tests - Validate Module Files ([Issue #282](https://github.com/PowerShell/xActiveDirectory/issues/282)) - - Common Tests - Validate Script Files ([Issue #283](https://github.com/PowerShell/xActiveDirectory/issues/283)) - - Common Tests - Relative Path Length ([Issue #284](https://github.com/PowerShell/xActiveDirectory/issues/284)) - - Common Tests - Validate Markdown Links ([Issue #280](https://github.com/PowerShell/xActiveDirectory/issues/280)) - - Common Tests - Validate Localization ([Issue #281](https://github.com/PowerShell/xActiveDirectory/issues/281)) - - Common Tests - Validate Example Files ([Issue #279](https://github.com/PowerShell/xActiveDirectory/issues/279)) - - Common Tests - Validate Example Files To Be Published ([Issue #311](https://github.com/PowerShell/xActiveDirectory/issues/311)) - - Move resource descriptions to Wiki using auto-documentation ([Issue #289](https://github.com/PowerShell/xActiveDirectory/issues/289)) + - Common Tests - Validate Module Files ([issue #282](https://github.com/PowerShell/xActiveDirectory/issues/282)) + - Common Tests - Validate Script Files ([issue #283](https://github.com/PowerShell/xActiveDirectory/issues/283)) + - Common Tests - Relative Path Length ([issue #284](https://github.com/PowerShell/xActiveDirectory/issues/284)) + - Common Tests - Validate Markdown Links ([issue #280](https://github.com/PowerShell/xActiveDirectory/issues/280)) + - Common Tests - Validate Localization ([issue #281](https://github.com/PowerShell/xActiveDirectory/issues/281)) + - Common Tests - Validate Example Files ([issue #279](https://github.com/PowerShell/xActiveDirectory/issues/279)) + - Common Tests - Validate Example Files To Be Published ([issue #311](https://github.com/PowerShell/xActiveDirectory/issues/311)) + - Move resource descriptions to Wiki using auto-documentation ([issue #289](https://github.com/PowerShell/xActiveDirectory/issues/289)) - Move helper functions from MSFT_xADCommon to the module - xActiveDirectory.Common ([issue #288](https://github.com/PowerShell/xActiveDirectory/issues/288)) + xActiveDirectory.Common ([issue #288](https://github.com/PowerShell/xActiveDirectory/issues/288)). - Removed helper function `Test-ADDomain` since it was not used. The helper function had design flaws too. - Now the helper function `Test-Members` outputs all the members that are not in desired state when verbose output is enabled. - Update all unit tests to latest unit test template. - - Deleted the obsolete xActiveDirectory_TechNetDocumentation.html file + - Deleted the obsolete xActiveDirectory_TechNetDocumentation.html file. - Added new resource xADObjectEnabledState. This resource should be used to enforce the `Enabled` property of computer accounts. This resource replaces the deprecated `Enabled` property in the resource @@ -53,15 +53,15 @@ if the computer account is created enabled or disabled. - Moved examples from the README.md to separate example files in the Examples folder. - - Fix the RestoreFromRecycleBin Description - - Fix unnecessary cast in `Test-TargetResource` ([Issue #295](https://github.com/PowerShell/xActiveDirectory/issues/295)) + - Fix the RestoreFromRecycleBin description. + - Fix unnecessary cast in `Test-TargetResource` ([issue #295](https://github.com/PowerShell/xActiveDirectory/issues/295)). - Changes to xADGroup - Change the description of the property RestoreFromRecycleBin. - Code cleanup. - Changes to xADObjectPermissionEntry - Change the description of the property IdentityReference. - - Fix failure when applied in the same configuration as xADDomain - - Localize and Improve verbose messaging + - Fix failure when applied in the same configuration as xADDomain. + - Localize and Improve verbose messaging. - Code cleanup. - Changes to xADOrganizationalUnit - Change the description of the property RestoreFromRecycleBin. From c0f0fe4b46df26af043e3f737fc1669840f08da5 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 13:27:39 +0200 Subject: [PATCH 20/29] Fix comment that did not match style guideline --- .../MSFT_xADDomain/MSFT_xADDomain.psm1 | 21 ++++++++++++------- .../MSFT_xADDomainController.psm1 | 2 +- .../MSFT_xADDomainDefaultPasswordPolicy.psm1 | 2 +- .../MSFT_xADOrganizationalUnit.psm1 | 4 ++-- .../xActiveDirectory.Common.psm1 | 14 ++++++------- Tests/Unit/MSFT_xADDomain.Tests.ps1 | 6 +++--- 6 files changed, 27 insertions(+), 22 deletions(-) diff --git a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 index a5a74d630..6959bf884 100644 --- a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 +++ b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 @@ -118,7 +118,7 @@ function Get-TargetResource { if ($isDomainMember) { - ## We're already a domain member, so take the credentials out of the equation + # We're already a domain member, so take the credentials out of the equation Write-Verbose ($script:localizedData.QueryDomainWithLocalCredential -f $domainFQDN) $domain = Get-ADDomain -Identity $domainFQDN -ErrorAction Stop $forest = Get-ADForest -Identity $domain.Forest -ErrorAction Stop @@ -129,9 +129,11 @@ function Get-TargetResource $forest = Get-ADForest -Identity $domain.Forest -Credential $DomainAdministratorCredential -ErrorAction Stop } - ## No need to check whether the node is actually a domain controller. If we don't throw an exception, - ## the domain is already UP - and this resource shouldn't run. Domain controller functionality - ## should be checked by the xADDomainController resource? + <# + No need to check whether the node is actually a domain controller. If we don't throw an exception, + the domain is already UP - and this resource shouldn't run. Domain controller functionality + should be checked by the xADDomainController resource? + #> Write-Verbose ($script:localizedData.DomainFound -f $domain.DnsRoot) $targetResource = @{ @@ -172,7 +174,7 @@ function Get-TargetResource } else { - ## Not sure what's gone on here! + # Not sure what's gone on here! throw $_ } } @@ -250,8 +252,10 @@ function Test-TargetResource $targetResource = Get-TargetResource @PSBoundParameters $isCompliant = $true - ## The Get-Target resource returns .DomainName as the domain's FQDN. Therefore, we - ## need to resolve this before comparison. + <# + The Get-Target resource returns .DomainName as the domain's FQDN. Therefore, we + need to resolve this before comparison. + #> $domainFQDN = Resolve-DomainFQDN -DomainName $DomainName -ParentDomainName $ParentDomainName if ($domainFQDN -ne $targetResource.DomainName) { @@ -359,7 +363,8 @@ function Set-TargetResource # Debug can pause Install-ADDSForest/Install-ADDSDomain, so we remove it. [ref] $null = $PSBoundParameters.Remove('Debug') - ## Not entirely necessary, but run Get-TargetResouece to ensure we raise any pre-flight errors. + + # Not entirely necessary, but run Get-TargetResource to ensure we raise any pre-flight errors. $targetResource = Get-TargetResource @PSBoundParameters $installADDSParams = @{ diff --git a/DSCResources/MSFT_xADDomainController/MSFT_xADDomainController.psm1 b/DSCResources/MSFT_xADDomainController/MSFT_xADDomainController.psm1 index 6da62eb90..91af8a185 100644 --- a/DSCResources/MSFT_xADDomainController/MSFT_xADDomainController.psm1 +++ b/DSCResources/MSFT_xADDomainController/MSFT_xADDomainController.psm1 @@ -433,7 +433,7 @@ function Test-TargetResource $testTargetResourceReturnValue = $false } - ## Check Global Catalog Config + # Check Global Catalog Config if ($PSBoundParameters.ContainsKey('IsGlobalCatalog') -and $existingResource.IsGlobalCatalog -ne $IsGlobalCatalog) { if ($IsGlobalCatalog) diff --git a/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 b/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 index f5a3694b0..888c33c69 100644 --- a/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 +++ b/DSCResources/MSFT_xADDomainDefaultPasswordPolicy/MSFT_xADDomainDefaultPasswordPolicy.psm1 @@ -6,7 +6,7 @@ Import-Module -Name (Join-Path -Path $script:localizationModulePath -ChildPath ' $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_xADDomainDefaultPasswordPolicy' -## List of changeable policy properties +# List of changeable policy properties $mutablePropertyMap = @( @{ Name = 'ComplexityEnabled' diff --git a/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 b/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 index 38d5f67cd..7dcba28a2 100644 --- a/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 +++ b/DSCResources/MSFT_xADOrganizationalUnit/MSFT_xADOrganizationalUnit.psm1 @@ -92,7 +92,7 @@ function Test-TargetResource { if ($Ensure -eq 'Present') { - ## Organizational unit exists + # Organizational unit exists if ([System.String]::IsNullOrEmpty($Description)) { $isCompliant = (($targetResource.Name -eq $Name) -and @@ -124,7 +124,7 @@ function Test-TargetResource } else { - ## Organizational unit does not exist + # Organizational unit does not exist if ($Ensure -eq 'Present') { $isCompliant = $false diff --git a/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 b/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 index 1007ee3c0..fb75b3662 100644 --- a/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 +++ b/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 @@ -669,7 +669,7 @@ function Assert-MemberParameters } #end function Assert-MemberParameters -## Internal function to remove duplicate strings (members) from a string array +# Internal function to remove duplicate strings (members) from a string array function Remove-DuplicateMembers { [CmdletBinding()] @@ -722,25 +722,25 @@ function Test-Members [OutputType([System.Boolean])] param ( - ## Existing array members + # Existing array members [Parameter()] [AllowNull()] [System.String[]] $ExistingMembers, - ## Explicit array members + # Explicit array members [Parameter()] [AllowNull()] [System.String[]] $Members, - ## Compulsory array members + # Compulsory array members [Parameter()] [AllowNull()] [System.String[]] $MembersToInclude, - ## Excluded array members + # Excluded array members [Parameter()] [AllowNull()] [System.String[]] @@ -998,7 +998,7 @@ function Get-ADCommonParameters [System.Management.Automation.SwitchParameter] $PreferCommonName, - ## Catch all to enable splatted $PSBoundParameters + # Catch all to enable splatted $PSBoundParameters [Parameter(ValueFromRemainingArguments)] $RemainingArguments ) @@ -1084,7 +1084,7 @@ function ThrowInvalidArgumentError } #end function ThrowInvalidArgumentError -## Internal function to test site availability +# Internal function to test site availability function Test-ADReplicationSite { [CmdletBinding()] diff --git a/Tests/Unit/MSFT_xADDomain.Tests.ps1 b/Tests/Unit/MSFT_xADDomain.Tests.ps1 index faa9eadb7..4deedfcf4 100644 --- a/Tests/Unit/MSFT_xADDomain.Tests.ps1 +++ b/Tests/Unit/MSFT_xADDomain.Tests.ps1 @@ -132,7 +132,7 @@ try Write-Error -Exception (New-Object System.Security.Authentication.AuthenticationException) } - ## Match operator is case-sensitive! + # Match operator is case-sensitive! { Get-TargetResource @testDefaultParams -DomainName $incorrectDomainName } | Should -Throw 'invalid credentials' } @@ -197,7 +197,7 @@ try DomainNetBIOSName = $correctDomainNetBIOSName } - ## Get-TargetResource returns the domain FQDN for .DomainName + # Get-TargetResource returns the domain FQDN for .DomainName $stubChildDomain = @{ DomainName = "$correctChildDomainName.$parentDomainName" ParentDomainName = $parentDomainName @@ -390,7 +390,7 @@ try Assert-MockCalled -CommandName Install-ADDSForest -ParameterFilter { $DomainMode -eq $testDomainForestMode } -Scope It } - #### ADDSDomain + # ADDSDomain It 'Calls "Install-ADDSDomain" with "NewDomainName" when creating child domain' { Mock -CommandName Install-ADDSDomain -ParameterFilter { $NewDomainName -eq $testDomainName } From b968759bb9e81d4bb4ce0fb4b380ec42e3d97b58 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 13:30:22 +0200 Subject: [PATCH 21/29] Fix if-blocks --- DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 index 6959bf884..f47e768b9 100644 --- a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 +++ b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 @@ -378,18 +378,22 @@ function Set-TargetResource $installADDSParams['DnsDelegationCredential'] = $DnsDelegationCredential $installADDSParams['CreateDnsDelegation'] = $true } + if ($PSBoundParameters.ContainsKey('DatabasePath')) { $installADDSParams['DatabasePath'] = $DatabasePath } + if ($PSBoundParameters.ContainsKey('LogPath')) { $installADDSParams['LogPath'] = $LogPath } + if ($PSBoundParameters.ContainsKey('SysvolPath')) { $installADDSParams['SysvolPath'] = $SysvolPath } + if ($PSBoundParameters.ContainsKey('DomainMode')) { $installADDSParams['DomainMode'] = $DomainMode @@ -402,6 +406,7 @@ function Set-TargetResource $installADDSParams['NewDomainName'] = $DomainName $installADDSParams['ParentDomainName'] = $ParentDomainName $installADDSParams['DomainType'] = 'ChildDomain' + if ($PSBoundParameters.ContainsKey('DomainNetBIOSName')) { $installADDSParams['NewDomainNetbiosName'] = $DomainNetBIOSName @@ -415,10 +420,12 @@ function Set-TargetResource { Write-Verbose -Message ($script:localizedData.CreatingForest -f $DomainName) $installADDSParams['DomainName'] = $DomainName + if ($PSBoundParameters.ContainsKey('DomainNetbiosName')) { $installADDSParams['DomainNetbiosName'] = $DomainNetBIOSName } + if ($PSBoundParameters.ContainsKey('ForestMode')) { $installADDSParams['ForestMode'] = $ForestMode From d06e88322a112747451691210c98c3758495e517 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 13:55:40 +0200 Subject: [PATCH 22/29] Fix named parameters on New-Object --- .../MSFT_xADDomainTrust.psm1 | 8 ++-- .../MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 | 2 +- .../MSFT_xADObjectPermissionEntry.psm1 | 14 ++++--- DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 | 4 +- .../MSFT_xWaitForADDomain.psm1 | 6 +-- .../xActiveDirectory.Common.psm1 | 10 ++--- Tests/Unit/MSFT_xADDomain.Tests.ps1 | 37 +++++++++++++++---- ...T_xADDomainDefaultPasswordPolicy.Tests.ps1 | 24 +++++++++--- Tests/Unit/MSFT_xADGroup.Tests.ps1 | 6 ++- Tests/Unit/MSFT_xADKDSKey.Tests.ps1 | 4 +- .../MSFT_xADManagedServiceAccount.Tests.ps1 | 10 +++-- .../Unit/MSFT_xADOrganizationalUnit.Tests.ps1 | 5 ++- Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 | 11 ++++-- Tests/Unit/xActiveDirectory.Common.Tests.ps1 | 20 +++++----- 14 files changed, 106 insertions(+), 55 deletions(-) diff --git a/DSCResources/MSFT_xADDomainTrust/MSFT_xADDomainTrust.psm1 b/DSCResources/MSFT_xADDomainTrust/MSFT_xADDomainTrust.psm1 index 8c859659d..577632bcc 100644 --- a/DSCResources/MSFT_xADDomainTrust/MSFT_xADDomainTrust.psm1 +++ b/DSCResources/MSFT_xADDomainTrust/MSFT_xADDomainTrust.psm1 @@ -68,11 +68,11 @@ function Get-TargetResource } # Create the target object - $trgDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest, $TargetDomainName, $TargetDomainAdministratorCredential.UserName, $TargetDomainAdministratorCredential.GetNetworkCredential().Password) + $trgDirectoryContext = New-Object -TypeName 'System.DirectoryServices.ActiveDirectory.DirectoryContext' -ArgumentList @($DomainOrForest, $TargetDomainName, $TargetDomainAdministratorCredential.UserName, $TargetDomainAdministratorCredential.GetNetworkCredential().Password) $trgDomain = ([type]"System.DirectoryServices.ActiveDirectory.$DomainOrForest")::"Get$DomainOrForest"($trgDirectoryContext) # Create the source object - $srcDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest, $SourceDomainName) + $srcDirectoryContext = New-Object -TypeName 'System.DirectoryServices.ActiveDirectory.DirectoryContext' -ArgumentList @($DomainOrForest, $SourceDomainName) $srcDomain = ([type]"System.DirectoryServices.ActiveDirectory.$DomainOrForest")::"Get$DomainOrForest"($srcDirectoryContext) # Find trust between source & destination. @@ -266,11 +266,11 @@ function Confirm-ResourceProperties } # Create the target object - $trgDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest, $TargetDomainName, $TargetDomainAdministratorCredential.UserName, $TargetDomainAdministratorCredential.GetNetworkCredential().Password) + $trgDirectoryContext = New-Object -TypeName 'System.DirectoryServices.ActiveDirectory.DirectoryContext' -ArgumentList @($DomainOrForest, $TargetDomainName, $TargetDomainAdministratorCredential.UserName, $TargetDomainAdministratorCredential.GetNetworkCredential().Password) $trgDomain = ([type]"System.DirectoryServices.ActiveDirectory.$DomainOrForest")::"Get$DomainOrForest"($trgDirectoryContext) # Create the source object - $srcDirectoryContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($DomainOrForest, $SourceDomainName) + $srcDirectoryContext = New-Object -TypeName 'System.DirectoryServices.ActiveDirectory.DirectoryContext' -ArgumentList @($DomainOrForest, $SourceDomainName) $srcDomain = ([type]"System.DirectoryServices.ActiveDirectory.$DomainOrForest")::"Get$DomainOrForest"($srcDirectoryContext) # Find trust diff --git a/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 b/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 index 2725a1f6d..08aefa234 100644 --- a/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 +++ b/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 @@ -479,7 +479,7 @@ function Assert-HasDomainAdminRights $User ) - $windowsPrincipal = New-Object -TypeName System.Security.Principal.WindowsPrincipal($User) + $windowsPrincipal = New-Object -TypeName 'System.Security.Principal.WindowsPrincipal' -ArgumentList @($User) $osInfo = Get-CimInstance -ClassName Win32_OperatingSystem Write-Verbose -Message ($script:localizedData.CheckingDomainAdminUserRights -f $User.Name) diff --git a/DSCResources/MSFT_xADObjectPermissionEntry/MSFT_xADObjectPermissionEntry.psm1 b/DSCResources/MSFT_xADObjectPermissionEntry/MSFT_xADObjectPermissionEntry.psm1 index 0dcac252c..e3458e25f 100644 --- a/DSCResources/MSFT_xADObjectPermissionEntry/MSFT_xADObjectPermissionEntry.psm1 +++ b/DSCResources/MSFT_xADObjectPermissionEntry/MSFT_xADObjectPermissionEntry.psm1 @@ -198,12 +198,14 @@ function Set-TargetResource $ntAccount = New-Object -TypeName 'System.Security.Principal.NTAccount' -ArgumentList $IdentityReference - $ace = New-Object -TypeName 'System.DirectoryServices.ActiveDirectoryAccessRule' -ArgumentList $ntAccount, - $ActiveDirectoryRights, - $AccessControlType, - $ObjectType, - $ActiveDirectorySecurityInheritance, - $InheritedObjectType + $ace = New-Object -TypeName 'System.DirectoryServices.ActiveDirectoryAccessRule' -ArgumentList @( + $ntAccount, + $ActiveDirectoryRights, + $AccessControlType, + $ObjectType, + $ActiveDirectorySecurityInheritance, + $InheritedObjectType + ) $acl.AddAccessRule($ace) } diff --git a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 index 79ecfa568..420ecedaf 100644 --- a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 +++ b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 @@ -1525,7 +1525,7 @@ function Test-Password if ($DomainAdministratorCredential) { - $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext( + $principalContext = New-Object -TypeName 'System.DirectoryServices.AccountManagement.PrincipalContext' -ArgumentList @( [System.DirectoryServices.AccountManagement.ContextType]::Domain, $DomainName, $DomainAdministratorCredential.UserName, @@ -1534,7 +1534,7 @@ function Test-Password } else { - $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext( + $principalContext = New-Object -TypeName 'System.DirectoryServices.AccountManagement.PrincipalContext' -ArgumentList @( [System.DirectoryServices.AccountManagement.ContextType]::Domain, $DomainName, $null, diff --git a/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 b/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 index 24e89309d..121214d59 100644 --- a/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 +++ b/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 @@ -1,4 +1,4 @@ -$script:resourceModulePath = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent +$script:resourceModulePath = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent $script:modulesFolderPath = Join-Path -Path $script:resourceModulePath -ChildPath 'Modules' $script:localizationModulePath = Join-Path -Path $script:modulesFolderPath -ChildPath 'xActiveDirectory.Common' @@ -209,11 +209,11 @@ function Get-Domain if ($DomainUserCredential) { - $context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $DomainName, $DomainUserCredential.UserName, $DomainUserCredential.GetNetworkCredential().Password) + $context = New-Object -TypeName 'System.DirectoryServices.ActiveDirectory.DirectoryContext' -ArgumentList @('Domain', $DomainName, $DomainUserCredential.UserName, $DomainUserCredential.GetNetworkCredential().Password) } else { - $context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain',$DomainName) + $context = New-Object -TypeName 'System.DirectoryServices.ActiveDirectory.DirectoryContext' -ArgumentList @('Domain', $DomainName) } try diff --git a/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 b/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 index fb75b3662..9a09221a2 100644 --- a/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 +++ b/Modules/xActiveDirectory.Common/xActiveDirectory.Common.psm1 @@ -705,7 +705,7 @@ function Remove-DuplicateMembers } # Create the output array. - $destination = New-Object -TypeName System.String[] -ArgumentList $destIndex + $destination = New-Object -TypeName 'System.String[]' -ArgumentList $destIndex # Copy only distinct elements from the original array to the destination array. [System.Array]::Copy($Members, $destination, $destIndex) @@ -1055,9 +1055,9 @@ function ThrowInvalidOperationError $ErrorMessage ) - $exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $ErrorMessage + $exception = New-Object -TypeName 'System.InvalidOperationException' -ArgumentList $ErrorMessage $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation - $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $exception, $ErrorId, $errorCategory, $null + $errorRecord = New-Object -TypeName 'System.Management.Automation.ErrorRecord' -ArgumentList @($exception, $ErrorId, $errorCategory, $null) throw $errorRecord } @@ -1077,9 +1077,9 @@ function ThrowInvalidArgumentError $ErrorMessage ) - $exception = New-Object -TypeName System.ArgumentException -ArgumentList $ErrorMessage + $exception = New-Object -TypeName 'System.ArgumentException' -ArgumentList $ErrorMessage $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument - $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $exception, $ErrorId, $errorCategory, $null + $errorRecord = New-Object -TypeName 'System.Management.Automation.ErrorRecord' -ArgumentList @($exception, $ErrorId, $errorCategory, $null) throw $errorRecord } #end function ThrowInvalidArgumentError diff --git a/Tests/Unit/MSFT_xADDomain.Tests.ps1 b/Tests/Unit/MSFT_xADDomain.Tests.ps1 index 4deedfcf4..d4a36fea2 100644 --- a/Tests/Unit/MSFT_xADDomain.Tests.ps1 +++ b/Tests/Unit/MSFT_xADDomain.Tests.ps1 @@ -57,8 +57,16 @@ try $mgmtForestMode = [Microsoft.ActiveDirectory.Management.ADForestMode]::Windows2012R2Forest $domainMode = [Microsoft.DirectoryServices.Deployment.Types.DomainMode]::Win2012R2 $mgmtDomainMode = [Microsoft.ActiveDirectory.Management.ADDomainMode]::Windows2012R2Domain - $testAdminCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) - $invalidCredential = New-Object System.Management.Automation.PSCredential 'Invalid', (ConvertTo-SecureString 'InvalidPassword' -AsPlainText -Force) + + $testAdminCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'DummyUser', + (ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force) + ) + + $invalidCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'Invalid', + (ConvertTo-SecureString -String 'InvalidPassword' -AsPlainText -Force) + ) $testDefaultParams = @{ DomainAdministratorCredential = $testAdminCredential @@ -185,7 +193,10 @@ try $correctDomainNetBIOSName = 'PRESENT' $incorrectDomainName = 'incorrect.com' $parentDomainName = 'parent.com' - $testAdminCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + $testAdminCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'DummyUser', + (ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force) + ) $testDefaultParams = @{ DomainAdministratorCredential = $testAdminCredential @@ -279,10 +290,22 @@ try $testParentDomainName = 'parent.com' $testDomainNetBIOSNameName = 'PRESENT' $testDomainForestMode = 'WinThreshold' - $testAdminCredential = New-Object System.Management.Automation.PSCredential 'Admin', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) - $testSafemodePassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) - $testSafemodeCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testSafemodePassword - $testDelegationCredential = New-Object System.Management.Automation.PSCredential 'Delegation', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + + $testAdminCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'Admin', + (ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force) + ) + + $testSafemodePassword = (ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force) + $testSafemodeCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'Safemode', + $testSafemodePassword + ) + + $testDelegationCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'Delegation', + (ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force) + ) $newForestParams = @{ DomainName = $testDomainName diff --git a/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 b/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 index e81d31ffc..1561f888d 100644 --- a/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 +++ b/Tests/Unit/MSFT_xADDomainDefaultPasswordPolicy.Tests.ps1 @@ -44,8 +44,12 @@ try DomainName = $testDomainName } $testDomainController = 'testserver.contoso.com' - $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) - $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword + + $testPassword = ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force + $testCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'Safemode', + $testPassword + ) $fakePasswordPolicy = @{ ComplexityEnabled = $true @@ -121,8 +125,12 @@ try DomainName = $testDomainName } $testDomainController = 'testserver.contoso.com' - $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) - $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword + + $testPassword = ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force + $testCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'Safemode', + $testPassword + ) $stubPasswordPolicy = @{ ComplexityEnabled = $true @@ -205,8 +213,12 @@ try DomainName = $testDomainName } $testDomainController = 'testserver.contoso.com' - $testPassword = (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) - $testCredential = New-Object System.Management.Automation.PSCredential 'Safemode', $testPassword + + $testPassword = ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force + $testCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'Safemode', + $testPassword + ) $stubPasswordPolicy = @{ ComplexityEnabled = $true diff --git a/Tests/Unit/MSFT_xADGroup.Tests.ps1 b/Tests/Unit/MSFT_xADGroup.Tests.ps1 index 4abb71a3d..010a44e09 100644 --- a/Tests/Unit/MSFT_xADGroup.Tests.ps1 +++ b/Tests/Unit/MSFT_xADGroup.Tests.ps1 @@ -94,7 +94,11 @@ try } $testDomainController = 'TESTDC' - $testCredentials = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + + $testCredentials = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'DummyUser', + (ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force) + ) #region Function Get-TargetResource Describe 'xADGroup\Get-TargetResource' { diff --git a/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 b/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 index aa48aa8ab..78eb09c38 100644 --- a/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 +++ b/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 @@ -49,8 +49,8 @@ try $DeepCopyObject ) - $memStream = New-Object IO.MemoryStream - $formatter = New-Object Runtime.Serialization.Formatters.Binary.BinaryFormatter + $memStream = New-Object -TypeName 'IO.MemoryStream' + $formatter = New-Object -TypeName 'Runtime.Serialization.Formatters.Binary.BinaryFormatter' $formatter.Serialize($memStream,$DeepCopyObject) $memStream.Position = 0 $formatter.Deserialize($memStream) diff --git a/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 b/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 index ed31b6b1e..e44a15e76 100644 --- a/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 +++ b/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 @@ -49,8 +49,8 @@ try $DeepCopyObject ) - $memStream = New-Object IO.MemoryStream - $formatter = New-Object Runtime.Serialization.Formatters.Binary.BinaryFormatter + $memStream = New-Object -TypeName 'IO.MemoryStream' + $formatter = New-Object -TypeName 'Runtime.Serialization.Formatters.Binary.BinaryFormatter' $formatter.Serialize($memStream,$DeepCopyObject) $memStream.Position=0 $formatter.Deserialize($memStream) @@ -58,7 +58,11 @@ try $mockPath = 'OU=Fake,DC=contoso,DC=com' $mockDomainController = 'MockDC' - $mockCredentials = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + + $mockCredentials = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'DummyUser', + (ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force) + ) $mockADUSer = @{ SamAccountName = 'User1' diff --git a/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 b/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 index 34f78237b..3071bfb24 100644 --- a/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 +++ b/Tests/Unit/MSFT_xADOrganizationalUnit.Tests.ps1 @@ -44,7 +44,10 @@ try function Remove-ADOrganizationalUnit { param ($Name, $Credential) } function New-ADOrganizationalUnit { param ($Name, $Credential) } - $testCredential = New-Object System.Management.Automation.PSCredential 'DummyUser', (ConvertTo-SecureString 'DummyPassword' -AsPlainText -Force) + $testCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'DummyUser', + (ConvertTo-SecureString -String 'DummyPassword' -AsPlainText -Force) + ) $testPresentParams = @{ Name = 'TestOU' diff --git a/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 b/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 index 4186f88f2..570e744e6 100644 --- a/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 +++ b/Tests/Unit/MSFT_xWaitForADDomain.Tests.ps1 @@ -39,19 +39,22 @@ try Invoke-TestSetup InModuleScope $script:dscResourceName { - $password = 'Password' | ConvertTo-SecureString -AsPlainText -Force - $DomainUserCredential = New-Object pscredential('Username', $password) + $domainUserCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( + 'Username', + $(ConvertTo-SecureString -String 'Password' -AsPlainText -Force) + ) + $domainName = 'example.com' $testParams = @{ DomainName = $domainName - DomainUserCredential = $DomainUserCredential + DomainUserCredential = $domainUserCredential RetryIntervalSec = 10 RetryCount = 5 } $rebootTestParams = @{ DomainName = $domainName - DomainUserCredential = $DomainUserCredential + DomainUserCredential = $domainUserCredential RetryIntervalSec = 10 RetryCount = 5 RebootRetryCount = 3 diff --git a/Tests/Unit/xActiveDirectory.Common.Tests.ps1 b/Tests/Unit/xActiveDirectory.Common.Tests.ps1 index cd49a2483..9a555b75c 100644 --- a/Tests/Unit/xActiveDirectory.Common.Tests.ps1 +++ b/Tests/Unit/xActiveDirectory.Common.Tests.ps1 @@ -324,8 +324,8 @@ InModuleScope 'xActiveDirectory.Common' { } } - $mockCurrentValues = @{ Example = New-Object -TypeName MockUnknownType } - $mockDesiredValues = @{ Example = New-Object -TypeName MockUnknownType } + $mockCurrentValues = @{ Example = New-Object -TypeName 'MockUnknownType' } + $mockDesiredValues = @{ Example = New-Object -TypeName 'MockUnknownType' } $testParameters = @{ CurrentValues = $mockCurrentValues @@ -477,8 +477,8 @@ InModuleScope 'xActiveDirectory.Common' { $mockErrorMessage = 'Mocked error' $mockExceptionErrorMessage = 'Mocked exception error message' - $mockException = New-Object -TypeName System.Exception -ArgumentList $mockExceptionErrorMessage - $mockErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $mockException, $null, 'InvalidResult', $null + $mockException = New-Object -TypeName 'System.Exception' -ArgumentList $mockExceptionErrorMessage + $mockErrorRecord = New-Object -TypeName 'System.Management.Automation.ErrorRecord' -ArgumentList @($mockException, $null, 'InvalidResult', $null) { New-InvalidResultException -Message $mockErrorMessage -ErrorRecord $mockErrorRecord } | Should -Throw ('System.Exception: {0} ---> System.Exception: {1}' -f $mockErrorMessage, $mockExceptionErrorMessage) } @@ -501,8 +501,8 @@ InModuleScope 'xActiveDirectory.Common' { $mockErrorMessage = 'Mocked error' $mockExceptionErrorMessage = 'Mocked exception error message' - $mockException = New-Object -TypeName System.Exception -ArgumentList $mockExceptionErrorMessage - $mockErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $mockException, $null, 'InvalidResult', $null + $mockException = New-Object -TypeName 'System.Exception' -ArgumentList $mockExceptionErrorMessage + $mockErrorRecord = New-Object -TypeName 'System.Management.Automation.ErrorRecord' -ArgumentList @($mockException, $null, 'InvalidResult', $null) { New-ObjectNotFoundException -Message $mockErrorMessage -ErrorRecord $mockErrorRecord } | Should -Throw ('System.Exception: {0} ---> System.Exception: {1}' -f $mockErrorMessage, $mockExceptionErrorMessage) } @@ -525,8 +525,8 @@ InModuleScope 'xActiveDirectory.Common' { $mockErrorMessage = 'Mocked error' $mockExceptionErrorMessage = 'Mocked exception error message' - $mockException = New-Object -TypeName System.Exception -ArgumentList $mockExceptionErrorMessage - $mockErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $mockException, $null, 'InvalidResult', $null + $mockException = New-Object -TypeName 'System.Exception' -ArgumentList $mockExceptionErrorMessage + $mockErrorRecord = New-Object -TypeName 'System.Management.Automation.ErrorRecord' -ArgumentList @($mockException, $null, 'InvalidResult', $null) { New-InvalidOperationException -Message $mockErrorMessage -ErrorRecord $mockErrorRecord } | Should -Throw ('System.InvalidOperationException: {0} ---> System.Exception: {1}' -f $mockErrorMessage, $mockExceptionErrorMessage) } @@ -1741,8 +1741,8 @@ InModuleScope 'xActiveDirectory.Common' { } $mockValues = @{ - CurrentValue = New-Object -TypeName MockUnknownType - DesiredValue = New-Object -TypeName MockUnknownType + CurrentValue = New-Object -TypeName 'MockUnknownType' + DesiredValue = New-Object -TypeName 'MockUnknownType' } Test-DscPropertyState -Values $mockValues | Should -Be $false From 22b6b620692013df14c0cf3cc406a60a5c996650 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 14:00:01 +0200 Subject: [PATCH 23/29] Fix named parameters on Where-Object --- .../MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 | 4 +- .../MSFT_xADManagedServiceAccount.psm1 | 20 +++++----- DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 | 2 +- Tests/Unit/MSFT_xADKDSKey.Tests.ps1 | 12 +++--- .../MSFT_xADManagedServiceAccount.Tests.ps1 | 40 +++++++++---------- 5 files changed, 38 insertions(+), 40 deletions(-) diff --git a/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 b/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 index 08aefa234..da9c670bb 100644 --- a/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 +++ b/DSCResources/MSFT_xADKDSKey/MSFT_xADKDSKey.psm1 @@ -506,9 +506,7 @@ function Get-ADRootDomainDN { [CmdletBinding()] [OutputType([System.String])] - param - ( - ) + param () $rootDomainDN = (New-Object -TypeName System.DirectoryServices.DirectoryEntry('LDAP://RootDSE')).Get('rootDomainNamingContext') Write-Verbose -Message ($script:localizedData.RetrievedRootDomainDN -f $rootDomainDN) diff --git a/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 b/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 index e89bbbc62..916fcb6eb 100644 --- a/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 +++ b/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 @@ -249,13 +249,13 @@ function Test-TargetResource $PSBoundParameters['MembershipAttribute'] = $MembershipAttribute $compareTargetResourceNonCompliant = Compare-TargetResourceState @PSBoundParameters | - Where-Object { $_.Pass -eq $false } + Where-Object -FilterScript { $_.Pass -eq $false } # Check if Absent, if so then we don't need to propagate any other parameters if ($Ensure -eq 'Absent') { $ensureState = $compareTargetResourceNonCompliant | - Where-Object { $_.Parameter -eq 'Ensure' } + Where-Object -FilterScript { $_.Parameter -eq 'Ensure' } if ($ensureState) { @@ -402,7 +402,7 @@ function Set-TargetResource $compareTargetResource = Compare-TargetResourceState @PSBoundParameters $compareTargetResourceNonCompliant = @($compareTargetResource | - Where-Object { $_.Pass -eq $false }) + Where-Object -FilterScript { $_.Pass -eq $false }) $adServiceAccountParameters = Get-ADCommonParameters @PSBoundParameters $setServiceAccountParameters = $adServiceAccountParameters.Clone() @@ -414,7 +414,7 @@ function Set-TargetResource { $isEnsureNonCompliant = $false if ($compareTargetResourceNonCompliant | - Where-Object { $_.Parameter -eq 'Ensure' }) + Where-Object -FilterScript { $_.Parameter -eq 'Ensure' }) { $isEnsureNonCompliant = $true } @@ -429,7 +429,7 @@ function Set-TargetResource { #region Check if AccountType is compliant $accountTypeState = $compareTargetResourceNonCompliant | - Where-Object { $_.Parameter -eq 'AccountType' } + Where-Object -FilterScript { $_.Parameter -eq 'AccountType' } # Account already exist, need to update parameters that are not in compliance if ($accountTypeState) @@ -450,13 +450,13 @@ function Set-TargetResource # Remove AccountType since we don't want to enumerate down below $compareTargetResourceNonCompliant = @($compareTargetResourceNonCompliant | - Where-Object { $_.Parameter -ne 'AccountType' }) + Where-Object -FilterScript { $_.Parameter -ne 'AccountType' }) #endregion Check if AccountType is compliant #region Check if Path is compliant $isPathNonCompliant = $false if ($compareTargetResourceNonCompliant | - Where-Object { $_.Parameter -eq 'Path' }) + Where-Object -FilterScript { $_.Parameter -eq 'Path' }) { $isPathNonCompliant = $true } @@ -465,7 +465,7 @@ function Set-TargetResource { Write-Verbose -Message ($script:localizedData.MovingManagedServiceAccount -f $ServiceAccountName, $Path) $distinguishedNameObject = $compareTargetResource | - Where-Object { $_.Parameter -eq 'DistinguishedName' } + Where-Object -FilterScript { $_.Parameter -eq 'DistinguishedName' } $moveADObjectParameters['Identity'] = $distinguishedNameObject.Actual @@ -473,7 +473,7 @@ function Set-TargetResource } $compareTargetResourceNonCompliant = @($compareTargetResourceNonCompliant | - Where-Object { $_.Parameter -ne 'Path' }) + Where-Object -FilterScript { $_.Parameter -ne 'Path' }) #endregion Check if Path is compliant #region Check if other parameters are compliant @@ -511,7 +511,7 @@ function Set-TargetResource { $isEnsureNonCompliant = $false if ($compareTargetResourceNonCompliant | - Where-Object { $_.Parameter -eq 'Ensure' }) + Where-Object -FilterScript { $_.Parameter -eq 'Ensure' }) { $isEnsureNonCompliant = $true } diff --git a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 index 420ecedaf..b542b5630 100644 --- a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 +++ b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 @@ -1353,7 +1353,7 @@ function Set-TargetResource { # Find the associated AD property $adProperty = $adPropertyMap | - Where-Object { $_.Parameter -eq $parameter } + Where-Object -FilterScript { $_.Parameter -eq $parameter } if ([System.String]::IsNullOrEmpty($adProperty)) { diff --git a/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 b/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 index 78eb09c38..a464eedbe 100644 --- a/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 +++ b/Tests/Unit/MSFT_xADKDSKey.Tests.ps1 @@ -489,7 +489,7 @@ try $compareTargetResourceResult = Compare-TargetResourceState @compareTargetResourceParametersFuture $testCases = @() # Need to remove parameters that will always be true - $compareTargetResourceResult = $compareTargetResourceResult | Where-Object { + $compareTargetResourceResult = $compareTargetResourceResult | Where-Object -FilterScript { $_.Parameter -ne 'EffectiveTime' -and $_.Parameter -ne 'DistinguishedName' } @@ -549,7 +549,7 @@ try Context -Name "When the system is in the desired state and 'Ensure' is 'Absent'" { It "Should pass when 'Ensure' is set to 'Absent" { $mockKDSRootKeyFutureCompareEnsureAbsent = Copy-ArrayObjects $mockKDSRootKeyFutureCompare - $objectEnsure = $mockKDSRootKeyFutureCompareEnsureAbsent | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockKDSRootKeyFutureCompareEnsureAbsent | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Actual = 'Absent' $objectEnsure.Pass = $true @@ -580,7 +580,7 @@ try $testCases = @() foreach($incorrectParameter in $testIncorrectParameters.GetEnumerator()) { - $objectParameter = $mockKDSRootKeyFutureCompareNotCompliant | Where-Object { $_.Parameter -eq $incorrectParameter.Name } + $objectParameter = $mockKDSRootKeyFutureCompareNotCompliant | Where-Object -FilterScript { $_.Parameter -eq $incorrectParameter.Name } $objectParameter.Expected = $incorrectParameter.Value $objectParameter.Pass = $false @@ -648,7 +648,7 @@ try Context -Name 'When the system is in the desired state and KDS Root Key is Absent' { $mockKDSRootKeyFutureCompareEnsureAbsent = Copy-ArrayObjects $mockKDSRootKeyFutureCompare - $objectEnsure = $mockKDSRootKeyFutureCompareEnsureAbsent | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockKDSRootKeyFutureCompareEnsureAbsent | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Expected = 'Absent' $objectEnsure.Pass = $false @@ -676,7 +676,7 @@ try Context -Name 'When the system is NOT in the desired state and need to remove KDS Root Key' { BeforeEach { $mockKDSRootKeyFutureCompareEnsureAbsent = Copy-ArrayObjects $mockKDSRootKeyFutureCompare - $objectEnsure = $mockKDSRootKeyFutureCompareEnsureAbsent | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockKDSRootKeyFutureCompareEnsureAbsent | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Actual = 'Present' $objectEnsure.Pass = $false @@ -768,7 +768,7 @@ try Context -Name 'When the system is NOT in the desired state and need to add KDS Root Key' { BeforeEach { $mockKDSRootKeyCompareEnsureAbsent = Copy-ArrayObjects $mockKDSRootKeyFutureCompare - $objectEnsure = $mockKDSRootKeyCompareEnsureAbsent | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockKDSRootKeyCompareEnsureAbsent | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Actual = 'Absent' $objectEnsure.Pass = $false diff --git a/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 b/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 index e44a15e76..f171c3c33 100644 --- a/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 +++ b/Tests/Unit/MSFT_xADManagedServiceAccount.Tests.ps1 @@ -663,7 +663,7 @@ try $getTargetResourceResult = Compare-TargetResourceState @testResourceParametersSingleNotCompliant $testCases = @() # Need to remove parameters that will always be true - $getTargetResourceResult = $getTargetResourceResult | Where-Object { + $getTargetResourceResult = $getTargetResourceResult | Where-Object -FilterScript { $_.Parameter -ne 'ServiceAccountName' -and $_.Parameter -ne 'DistinguishedName' -and $_.Parameter -ne 'MembershipAttribute' @@ -750,7 +750,7 @@ try $getTargetResourceResult = Compare-TargetResourceState @testResourceParametersGroup $testCases = @() # Need to remove parameters that will always be true - $getTargetResourceResult = $getTargetResourceResult | Where-Object { + $getTargetResourceResult = $getTargetResourceResult | Where-Object -FilterScript { $_.Parameter -ne 'ServiceAccountName' -and $_.Parameter -ne 'DistinguishedName' -and $_.Parameter -ne 'MembershipAttribute' @@ -793,7 +793,7 @@ try $getTargetResourceResultSAM = Compare-TargetResourceState @testResourceParametersGroupSAM - $membersState = $getTargetResourceResultSAM | Where-Object {$_.Parameter -eq 'Members'} + $membersState = $getTargetResourceResultSAM | Where-Object -FilterScript {$_.Parameter -eq 'Members'} $membersState.Expected | Should -Not -BeExactly $membersState.Actual $membersState.Pass | Should -BeFalse } @@ -808,7 +808,7 @@ try $getTargetResourceResultDN = Compare-TargetResourceState @testResourceParametersGroupDN - $membersState = $getTargetResourceResultDN | Where-Object {$_.Parameter -eq 'Members'} + $membersState = $getTargetResourceResultDN | Where-Object -FilterScript {$_.Parameter -eq 'Members'} $membersState.Expected | Should -Not -BeExactly $membersState.Actual $membersState.Pass | Should -BeFalse } @@ -823,7 +823,7 @@ try $getTargetResourceResultSID = Compare-TargetResourceState @testResourceParametersGroupSID - $membersState = $getTargetResourceResultSID | Where-Object {$_.Parameter -eq 'Members'} + $membersState = $getTargetResourceResultSID | Where-Object -FilterScript {$_.Parameter -eq 'Members'} $membersState.Expected | Should -Not -BeExactly $membersState.Actual $membersState.Pass | Should -BeFalse } @@ -838,7 +838,7 @@ try $getTargetResourceResultGUID = Compare-TargetResourceState @testResourceParametersGroupGUID - $membersState = $getTargetResourceResultGUID | Where-Object {$_.Parameter -eq 'Members'} + $membersState = $getTargetResourceResultGUID | Where-Object -FilterScript {$_.Parameter -eq 'Members'} $membersState.Expected | Should -Not -BeExactly $membersState.Actual $membersState.Pass | Should -BeFalse } @@ -897,7 +897,7 @@ try Context -Name "When the system is in the desired state and 'Ensure' is 'Absent' (Both)" { It "Should pass when 'Ensure' is set to 'Absent" { $mockCompareSingleServiceAccountEnsureAbsent = $mockCompareSingleServiceAccount.Clone() - $objectEnsure = $mockCompareSingleServiceAccountEnsureAbsent | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockCompareSingleServiceAccountEnsureAbsent | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Actual = 'Absent' $objectEnsure.Pass = $true @@ -931,7 +931,7 @@ try $testCases = @() foreach($incorrectParameter in $testIncorrectParameters.GetEnumerator()) { - $objectParameter = $mockCompareSingleServiceAccountNotCompliant | Where-Object { $_.Parameter -eq $incorrectParameter.Name } + $objectParameter = $mockCompareSingleServiceAccountNotCompliant | Where-Object -FilterScript { $_.Parameter -eq $incorrectParameter.Name } $objectParameter.Expected = $incorrectParameter.Value $objectParameter.Pass = $false @@ -983,7 +983,7 @@ try $testCases = @() foreach($incorrectParameter in $testIncorrectParameters.GetEnumerator()) { - $objectParameter = $mockCompareGroupServiceAccountNotCompliant | Where-Object { $_.Parameter -eq $incorrectParameter.Name } + $objectParameter = $mockCompareGroupServiceAccountNotCompliant | Where-Object -FilterScript { $_.Parameter -eq $incorrectParameter.Name } $objectParameter.Expected = $incorrectParameter.Value $objectParameter.Pass = $false @@ -1133,7 +1133,7 @@ try Context -Name "When the system is in the desired state and 'Ensure' is 'Absent' (Both)" { $mockCompareSingleServiceAccountEnsureAbsent = $mockCompareSingleServiceAccount.Clone() - $objectEnsure = $mockCompareSingleServiceAccountEnsureAbsent | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockCompareSingleServiceAccountEnsureAbsent | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Actual = 'Absent' $objectEnsure.Pass = $true @@ -1167,7 +1167,7 @@ try $mockCompareSingleServiceAccountNotCompliantEnsure = Copy-ArrayObjects $mockCompareSingleServiceAccount #region Incorrect Path setup - $objectPath = $mockCompareSingleServiceAccountNotCompliantPath | Where-Object {$_.Parameter -eq 'Path'} + $objectPath = $mockCompareSingleServiceAccountNotCompliantPath | Where-Object -FilterScript {$_.Parameter -eq 'Path'} $objectPath.Expected = 'WrongPath' $objectPath.Pass = $false @@ -1203,7 +1203,7 @@ try foreach($incorrectParameter in $testIncorrectParameters.GetEnumerator()) { $objectParameter = $mockCompareSingleServiceAccountNotCompliantOtherParameters | - Where-Object { $_.Parameter -eq $incorrectParameter.Name } + Where-Object -FilterScript { $_.Parameter -eq $incorrectParameter.Name } $objectParameter.Expected = $incorrectParameter.Value $objectParameter.Pass = $false @@ -1245,7 +1245,7 @@ try } #region Incorrect Account type setup - $objectAccountType = $mockCompareSingleServiceAccountNotCompliantAccountType | Where-Object {$_.Parameter -eq 'AccountType'} + $objectAccountType = $mockCompareSingleServiceAccountNotCompliantAccountType | Where-Object -FilterScript {$_.Parameter -eq 'AccountType'} $objectAccountType.Expected = 'Group' $objectAccountType.Pass = $false @@ -1291,7 +1291,7 @@ try } #region Incorrect Ensure setup - $objectEnsure = $mockCompareSingleServiceAccountNotCompliantEnsure | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockCompareSingleServiceAccountNotCompliantEnsure | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Expected = 'Absent' $objectEnsure.Pass = $false @@ -1327,7 +1327,7 @@ try $mockCompareGroupServiceAccountNotCompliantEnsure = Copy-ArrayObjects $mockCompareGroupServiceAccount #region Incorrect Path setup - $objectPath = $mockCompareGroupServiceAccountNotCompliantPath | Where-Object {$_.Parameter -eq 'Path'} + $objectPath = $mockCompareGroupServiceAccountNotCompliantPath | Where-Object -FilterScript {$_.Parameter -eq 'Path'} $objectPath.Expected = 'WrongPath' $objectPath.Pass = $false @@ -1365,7 +1365,7 @@ try foreach($incorrectParameter in $testIncorrectParameters.GetEnumerator()) { $objectParameter = $mockCompareGroupServiceAccountNotCompliantOtherParameters | - Where-Object { $_.Parameter -eq $incorrectParameter.Name } + Where-Object -FilterScript { $_.Parameter -eq $incorrectParameter.Name } $objectParameter.Expected = $incorrectParameter.Value $objectParameter.Pass = $false @@ -1408,7 +1408,7 @@ try } #region Incorrect Account type setup - $objectAccountType = $mockCompareGroupServiceAccountNotCompliantAccountType | Where-Object {$_.Parameter -eq 'AccountType'} + $objectAccountType = $mockCompareGroupServiceAccountNotCompliantAccountType | Where-Object -FilterScript {$_.Parameter -eq 'AccountType'} $objectAccountType.Expected = 'Single' $objectAccountType.Pass = $false @@ -1453,7 +1453,7 @@ try } #region Incorrect Ensure setup - $objectEnsure = $mockCompareGroupServiceAccountNotCompliantEnsure | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockCompareGroupServiceAccountNotCompliantEnsure | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Expected = 'Absent' $objectEnsure.Pass = $false @@ -1486,7 +1486,7 @@ try $mockCompareSingleServiceAccountNotEnsure = Copy-ArrayObjects $mockCompareSingleServiceAccount #region Incorrect Ensure setup - $objectEnsure = $mockCompareSingleServiceAccountNotEnsure | Where-Object {$_.Parameter -eq 'Ensure'} + $objectEnsure = $mockCompareSingleServiceAccountNotEnsure | Where-Object -FilterScript {$_.Parameter -eq 'Ensure'} $objectEnsure.Expected = 'Present' $objectEnsure.Actual = 'Absent' $objectEnsure.Pass = $false @@ -1524,7 +1524,7 @@ try $mockCompareSingleServiceAccountNotCompliantPath = Copy-ArrayObjects $mockCompareSingleServiceAccount #region Incorrect Path setup - $objectPath = $mockCompareSingleServiceAccountNotCompliantPath | Where-Object {$_.Parameter -eq 'Path'} + $objectPath = $mockCompareSingleServiceAccountNotCompliantPath | Where-Object -FilterScript {$_.Parameter -eq 'Path'} $objectPath.Expected = 'WrongPath' $objectPath.Pass = $false From 08c7704afd08b671471db173aa506ad2723d3dbc Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 14:03:24 +0200 Subject: [PATCH 24/29] Remove semi-colon from missed file --- .../MSFT_xADManagedServiceAccount.psm1 | 1 + Tests/Unit/MSFT_xADGroup.Tests.ps1 | 96 +++++++++---------- 2 files changed, 49 insertions(+), 48 deletions(-) diff --git a/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 b/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 index 916fcb6eb..abb67fe34 100644 --- a/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 +++ b/DSCResources/MSFT_xADManagedServiceAccount/MSFT_xADManagedServiceAccount.psm1 @@ -413,6 +413,7 @@ function Set-TargetResource if ($Ensure -eq 'Present') { $isEnsureNonCompliant = $false + if ($compareTargetResourceNonCompliant | Where-Object -FilterScript { $_.Parameter -eq 'Ensure' }) { diff --git a/Tests/Unit/MSFT_xADGroup.Tests.ps1 b/Tests/Unit/MSFT_xADGroup.Tests.ps1 index 010a44e09..dd9bec879 100644 --- a/Tests/Unit/MSFT_xADGroup.Tests.ps1 +++ b/Tests/Unit/MSFT_xADGroup.Tests.ps1 @@ -105,17 +105,17 @@ try Mock -CommandName Assert-Module -ParameterFilter { $ModuleName -eq 'ActiveDirectory' } It 'Calls "Assert-Module" to check AD module is installed' { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember {return @($fakeADUser1, $fakeADUser2) } - $result = Get-TargetResource @testPresentParams; # -DomainName $correctDomainName + $result = Get-TargetResource @testPresentParams Assert-MockCalled -CommandName Assert-Module -ParameterFilter { $ModuleName -eq 'ActiveDirectory' } -Scope It } It "Returns 'Ensure' is 'Present' when group exists" { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } (Get-TargetResource @testPresentParams).Ensure | Should -Be 'Present' } @@ -128,8 +128,8 @@ try It "Calls 'Get-ADGroup' with 'Server' parameter when 'DomainController' specified" { - Mock -CommandName Get-ADGroup -ParameterFilter { $Server -eq $testDomainController } -MockWith { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup -ParameterFilter { $Server -eq $testDomainController } -MockWith { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } Get-TargetResource @testPresentParams -DomainController $testDomainController @@ -137,8 +137,8 @@ try } It "Calls 'Get-ADGroup' with 'Credential' parameter when specified" { - Mock -CommandName Get-ADGroup -ParameterFilter { $Credential -eq $testCredentials } -MockWith { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup -ParameterFilter { $Credential -eq $testCredentials } -MockWith { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } Get-TargetResource @testPresentParams -Credential $testCredentials @@ -146,8 +146,8 @@ try } It "Calls 'Get-ADGroupMember' with 'Server' parameter when 'DomainController' specified" { - Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember -ParameterFilter { $Server -eq $testDomainController } -MockWith { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember -ParameterFilter { $Server -eq $testDomainController } -MockWith { return @($fakeADUser1, $fakeADUser2) } Get-TargetResource @testPresentParams -DomainController $testDomainController @@ -155,8 +155,8 @@ try } It "Calls 'Get-ADGroupMember' with 'Credential' parameter when specified" { - Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember -ParameterFilter { $Credential -eq $testCredentials } -MockWith { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember -ParameterFilter { $Credential -eq $testCredentials } -MockWith { return @($fakeADUser1, $fakeADUser2) } Get-TargetResource @testPresentParams -Credential $testCredentials @@ -173,8 +173,8 @@ try foreach ($attribute in @('SamAccountName','DistinguishedName','ObjectGUID','SID')) { It "Passes when group 'Members' match using '$attribute'" { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser1.$attribute, $fakeADUser2.$attribute -MembershipAttribute $attribute @@ -182,8 +182,8 @@ try } It "Fails when group membership counts do not match using '$attribute'" { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1) } $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser2.$attribute, $fakeADUser3.$attribute -MembershipAttribute $attribute @@ -191,8 +191,8 @@ try } It "Fails when group 'Members' do not match using '$attribute'" { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } $targetResource = Test-TargetResource @testPresentParams -Members $fakeADUser2.$attribute, $fakeADUser3.$attribute -MembershipAttribute $attribute @@ -200,8 +200,8 @@ try } It "Passes when specified 'MembersToInclude' match using '$attribute'" { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } $targetResource = Test-TargetResource @testPresentParams -MembersToInclude $fakeADUser2.$attribute -MembershipAttribute $attribute @@ -209,8 +209,8 @@ try } It "Fails when specified 'MembersToInclude' are missing using '$attribute'" { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } $targetResource = Test-TargetResource @testPresentParams -MembersToInclude $fakeADUser3.$attribute -MembershipAttribute $attribute @@ -218,8 +218,8 @@ try } It "Passes when specified 'MembersToExclude' are missing using '$attribute'" { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } $targetResource = Test-TargetResource @testPresentParams -MembersToExclude $fakeADUser3.$attribute -MembershipAttribute $attribute @@ -227,8 +227,8 @@ try } It "Fails when when specified 'MembersToExclude' match using '$attribute'" { - Mock -CommandName Get-ADGroup { return $fakeADGroup; } - Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroup { return $fakeADGroup } + Mock -CommandName Get-ADGroupMember { return @($fakeADUser1, $fakeADUser2) } $targetResource = Test-TargetResource @testPresentParams -MembersToExclude $fakeADUser2.$attribute -MembershipAttribute $attribute @@ -341,7 +341,7 @@ try It "Calls 'New-ADGroup' when 'Ensure' is 'Present' and the group does not exist" { Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Set-TargetResource @testPresentParams @@ -417,7 +417,7 @@ try Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup Mock -CommandName Add-ADCommonGroupMember - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Set-TargetResource @testPresentParams -Members @($fakeADUser1.SamAccountName, $fakeADUser2.SamAccountName) @@ -428,7 +428,7 @@ try Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup Mock -CommandName Add-ADCommonGroupMember - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Get-DomainName -MockWith { return 'contoso.com' } Mock -CommandName Get-ADDomainNameFromDistinguishedName -MockWith { return 'contoso.com' } Mock -CommandName Write-Verbose -ParameterFilter { $Message -and $Message -match 'Group membership objects are in .* different AD Domains.'} @@ -444,7 +444,7 @@ try Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup Mock -CommandName Add-ADCommonGroupMember - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Get-DomainName -MockWith {return 'contoso.com'} Mock -CommandName Get-ADDomainNameFromDistinguishedName -MockWith { param ( @@ -475,7 +475,7 @@ try Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup Mock -CommandName Add-ADCommonGroupMember - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Set-TargetResource @testPresentParams -MembersToInclude @($fakeADUser1.SamAccountName, $fakeADUser2.SamAccountName) @@ -498,9 +498,9 @@ try } It "Resets group membership when 'Ensure' is 'Present' and 'Members' is incorrect" { - Mock -CommandName Get-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName Get-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Set-ADGroup - Mock -CommandName Get-ADGroupMember -MockWith { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroupMember -MockWith { return @($fakeADUser1, $fakeADUser2) } Mock -CommandName Add-ADCommonGroupMember Mock -CommandName Remove-ADGroupMember @@ -511,7 +511,7 @@ try } It "Does not reset group membership when 'Ensure' is 'Present' and existing group is empty" { - Mock -CommandName Get-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName Get-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Set-ADGroup Mock -CommandName Get-ADGroupMember Mock -CommandName Remove-ADGroupMember @@ -522,9 +522,9 @@ try } It "Removes members when 'Ensure' is 'Present' and 'MembersToExclude' is incorrect" { - Mock -CommandName Get-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName Get-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Set-ADGroup - Mock -CommandName Get-ADGroupMember -MockWith { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroupMember -MockWith { return @($fakeADUser1, $fakeADUser2) } Mock -CommandName Remove-ADGroupMember Set-TargetResource @testPresentParams -MembersToExclude $fakeADuser1.SamAccountName @@ -533,9 +533,9 @@ try } It "Adds members when 'Ensure' is 'Present' and 'MembersToInclude' is incorrect" { - Mock -CommandName Get-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName Get-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Set-ADGroup - Mock -CommandName Get-ADGroupMember -MockWith { return @($fakeADUser1, $fakeADUser2); } + Mock -CommandName Get-ADGroupMember -MockWith { return @($fakeADUser1, $fakeADUser2) } Mock -CommandName Add-ADCommonGroupMember Set-TargetResource @testPresentParams -MembersToInclude $fakeADuser3.SamAccountName @@ -544,7 +544,7 @@ try } It "Removes group when 'Ensure' is 'Absent' and group exists" { - Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup; } + Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup } Mock -CommandName Remove-ADGroup Set-TargetResource @testAbsentParams @@ -553,8 +553,8 @@ try } It "Calls 'Set-ADGroup' with credentials when 'Ensure' is 'Present' and the group exists (#106)" { - Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup; } - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName Get-ADGroup -MockWith { return $fakeADGroup } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Get-ADGroupMember Mock -CommandName Set-ADGroup -ParameterFilter { $Credential -eq $testCredentials } @@ -566,7 +566,7 @@ try It "Calls 'Set-ADGroup' with credentials when 'Ensure' is 'Present' and the group does not exist (#106)" { Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup -ParameterFilter { $Credential -eq $testCredentials } - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Set-TargetResource @testPresentParams -Credential $testCredentials @@ -656,8 +656,8 @@ try $restoreParam.RestoreFromRecycleBin = $true Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } - Mock -CommandName Restore-ADCommonObject -MockWith { return [PSCustomObject] $fakeADGroup;} + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } + Mock -CommandName Restore-ADCommonObject -MockWith { return [PSCustomObject] $fakeADGroup} Set-TargetResource @restoreParam @@ -671,7 +671,7 @@ try $restoreParam.RestoreFromRecycleBin = $true Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Restore-ADCommonObject Set-TargetResource @restoreParam @@ -685,10 +685,10 @@ try $restoreParam.RestoreFromRecycleBin = $true Mock -CommandName Get-ADGroup -MockWith { throw New-Object Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException } Mock -CommandName Set-ADGroup - Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup; } + Mock -CommandName New-ADGroup -MockWith { return [PSCustomObject] $fakeADGroup } Mock -CommandName Restore-ADCommonObject -MockWith { throw (New-Object -TypeName System.InvalidOperationException)} - {Set-TargetResource @restoreParam;} | Should -Throw + {Set-TargetResource @restoreParam} | Should -Throw Assert-MockCalled -CommandName Restore-AdCommonObject -Scope It Assert-MockCalled -CommandName New-ADGroup -Scope It -Exactly -Times 0 From 0b984f6a63eb2d7eedc190db387fc5c0f5deeca5 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 14:31:35 +0200 Subject: [PATCH 25/29] Fixed missed comment block --- DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 index f47e768b9..c8056d59d 100644 --- a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 +++ b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 @@ -438,8 +438,10 @@ function Set-TargetResource 'Finished' | Out-File -FilePath (Get-TrackingFilename -DomainName $DomainName) -Force - # Signal to the LCM to reboot the node to compensate for the one we - # suppressed from Install-ADDSForest/Install-ADDSDomain + <# + Signal to the LCM to reboot the node to compensate for the one we + suppressed from Install-ADDSForest/Install-ADDSDomain. + #> $global:DSCMachineStatus = 1 } #end function Set-TargetResource From b1b614795f5b4a6d6a87786e597c2d221b6f7f55 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 14:43:00 +0200 Subject: [PATCH 26/29] Remove BOM from file --- DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 b/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 index 121214d59..a724c33c9 100644 --- a/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 +++ b/DSCResources/MSFT_xWaitForADDomain/MSFT_xWaitForADDomain.psm1 @@ -1,4 +1,4 @@ -$script:resourceModulePath = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent +$script:resourceModulePath = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent $script:modulesFolderPath = Join-Path -Path $script:resourceModulePath -ChildPath 'Modules' $script:localizationModulePath = Join-Path -Path $script:modulesFolderPath -ChildPath 'xActiveDirectory.Common' From b63859389f3ffd5d4acf1243db23c63c1eb08411 Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 14:49:26 +0200 Subject: [PATCH 27/29] Fix review comments at r3 --- DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 | 3 ++- DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 index c8056d59d..c664e423f 100644 --- a/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 +++ b/DSCResources/MSFT_xADDomain/MSFT_xADDomain.psm1 @@ -123,7 +123,8 @@ function Get-TargetResource $domain = Get-ADDomain -Identity $domainFQDN -ErrorAction Stop $forest = Get-ADForest -Identity $domain.Forest -ErrorAction Stop } - else { + else + { Write-Verbose ($script:localizedData.QueryDomainWithCredential -f $domainFQDN) $domain = Get-ADDomain -Identity $domainFQDN -Credential $DomainAdministratorCredential -ErrorAction Stop $forest = Get-ADForest -Identity $domain.Forest -Credential $DomainAdministratorCredential -ErrorAction Stop diff --git a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 index b542b5630..b3aad6443 100644 --- a/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 +++ b/DSCResources/MSFT_xADUser/MSFT_xADUser.psm1 @@ -149,7 +149,6 @@ $adPropertyMap = @( UseCmdletParameter = $true } @{ - Parameter = 'TrustedForDelegation' UseCmdletParameter = $true } @@ -530,12 +529,14 @@ function Get-TargetResource { $targetResource['ServicePrincipalNames'] = [System.String[]]$adUser.ServicePrincipalNames } - elseif (($property.Parameter) -eq 'ChangePasswordAtLogon') { + elseif (($property.Parameter) -eq 'ChangePasswordAtLogon') + { if ($adUser.pwdlastset -eq 0) { $targetResource['ChangePasswordAtLogon'] = $true } - else { + else + { $targetResource['ChangePasswordAtLogon'] = $false } } From 006e8368596b433eeefdd32e5f5619ba04f3760b Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sat, 15 Jun 2019 15:21:44 +0200 Subject: [PATCH 28/29] Fix Pester syntax in recent merges --- Tests/Unit/MSFT_xADUser.Tests.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/Unit/MSFT_xADUser.Tests.ps1 b/Tests/Unit/MSFT_xADUser.Tests.ps1 index 5cf8587bc..05e83dd2d 100644 --- a/Tests/Unit/MSFT_xADUser.Tests.ps1 +++ b/Tests/Unit/MSFT_xADUser.Tests.ps1 @@ -292,7 +292,7 @@ try return $invalidADUser } - Test-TargetResource @testValidPresentParams | Should Be $false + Test-TargetResource @testValidPresentParams | Should -Be $false } It "Should pass when user account '$testParameter' is false matches AD account property" { @@ -305,7 +305,7 @@ try return $validADUser } - Test-TargetResource @testValidPresentParams | Should Be $true + Test-TargetResource @testValidPresentParams | Should -Be $true } It "Should fail when user account '$testParameter' is false and does not match AD account property value" { From acc3c780e5249d4647e37892ec73d77f97da4e4d Mon Sep 17 00:00:00 2001 From: Johan Ljunggren Date: Sun, 16 Jun 2019 11:06:28 +0200 Subject: [PATCH 29/29] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index acb1b362c..476a2bab6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,10 +77,12 @@ - Suppressing the Script Analyzer rule `PSAvoidGlobalVars` since the resource is using the `$global:DSCMachineStatus` variable to trigger a reboot. + - Code cleanup. - Changes to xADDomain - Suppressing the Script Analyzer rule `PSAvoidGlobalVars` since the resource is using the `$global:DSCMachineStatus` variable to trigger a reboot. + - Code cleanup. - Changes to xADDomainTrust - Replaced New-TerminatingError with Standard Function. - Code cleanup.