diff --git a/CHANGELOG.md b/CHANGELOG.md index d980202b63..1bc1efa63e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ FIXES [#5634](https://github.com/microsoft/Microsoft365DSC/issues/5634) * M365DSCTelemetryEngine * Report LCM details only if running as administrator. +* MISC + * Export Performance Improvements + Implements the changes described in [#5615](https://github.com/microsoft/Microsoft365DSC/issues/5615) # 1.25.115.1 diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAdministrativeUnit/MSFT_AADAdministrativeUnit.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAdministrativeUnit/MSFT_AADAdministrativeUnit.psm1 index 6287779158..807a436a05 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAdministrativeUnit/MSFT_AADAdministrativeUnit.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAdministrativeUnit/MSFT_AADAdministrativeUnit.psm1 @@ -84,64 +84,58 @@ function Get-TargetResource ) try { - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - } - catch - { - Write-Verbose -Message ($_) - } - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullResult = $PSBoundParameters - $nullResult.Ensure = 'Absent' - try - { - $getValue = $null - #region resource generator code - if (-not [string]::IsNullOrEmpty($Id)) + if (-not $Script:exportedInstance) { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) + try { - $getValue = $Script:exportedInstances | Where-Object -FilterScript { $_.Id -eq $Id } + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters } - else + catch + { + Write-Verbose -Message ($_) + } + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullResult = $PSBoundParameters + $nullResult.Ensure = 'Absent' + + $getValue = $null + #region resource generator code + if (-not [string]::IsNullOrEmpty($Id)) { $getValue = Get-MgBetaDirectoryAdministrativeUnit -AdministrativeUnitId $Id -ErrorAction SilentlyContinue } - } - if ($null -eq $getValue -and -not [string]::IsNullOrEmpty($DisplayName)) - { - Write-Verbose -Message "Could not find an Azure AD Administrative Unit by Id, trying by DisplayName {$DisplayName}" - if (-Not [string]::IsNullOrEmpty($DisplayName)) + if ($null -eq $getValue -and -not [string]::IsNullOrEmpty($DisplayName)) { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $getValue = $Script:exportedInstances | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } - } - else + Write-Verbose -Message "Could not find an Azure AD Administrative Unit by Id, trying by DisplayName {$DisplayName}" + if (-Not [string]::IsNullOrEmpty($DisplayName)) { $getValue = Get-MgBetaDirectoryAdministrativeUnit -Filter "DisplayName eq '$DisplayName'" -ErrorAction Stop } } + #endregion + if ($null -eq $getValue) + { + Write-Verbose -Message "Could not find an Azure AD Administrative Unit with DisplayName {$DisplayName}" + return $nullResult + } } - #endregion - if ($null -eq $getValue) + else { - Write-Verbose -Message "Could not find an Azure AD Administrative Unit with DisplayName {$DisplayName}" - return $nullResult + $getValue = $Script:exportedInstance } $Id = $getValue.Id Write-Verbose -Message "An Azure AD Administrative Unit with Id {$Id} and DisplayName {$DisplayName} was found." @@ -1099,6 +1093,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $config $Results = Get-TargetResource @Params if ($null -ne $Results.ScopedRoleMembers) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADApplication/MSFT_AADApplication.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADApplication/MSFT_AADApplication.psm1 index fd8647a090..d38ad0c241 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADApplication/MSFT_AADApplication.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADApplication/MSFT_AADApplication.psm1 @@ -129,393 +129,383 @@ function Get-TargetResource [System.String[]] $AccessTokens ) - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters + try + { + if (-not $Script:exportedInstance) + { + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters - Write-Verbose -Message 'Getting configuration of Azure AD Application' + Write-Verbose -Message 'Getting configuration of Azure AD Application' - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - $AADApp = $null - try - { - try - { - if (-not [System.String]::IsNullOrEmpty($AppId)) + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + $AADApp = $null + + try { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $AADApp = $Script:exportedInstances | Where-Object -FilterScript { $_.Id -eq $AppId } - } - else + if (-not [System.String]::IsNullOrEmpty($AppId)) { $AADApp = Get-MgBetaApplication -Filter "AppId eq '$AppId'" } } - } - catch - { - Write-Verbose -Message "Could not retrieve AzureAD Application by Application ID {$AppId}" - } - - if ($null -eq $AADApp) - { - Write-Verbose -Message "Attempting to retrieve Azure AD Application by DisplayName {$DisplayName}" - - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) + catch { - $AADApp = $Script:exportedInstances | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } + Write-Verbose -Message "Could not retrieve AzureAD Application by Application ID {$AppId}" } - else + + if ($null -eq $AADApp) { + Write-Verbose -Message "Attempting to retrieve Azure AD Application by DisplayName {$DisplayName}" $AADApp = [Array](Get-MgBetaApplication -Filter "DisplayName eq '$($DisplayName)'") } + if ($null -ne $AADApp -and $AADApp.Count -gt 1) + { + Throw "Multiple AAD Apps with the Displayname $($DisplayName) exist in the tenant." + } + elseif ($null -eq $AADApp) + { + Write-Verbose -Message 'Could not retrieve and instance of the Azure AD App in the Get-TargetResource function.' + return $nullReturn + } } - if ($null -ne $AADApp -and $AADApp.Count -gt 1) + else { - Throw "Multiple AAD Apps with the Displayname $($DisplayName) exist in the tenant." + $AADApp = $Script:exportedInstance } - elseif ($null -eq $AADApp) + Write-Verbose -Message 'An instance of Azure AD App was retrieved.' + + $AADBetaApp = Get-MgBetaApplication -Property 'id,displayName,appId,authenticationBehaviors,additionalProperties' -ApplicationId $AADApp.Id -ErrorAction SilentlyContinue + $AADAppKeyCredentials = Get-MgBetaApplication -Property 'keyCredentials' -ApplicationId $AADApp.Id -ErrorAction SilentlyContinue + + $complexAuthenticationBehaviors = @{} + if ($null -ne $AADBetaApp.authenticationBehaviors.blockAzureADGraphAccess) { - Write-Verbose -Message 'Could not retrieve and instance of the Azure AD App in the Get-TargetResource function.' - return $nullReturn + $complexAuthenticationBehaviors.Add('BlockAzureADGraphAccess', $AADBetaApp.authenticationBehaviors.blockAzureADGraphAccess) } - else + if ($null -ne $AADBetaApp.authenticationBehaviors.removeUnverifiedEmailClaim) { - Write-Verbose -Message 'An instance of Azure AD App was retrieved.' - - $AADBetaApp = Get-MgBetaApplication -Property 'id,displayName,appId,authenticationBehaviors,additionalProperties' -ApplicationId $AADApp.Id -ErrorAction SilentlyContinue - $AADAppKeyCredentials = Get-MgBetaApplication -Property 'keyCredentials' -ApplicationId $AADApp.Id -ErrorAction SilentlyContinue + $complexAuthenticationBehaviors.Add('RemoveUnverifiedEmailClaim', $AADBetaApp.authenticationBehaviors.removeUnverifiedEmailClaim) + } + if ($null -ne $AADBetaApp.authenticationBehaviors.requireClientServicePrincipal) + { + $complexAuthenticationBehaviors.Add('RequireClientServicePrincipal', $AADBetaApp.authenticationBehaviors.requireClientServicePrincipal) + } + if ($complexAuthenticationBehaviors.values.Where({ $null -ne $_ }).Count -eq 0) + { + $complexAuthenticationBehaviors = $null + } - $complexAuthenticationBehaviors = @{} - if ($null -ne $AADBetaApp.authenticationBehaviors.blockAzureADGraphAccess) - { - $complexAuthenticationBehaviors.Add('BlockAzureADGraphAccess', $AADBetaApp.authenticationBehaviors.blockAzureADGraphAccess) - } - if ($null -ne $AADBetaApp.authenticationBehaviors.removeUnverifiedEmailClaim) + $complexOptionalClaims = @{} + $complexAccessToken = @() + foreach ($currentAccessToken in $AADApp.optionalClaims.accessToken) + { + $myAccessToken = @{} + $myAccessToken.Add('Essential', $currentAccessToken.essential) + $myAccessToken.Add('Name', $currentAccessToken.name) + $myAccessToken.Add('Source', $currentAccessToken.source) + if ($myAccessToken.values.Where({ $null -ne $_ }).Count -gt 0) { - $complexAuthenticationBehaviors.Add('RemoveUnverifiedEmailClaim', $AADBetaApp.authenticationBehaviors.removeUnverifiedEmailClaim) + $complexAccessToken += $myAccessToken } - if ($null -ne $AADBetaApp.authenticationBehaviors.requireClientServicePrincipal) + } + $complexOptionalClaims.Add('AccessToken', $complexAccessToken) + $complexIdToken = @() + foreach ($currentIdToken in $AADApp.optionalClaims.idToken) + { + $myIdToken = @{} + $myIdToken.Add('Essential', $currentIdToken.essential) + $myIdToken.Add('Name', $currentIdToken.name) + $myIdToken.Add('Source', $currentIdToken.source) + if ($myIdToken.values.Where({ $null -ne $_ }).Count -gt 0) { - $complexAuthenticationBehaviors.Add('RequireClientServicePrincipal', $AADBetaApp.authenticationBehaviors.requireClientServicePrincipal) + $complexIdToken += $myIdToken } - if ($complexAuthenticationBehaviors.values.Where({ $null -ne $_ }).Count -eq 0) + } + $complexOptionalClaims.Add('IdToken', $complexIdToken) + $complexSaml2Token = @() + foreach ($currentSaml2Token in $AADApp.optionalClaims.saml2Token) + { + $mySaml2Token = @{} + $mySaml2Token.Add('Essential', $currentSaml2Token.essential) + $mySaml2Token.Add('Name', $currentSaml2Token.name) + $mySaml2Token.Add('Source', $currentSaml2Token.source) + if ($mySaml2Token.values.Where({ $null -ne $_ }).Count -gt 0) { - $complexAuthenticationBehaviors = $null + $complexSaml2Token += $mySaml2Token } + } + $complexOptionalClaims.Add('Saml2Token', $complexSaml2Token) + if ($complexOptionalClaims.values.Where({ $null -ne $_ }).Count -eq 0) + { + $complexOptionalClaims = $null + } - $complexOptionalClaims = @{} - $complexAccessToken = @() - foreach ($currentAccessToken in $AADApp.optionalClaims.accessToken) - { - $myAccessToken = @{} - $myAccessToken.Add('Essential', $currentAccessToken.essential) - $myAccessToken.Add('Name', $currentAccessToken.name) - $myAccessToken.Add('Source', $currentAccessToken.source) - if ($myAccessToken.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexAccessToken += $myAccessToken - } - } - $complexOptionalClaims.Add('AccessToken', $complexAccessToken) - $complexIdToken = @() - foreach ($currentIdToken in $AADApp.optionalClaims.idToken) + + $complexApi = @{} + $complexPreAuthorizedApplications = @() + foreach ($currentPreAuthorizedApplications in $AADApp.api.preAuthorizedApplications) + { + $myPreAuthorizedApplications = @{} + $myPreAuthorizedApplications.Add('AppId', $currentPreAuthorizedApplications.appId) + $myPreAuthorizedApplications.Add('PermissionIds', $currentPreAuthorizedApplications.permissionIds) + if ($myPreAuthorizedApplications.values.Where({ $null -ne $_ }).Count -gt 0) { - $myIdToken = @{} - $myIdToken.Add('Essential', $currentIdToken.essential) - $myIdToken.Add('Name', $currentIdToken.name) - $myIdToken.Add('Source', $currentIdToken.source) - if ($myIdToken.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexIdToken += $myIdToken - } + $complexPreAuthorizedApplications += $myPreAuthorizedApplications } - $complexOptionalClaims.Add('IdToken', $complexIdToken) - $complexSaml2Token = @() - foreach ($currentSaml2Token in $AADApp.optionalClaims.saml2Token) - { - $mySaml2Token = @{} - $mySaml2Token.Add('Essential', $currentSaml2Token.essential) - $mySaml2Token.Add('Name', $currentSaml2Token.name) - $mySaml2Token.Add('Source', $currentSaml2Token.source) - if ($mySaml2Token.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexSaml2Token += $mySaml2Token - } - } - $complexOptionalClaims.Add('Saml2Token', $complexSaml2Token) - if ($complexOptionalClaims.values.Where({ $null -ne $_ }).Count -eq 0) - { - $complexOptionalClaims = $null + } + + $complexOAuth2Scopes = @() + foreach ($currentOAuth2Scope in $AADApp.api.Oauth2PermissionScopes) + { + $complexOAuth2Scopes += @{ + adminConsentDescription = $currentOAuth2Scope.adminConsentDescription + adminConsentDisplayName = $currentOAuth2Scope.adminConsentDisplayName + id = $currentOAuth2Scope.id + isEnabled = $currentOAuth2Scope.isEnabled + type = $currentOAuth2Scope.type + userConsentDescription = $currentOAuth2Scope.userConsentDescription + userConsentDisplayName = $currentOAuth2Scope.userConsentDisplayName + value = $currentOAuth2Scope.value } + } + $complexApi.Add('PreAuthorizedApplications', $complexPreAuthorizedApplications) + $complexApi.Add('Oauth2PermissionScopes', $complexOAuth2Scopes) + if ($complexApi.values.Where({ $null -ne $_ }).Count -eq 0) + { + $complexApi = $null + } - $complexApi = @{} - $complexPreAuthorizedApplications = @() - foreach ($currentPreAuthorizedApplications in $AADApp.api.preAuthorizedApplications) + $complexKeyCredentials = @() + foreach ($currentkeyCredentials in $AADAppKeyCredentials.keyCredentials) + { + $mykeyCredentials = @{} + if ($null -ne $currentkeyCredentials.customKeyIdentifier) { - $myPreAuthorizedApplications = @{} - $myPreAuthorizedApplications.Add('AppId', $currentPreAuthorizedApplications.appId) - $myPreAuthorizedApplications.Add('PermissionIds', $currentPreAuthorizedApplications.permissionIds) - if ($myPreAuthorizedApplications.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexPreAuthorizedApplications += $myPreAuthorizedApplications - } + $mykeyCredentials.Add('CustomKeyIdentifier', [convert]::ToBase64String($currentkeyCredentials.customKeyIdentifier)) } - - $complexOAuth2Scopes = @() - foreach ($currentOAuth2Scope in $AADApp.api.Oauth2PermissionScopes) + $mykeyCredentials.Add('DisplayName', $currentkeyCredentials.displayName) + if ($null -ne $currentkeyCredentials.endDateTime) { - $complexOAuth2Scopes += @{ - adminConsentDescription = $currentOAuth2Scope.adminConsentDescription - adminConsentDisplayName = $currentOAuth2Scope.adminConsentDisplayName - id = $currentOAuth2Scope.id - isEnabled = $currentOAuth2Scope.isEnabled - type = $currentOAuth2Scope.type - userConsentDescription = $currentOAuth2Scope.userConsentDescription - userConsentDisplayName = $currentOAuth2Scope.userConsentDisplayName - value = $currentOAuth2Scope.value - } + $mykeyCredentials.Add('EndDateTime', ([DateTimeOffset]$currentkeyCredentials.endDateTime).ToString('o')) } + $mykeyCredentials.Add('KeyId', $currentkeyCredentials.keyId) - $complexApi.Add('PreAuthorizedApplications', $complexPreAuthorizedApplications) - $complexApi.Add('Oauth2PermissionScopes', $complexOAuth2Scopes) - if ($complexApi.values.Where({ $null -ne $_ }).Count -eq 0) - { - $complexApi = $null - } - $complexKeyCredentials = @() - foreach ($currentkeyCredentials in $AADAppKeyCredentials.keyCredentials) + if ($null -ne $currentkeyCredentials.Key) { - $mykeyCredentials = @{} - if ($null -ne $currentkeyCredentials.customKeyIdentifier) - { - $mykeyCredentials.Add('CustomKeyIdentifier', [convert]::ToBase64String($currentkeyCredentials.customKeyIdentifier)) - } - $mykeyCredentials.Add('DisplayName', $currentkeyCredentials.displayName) - if ($null -ne $currentkeyCredentials.endDateTime) - { - $mykeyCredentials.Add('EndDateTime', ([DateTimeOffset]$currentkeyCredentials.endDateTime).ToString('o')) - } - $mykeyCredentials.Add('KeyId', $currentkeyCredentials.keyId) - - - if ($null -ne $currentkeyCredentials.Key) - { - $mykeyCredentials.Add('Key', [convert]::ToBase64String($currentkeyCredentials.key)) - } - - if ($null -ne $currentkeyCredentials.startDateTime) - { - $mykeyCredentials.Add('StartDateTime', ([DateTimeOffset]$currentkeyCredentials.startDateTime).ToString('o')) - } - $mykeyCredentials.Add('Type', $currentkeyCredentials.type) - $mykeyCredentials.Add('Usage', $currentkeyCredentials.usage) - if ($mykeyCredentials.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexKeyCredentials += $mykeyCredentials - } + $mykeyCredentials.Add('Key', [convert]::ToBase64String($currentkeyCredentials.key)) } - $complexPasswordCredentials = @() - foreach ($currentpasswordCredentials in $AADApp.passwordCredentials) + if ($null -ne $currentkeyCredentials.startDateTime) { - $mypasswordCredentials = @{} - $mypasswordCredentials.Add('DisplayName', $currentpasswordCredentials.displayName) - if ($null -ne $currentpasswordCredentials.endDateTime) - { - $mypasswordCredentials.Add('EndDateTime', ([DateTimeOffset]$currentpasswordCredentials.endDateTime).ToString('o')) - } - $mypasswordCredentials.Add('Hint', $currentpasswordCredentials.hint) - $mypasswordCredentials.Add('KeyId', $currentpasswordCredentials.keyId) - if ($null -ne $currentpasswordCredentials.startDateTime) - { - $mypasswordCredentials.Add('StartDateTime', ([DateTimeOffset]$currentpasswordCredentials.startDateTime).ToString('o')) - } - if ($mypasswordCredentials.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexPasswordCredentials += $mypasswordCredentials - } + $mykeyCredentials.Add('StartDateTime', ([DateTimeOffset]$currentkeyCredentials.startDateTime).ToString('o')) } - - $complexAppRoles = @() - foreach ($currentappRoles in $AADApp.appRoles) + $mykeyCredentials.Add('Type', $currentkeyCredentials.type) + $mykeyCredentials.Add('Usage', $currentkeyCredentials.usage) + if ($mykeyCredentials.values.Where({ $null -ne $_ }).Count -gt 0) { - $myappRoles = @{} - $myappRoles.Add('AllowedMemberTypes', $currentappRoles.allowedMemberTypes) - $myappRoles.Add('Description', $currentappRoles.description) - $myappRoles.Add('DisplayName', $currentappRoles.displayName) - $myappRoles.Add('Id', $currentappRoles.id) - $myappRoles.Add('IsEnabled', $currentappRoles.isEnabled) - $myappRoles.Add('Origin', $currentappRoles.origin) - $myappRoles.Add('Value', $currentappRoles.value) - if ($myappRoles.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexAppRoles += $myappRoles - } + $complexKeyCredentials += $mykeyCredentials } + } - $permissionsObj = Get-M365DSCAzureADAppPermissions -App $AADApp - $isPublicClient = $false - if (-not [System.String]::IsNullOrEmpty($AADApp.PublicClient) -and $AADApp.PublicClient -eq $true) + $complexPasswordCredentials = @() + foreach ($currentpasswordCredentials in $AADApp.passwordCredentials) + { + $mypasswordCredentials = @{} + $mypasswordCredentials.Add('DisplayName', $currentpasswordCredentials.displayName) + if ($null -ne $currentpasswordCredentials.endDateTime) { - $isPublicClient = $true + $mypasswordCredentials.Add('EndDateTime', ([DateTimeOffset]$currentpasswordCredentials.endDateTime).ToString('o')) } - $AvailableToOtherTenantsValue = $false - if ($AADApp.SignInAudience -ne 'AzureADMyOrg') + $mypasswordCredentials.Add('Hint', $currentpasswordCredentials.hint) + $mypasswordCredentials.Add('KeyId', $currentpasswordCredentials.keyId) + if ($null -ne $currentpasswordCredentials.startDateTime) { - $AvailableToOtherTenantsValue = $true + $mypasswordCredentials.Add('StartDateTime', ([DateTimeOffset]$currentpasswordCredentials.startDateTime).ToString('o')) } - - [Array]$Owners = Get-MgApplicationOwner -ApplicationId $AADApp.Id -All:$true | ` - Where-Object { !$_.DeletedDateTime } - $OwnersValues = @() - foreach ($Owner in $Owners) + if ($mypasswordCredentials.values.Where({ $null -ne $_ }).Count -gt 0) { - if ($Owner.AdditionalProperties.userPrincipalName) - { - $OwnersValues += $Owner.AdditionalProperties.userPrincipalName - } - else - { - $OwnersValues += $Owner.Id - } + $complexPasswordCredentials += $mypasswordCredentials } + } - $IsFallbackPublicClientValue = $false - if ($AADApp.IsFallbackPublicClient) + $complexAppRoles = @() + foreach ($currentappRoles in $AADApp.appRoles) + { + $myappRoles = @{} + $myappRoles.Add('AllowedMemberTypes', $currentappRoles.allowedMemberTypes) + $myappRoles.Add('Description', $currentappRoles.description) + $myappRoles.Add('DisplayName', $currentappRoles.displayName) + $myappRoles.Add('Id', $currentappRoles.id) + $myappRoles.Add('IsEnabled', $currentappRoles.isEnabled) + $myappRoles.Add('Origin', $currentappRoles.origin) + $myappRoles.Add('Value', $currentappRoles.value) + if ($myappRoles.values.Where({ $null -ne $_ }).Count -gt 0) { - $IsFallbackPublicClientValue = $AADApp.IsFallbackPublicClient + $complexAppRoles += $myappRoles } + } - #region OnPremisesPublishing - $onPremisesPublishingValue = @{} - $oppInfo = $null + $permissionsObj = Get-M365DSCAzureADAppPermissions -App $AADApp + $isPublicClient = $false + if (-not [System.String]::IsNullOrEmpty($AADApp.PublicClient) -and $AADApp.PublicClient -eq $true) + { + $isPublicClient = $true + } + $AvailableToOtherTenantsValue = $false + if ($AADApp.SignInAudience -ne 'AzureADMyOrg') + { + $AvailableToOtherTenantsValue = $true + } - try + [Array]$Owners = Get-MgApplicationOwner -ApplicationId $AADApp.Id -All:$true | ` + Where-Object { !$_.DeletedDateTime } + $OwnersValues = @() + foreach ($Owner in $Owners) + { + if ($Owner.AdditionalProperties.userPrincipalName) { - $Uri = (Get-MSCloudLoginConnectionProfile -Workload MicrosoftGraph).ResourceUrl + "beta/applications/$($AADBetaApp.Id)/onPremisesPublishing" - $oppInfo = Invoke-MgGraphRequest -Method GET ` - -Uri $Uri ` - -ErrorAction SilentlyContinue + $OwnersValues += $Owner.AdditionalProperties.userPrincipalName } - catch + else { - Write-Verbose -Message "On-premises publishing is not enabled for App {$($AADBetaApp.DisplayName)}" + $OwnersValues += $Owner.Id } + } - if ($null -ne $oppInfo) + $IsFallbackPublicClientValue = $false + if ($AADApp.IsFallbackPublicClient) + { + $IsFallbackPublicClientValue = $AADApp.IsFallbackPublicClient + } + + #region OnPremisesPublishing + $onPremisesPublishingValue = @{} + $oppInfo = $null + + try + { + $Uri = (Get-MSCloudLoginConnectionProfile -Workload MicrosoftGraph).ResourceUrl + "beta/applications/$($AADBetaApp.Id)/onPremisesPublishing" + $oppInfo = Invoke-MgGraphRequest -Method GET ` + -Uri $Uri ` + -ErrorAction SilentlyContinue + } + catch + { + Write-Verbose -Message "On-premises publishing is not enabled for App {$($AADBetaApp.DisplayName)}" + } + + if ($null -ne $oppInfo) + { + $onPremisesPublishingValue = @{ + alternateUrl = $oppInfo.alternateUrl + applicationServerTimeout = $oppInfo.applicationServerTimeout + externalAuthenticationType = $oppInfo.externalAuthenticationType + externalUrl = $oppInfo.externalUrl + internalUrl = $oppInfo.internalUrl + isBackendCertificateValidationEnabled = $oppInfo.isBackendCertificateValidationEnabled + isHttpOnlyCookieEnabled = $oppInfo.isHttpOnlyCookieEnabled + isPersistentCookieEnabled = $oppInfo.isPersistentCookieEnabled + isSecureCookieEnabled = $oppInfo.isSecureCookieEnabled + isStateSessionEnabled = $oppInfo.isStateSessionEnabled + isTranslateHostHeaderEnabled = $oppInfo.isTranslateHostHeaderEnabled + isTranslateLinksInBodyEnabled = $oppInfo.isTranslateLinksInBodyEnabled + } + + # onPremisesApplicationSegments + $segmentValues = @() + foreach ($segment in $oppInfo.onPremisesApplicationSegments) { - $onPremisesPublishingValue = @{ - alternateUrl = $oppInfo.alternateUrl - applicationServerTimeout = $oppInfo.applicationServerTimeout - externalAuthenticationType = $oppInfo.externalAuthenticationType - externalUrl = $oppInfo.externalUrl - internalUrl = $oppInfo.internalUrl - isBackendCertificateValidationEnabled = $oppInfo.isBackendCertificateValidationEnabled - isHttpOnlyCookieEnabled = $oppInfo.isHttpOnlyCookieEnabled - isPersistentCookieEnabled = $oppInfo.isPersistentCookieEnabled - isSecureCookieEnabled = $oppInfo.isSecureCookieEnabled - isStateSessionEnabled = $oppInfo.isStateSessionEnabled - isTranslateHostHeaderEnabled = $oppInfo.isTranslateHostHeaderEnabled - isTranslateLinksInBodyEnabled = $oppInfo.isTranslateLinksInBodyEnabled + $entry = @{ + alternateUrl = $segment.AlternateUrl + externalUrl = $segment.externalUrl + internalUrl = $segment.internalUrl } - # onPremisesApplicationSegments - $segmentValues = @() - foreach ($segment in $oppInfo.onPremisesApplicationSegments) + $corsConfigurationValues = @() + foreach ($cors in $segment.corsConfigurations) { - $entry = @{ - alternateUrl = $segment.AlternateUrl - externalUrl = $segment.externalUrl - internalUrl = $segment.internalUrl - } - - $corsConfigurationValues = @() - foreach ($cors in $segment.corsConfigurations) - { - $corsEntry = @{ - allowedHeaders = [Array]($cors.allowedHeaders) - allowedMethods = [Array]($cors.allowedMethods) - allowedOrigins = [Array]($cors.allowedOrigins) - maxAgeInSeconds = $cors.maxAgeInSeconds - resource = $cors.resource - } - $corsConfigurationValues += $corsEntry + $corsEntry = @{ + allowedHeaders = [Array]($cors.allowedHeaders) + allowedMethods = [Array]($cors.allowedMethods) + allowedOrigins = [Array]($cors.allowedOrigins) + maxAgeInSeconds = $cors.maxAgeInSeconds + resource = $cors.resource } - $entry.Add('corsConfigurations', $corsConfigurationValues) - $segmentValues += $entry + $corsConfigurationValues += $corsEntry } - $onPremisesPublishingValue.Add('onPremisesApplicationSegments', $segmentValues) + $entry.Add('corsConfigurations', $corsConfigurationValues) + $segmentValues += $entry + } + $onPremisesPublishingValue.Add('onPremisesApplicationSegments', $segmentValues) - # singleSignOnSettings - $singleSignOnValues = @{ - kerberosSignOnSettings = @{ - kerberosServicePrincipalName = $oppInfo.singleSignOnSettings.kerberosSignOnSettings.kerberosServicePrincipalName - kerberosSignOnMappingAttributeType = $oppInfo.singleSignOnSettings.kerberosSignOnSettings.kerberosSignOnMappingAttributeType - } - singleSignOnMode = $oppInfo.singleSignOnSettings.singleSignOnMode + # singleSignOnSettings + $singleSignOnValues = @{ + kerberosSignOnSettings = @{ + kerberosServicePrincipalName = $oppInfo.singleSignOnSettings.kerberosSignOnSettings.kerberosServicePrincipalName + kerberosSignOnMappingAttributeType = $oppInfo.singleSignOnSettings.kerberosSignOnSettings.kerberosSignOnMappingAttributeType } - $onPremisesPublishingValue.Add('singleSignOnSettings', $singleSignOnValues) + singleSignOnMode = $oppInfo.singleSignOnSettings.singleSignOnMode } - #endregion + $onPremisesPublishingValue.Add('singleSignOnSettings', $singleSignOnValues) + } + #endregion - $IdentifierUrisValue = @() - if ($null -ne $AADApp.IdentifierUris) - { - $IdentifierUrisValue = $AADApp.IdentifierUris - } + $IdentifierUrisValue = @() + if ($null -ne $AADApp.IdentifierUris) + { + $IdentifierUrisValue = $AADApp.IdentifierUris + } - $result = @{ - DisplayName = $AADApp.DisplayName - AvailableToOtherTenants = $AvailableToOtherTenantsValue - Description = $AADApp.Description - GroupMembershipClaims = $AADApp.GroupMembershipClaims - Homepage = $AADApp.web.HomepageUrl - IdentifierUris = $IdentifierUrisValue - IsFallbackPublicClient = $IsFallbackPublicClientValue - KnownClientApplications = $AADApp.Api.KnownClientApplications - LogoutURL = $AADApp.web.LogoutURL - PublicClient = $isPublicClient - ReplyURLs = $AADApp.web.RedirectUris - Owners = $OwnersValues - ObjectId = $AADApp.Id - AppId = $AADApp.AppId - OptionalClaims = $complexOptionalClaims - Api = $complexApi - AuthenticationBehaviors = $complexAuthenticationBehaviors - KeyCredentials = $complexKeyCredentials - PasswordCredentials = $complexPasswordCredentials - AppRoles = $complexAppRoles - Permissions = $permissionsObj - OnPremisesPublishing = $onPremisesPublishingValue - ApplicationTemplateId = $AADApp.AdditionalProperties.applicationTemplateId - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - ApplicationSecret = $ApplicationSecret - CertificateThumbprint = $CertificateThumbprint - ManagedIdentity = $ManagedIdentity.IsPresent - AccessTokens = $AccessTokens - } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + $result = @{ + DisplayName = $AADApp.DisplayName + AvailableToOtherTenants = $AvailableToOtherTenantsValue + Description = $AADApp.Description + GroupMembershipClaims = $AADApp.GroupMembershipClaims + Homepage = $AADApp.web.HomepageUrl + IdentifierUris = $IdentifierUrisValue + IsFallbackPublicClient = $IsFallbackPublicClientValue + KnownClientApplications = $AADApp.Api.KnownClientApplications + LogoutURL = $AADApp.web.LogoutURL + PublicClient = $isPublicClient + ReplyURLs = $AADApp.web.RedirectUris + Owners = $OwnersValues + ObjectId = $AADApp.Id + AppId = $AADApp.AppId + OptionalClaims = $complexOptionalClaims + Api = $complexApi + AuthenticationBehaviors = $complexAuthenticationBehaviors + KeyCredentials = $complexKeyCredentials + PasswordCredentials = $complexPasswordCredentials + AppRoles = $complexAppRoles + Permissions = $permissionsObj + OnPremisesPublishing = $onPremisesPublishingValue + ApplicationTemplateId = $AADApp.AdditionalProperties.applicationTemplateId + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + ApplicationSecret = $ApplicationSecret + CertificateThumbprint = $CertificateThumbprint + ManagedIdentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens } + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -1602,6 +1592,7 @@ function Export-TargetResource } try { + $Script:exportedInstance = $AADApp $Results = Get-TargetResource @Params if ($Results.Ensure -eq 'Present') { diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationMethodPolicy/MSFT_AADAuthenticationMethodPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationMethodPolicy/MSFT_AADAuthenticationMethodPolicy.psm1 index be5b8e6c1a..ac69ac161e 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationMethodPolicy/MSFT_AADAuthenticationMethodPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationMethodPolicy/MSFT_AADAuthenticationMethodPolicy.psm1 @@ -79,50 +79,57 @@ function Get-TargetResource try { - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullResult = $PSBoundParameters - $nullResult.Ensure = 'Absent' - - $getValue = $null - #region resource generator code - if (-not [System.String]::IsNullOrEmpty($Id)) + if (-not $Script:exportedInstance) { - $getValue = Get-MgBetaPolicyAuthenticationMethodPolicy -ErrorAction SilentlyContinue - } + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $getValue) - { - Write-Verbose -Message "Could not find an Azure AD Authentication Method Policy with Id {$Id}" + $nullResult = $PSBoundParameters + $nullResult.Ensure = 'Absent' - if (-Not [string]::IsNullOrEmpty($DisplayName)) + $getValue = $null + #region resource generator code + if (-not [System.String]::IsNullOrEmpty($Id)) { - $getValue = Get-MgBetaPolicyAuthenticationMethodPolicy ` - -ErrorAction SilentlyContinue | Where-Object ` - -FilterScript { ` - $_.DisplayName -eq "$($DisplayName)" ` - -and $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.AuthenticationMethodsPolicy' ` + $getValue = Get-MgBetaPolicyAuthenticationMethodPolicy -ErrorAction SilentlyContinue + } + + if ($null -eq $getValue) + { + Write-Verbose -Message "Could not find an Azure AD Authentication Method Policy with Id {$Id}" + + if (-Not [string]::IsNullOrEmpty($DisplayName)) + { + $getValue = Get-MgBetaPolicyAuthenticationMethodPolicy ` + -ErrorAction SilentlyContinue | Where-Object ` + -FilterScript { ` + $_.DisplayName -eq "$($DisplayName)" ` + -and $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.AuthenticationMethodsPolicy' ` + } } } + #endregion + if ($null -eq $getValue) + { + Write-Verbose -Message "Could not find an Azure AD Authentication Method Policy with DisplayName {$DisplayName}" + return $nullResult + } } - #endregion - if ($null -eq $getValue) + else { - Write-Verbose -Message "Could not find an Azure AD Authentication Method Policy with DisplayName {$DisplayName}" - return $nullResult + $getValue = $Script:exportedInstance } $Id = $getValue.Id Write-Verbose -Message "An Azure AD Authentication Method Policy with Id {$Id} and DisplayName {$DisplayName} was found." @@ -642,6 +649,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $config $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationStrengthPolicy/MSFT_AADAuthenticationStrengthPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationStrengthPolicy/MSFT_AADAuthenticationStrengthPolicy.psm1 index 63e999016f..56463cd84f 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationStrengthPolicy/MSFT_AADAuthenticationStrengthPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADAuthenticationStrengthPolicy/MSFT_AADAuthenticationStrengthPolicy.psm1 @@ -57,41 +57,47 @@ function Get-TargetResource try { - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + if (-not $Script:exportedInstance) + { + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters - $nullResult = $PSBoundParameters - $nullResult.Ensure = 'Absent' + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $getValue = $null + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if (-not [System.String]::IsNullOrEmpty($Id)) - { - $getValue = Get-MgBetaPolicyAuthenticationStrengthPolicy -AuthenticationStrengthPolicyId $Id -ErrorAction 'SilentlyContinue' - } + $nullResult = $PSBoundParameters + $nullResult.Ensure = 'Absent' - if ($null -eq $getValue) - { - $getValue = Get-MgBetaPolicyAuthenticationStrengthPolicy | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } -ErrorAction SilentlyContinue - } + $getValue = $null + + if (-not [System.String]::IsNullOrEmpty($Id)) + { + $getValue = Get-MgBetaPolicyAuthenticationStrengthPolicy -AuthenticationStrengthPolicyId $Id -ErrorAction 'SilentlyContinue' + } - if ($null -eq $getValue) + if ($null -eq $getValue) + { + $getValue = Get-MgBetaPolicyAuthenticationStrengthPolicy | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } -ErrorAction SilentlyContinue + } + + if ($null -eq $getValue) + { + return $nullResult + } + } + else { - return $nullResult + $getValue = $Script:exportedInstance } - $results = @{ Description = $getValue.Description DisplayName = $getValue.DisplayName @@ -409,6 +415,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $config $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADConditionalAccessPolicy/MSFT_AADConditionalAccessPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADConditionalAccessPolicy/MSFT_AADConditionalAccessPolicy.psm1 index 9cf2dcd73a..a15541b429 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADConditionalAccessPolicy/MSFT_AADConditionalAccessPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADConditionalAccessPolicy/MSFT_AADConditionalAccessPolicy.psm1 @@ -263,56 +263,63 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message 'Getting configuration of AzureAD Conditional Access Policy' - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - if ($PSBoundParameters.ContainsKey('Id')) + if (-not $Script:exportedInstance) { - Write-Verbose -Message 'PolicyID was specified' - try + Write-Verbose -Message 'Getting configuration of AzureAD Conditional Access Policy' + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + if ($PSBoundParameters.ContainsKey('Id')) { - $Policy = Get-MgBetaIdentityConditionalAccessPolicy -ConditionalAccessPolicyId $Id -ErrorAction Stop + Write-Verbose -Message 'PolicyID was specified' + try + { + $Policy = Get-MgBetaIdentityConditionalAccessPolicy -ConditionalAccessPolicyId $Id -ErrorAction Stop + } + catch + { + Write-Verbose -Message "Couldn't find existing policy by ID {$Id}" + $Policy = Get-MgBetaIdentityConditionalAccessPolicy -Filter "DisplayName eq '$DisplayName'" + if ($Policy.Length -gt 1) + { + throw "Duplicate CA Policies named $DisplayName exist in tenant" + } + } } - catch + else { - Write-Verbose -Message "Couldn't find existing policy by ID {$Id}" + Write-Verbose -Message 'Id was NOT specified' + ## Can retreive multiple CA Policies since displayname is not unique $Policy = Get-MgBetaIdentityConditionalAccessPolicy -Filter "DisplayName eq '$DisplayName'" if ($Policy.Length -gt 1) { throw "Duplicate CA Policies named $DisplayName exist in tenant" } } - } - else - { - Write-Verbose -Message 'Id was NOT specified' - ## Can retreive multiple CA Policies since displayname is not unique - $Policy = Get-MgBetaIdentityConditionalAccessPolicy -Filter "DisplayName eq '$DisplayName'" - if ($Policy.Length -gt 1) + + if ([String]::IsNullOrEmpty($Policy.id)) { - throw "Duplicate CA Policies named $DisplayName exist in tenant" + Write-Verbose -Message "No existing Policy with name {$DisplayName} were found" + $currentValues = $PSBoundParameters + $currentValues.Ensure = 'Absent' + return $currentValues } } - - if ([String]::IsNullOrEmpty($Policy.id)) + else { - Write-Verbose -Message "No existing Policy with name {$DisplayName} were found" - $currentValues = $PSBoundParameters - $currentValues.Ensure = 'Absent' - return $currentValues + $Policy = $Script:exportedInstance } Write-Verbose -Message 'Get-TargetResource: Found existing Conditional Access policy' @@ -2289,6 +2296,7 @@ function Export-TargetResource Managedidentity = $ManagedIdentity.IsPresent AccessTokens = $AccessTokens } + $Script:exportedInstance = $Policy $Results = Get-TargetResource @Params if ([System.String]::IsNullOrEmpty($Results.DeviceFilterMode)) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADGroup/MSFT_AADGroup.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADGroup/MSFT_AADGroup.psm1 index 10b9a40cd5..9d0cf188b7 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADGroup/MSFT_AADGroup.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADGroup/MSFT_AADGroup.psm1 @@ -108,112 +108,98 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message 'Getting configuration of AzureAD Group' - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - $nullReturn.Owners = @() - $nullReturn.Members = @() - $nullReturn.MemberOf = @() - $nullReturn.AssignedToRole = @() try { - if ($PSBoundParameters.ContainsKey('Id')) + if (-not $Script:exportedInstance) { - Write-Verbose -Message 'GroupID was specified' - try + Write-Verbose -Message 'Getting configuration of AzureAD Group' + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + $nullReturn.Owners = @() + $nullReturn.Members = @() + $nullReturn.MemberOf = @() + $nullReturn.AssignedToRole = @() + + if ($PSBoundParameters.ContainsKey('Id')) { - if ($null -ne $Script:exportedGroups -and $Script:ExportMode) - { - $Group = $Script:exportedGroups | Where-Object -FilterScript { $_.Id -eq $Id } - } - else + Write-Verbose -Message 'GroupID was specified' + try { $Group = Get-MgGroup -GroupId $Id -ErrorAction Stop } - } - catch - { - Write-Verbose -Message "Couldn't get group by ID, trying by name" - if ($null -ne $Script:exportedGroups -and $Script:ExportMode) - { - $Group = $Script:exportedGroups | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } - } - else + catch { + Write-Verbose -Message "Couldn't get group by ID, trying by name" if ($DisplayName.Contains("'")) { $DisplayName = $DisplayName -replace "'", "''" } $filter = "DisplayName eq '$DisplayName'" $Group = Get-MgGroup -Filter $filter -ErrorAction Stop - } - if ($Group.Length -gt 1) - { - throw "Duplicate AzureAD Groups named $DisplayName exist in tenant" + if ($Group.Length -gt 1) + { + throw "Duplicate AzureAD Groups named $DisplayName exist in tenant" + } } } - } - else - { - Write-Verbose -Message 'Id was NOT specified' - ## Can retreive multiple AAD Groups since displayname is not unique - if ($null -ne $Script:exportedGroups -and $Script:ExportMode) - { - $Group = $Script:exportedGroups | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } - } else { + Write-Verbose -Message 'Id was NOT specified' + ## Can retreive multiple AAD Groups since displayname is not unique if ($DisplayName.Contains("'")) { $DisplayName = $DisplayName -replace "'", "''" } $filter = "DisplayName eq '$DisplayName'" $Group = Get-MgGroup -Filter $filter -ErrorAction Stop + if ($Group.Length -gt 1) + { + throw "Duplicate AzureAD Groups named $DisplayName exist in tenant" + } } - if ($Group.Length -gt 1) + + if ($null -eq $Group) { - throw "Duplicate AzureAD Groups named $DisplayName exist in tenant" + Write-Verbose -Message 'Group was null, returning null' + return $nullReturn } } - - if ($null -eq $Group) - { - Write-Verbose -Message 'Group was null, returning null' - return $nullReturn - } else { - Write-Verbose -Message 'Found existing AzureAD Group' + $Group = $Script:exportedInstance + } + + Write-Verbose -Message 'Found existing AzureAD Group' - # Owners - [Array]$owners = Get-MgBetaGroupOwner -GroupId $Group.Id -All:$true - $OwnersValues = @() - foreach ($owner in $owners) + # Owners + [Array]$owners = Get-MgBetaGroupOwner -GroupId $Group.Id -All:$true + $OwnersValues = @() + foreach ($owner in $owners) + { + if ($owner.AdditionalProperties.userPrincipalName -ne $null) { - if ($owner.AdditionalProperties.userPrincipalName -ne $null) - { - $OwnersValues += $owner.AdditionalProperties.userPrincipalName - } - elseif ($owner.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.servicePrincipal') - { - $OwnersValues += $owner.AdditionalProperties.displayName - } + $OwnersValues += $owner.AdditionalProperties.userPrincipalName + } + elseif ($owner.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.servicePrincipal') + { + $OwnersValues += $owner.AdditionalProperties.displayName } + } $MembersValues = $null $result = @{} @@ -242,42 +228,42 @@ function Get-TargetResource $result.Add('GroupAsMembers', $GroupAsMembersValues) } - # MemberOf - [Array]$memberOf = Get-MgBetaGroupMemberOf -GroupId $Group.Id -All # result also used for/by AssignedToRole - $MemberOfValues = @() - # Note: only process security-groups that this group is a member of and not directory roles (if any) - foreach ($member in ($memberOf | Where-Object -FilterScript { $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.group' })) + # MemberOf + [Array]$memberOf = Get-MgBetaGroupMemberOf -GroupId $Group.Id -All # result also used for/by AssignedToRole + $MemberOfValues = @() + # Note: only process security-groups that this group is a member of and not directory roles (if any) + foreach ($member in ($memberOf | Where-Object -FilterScript { $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.group' })) + { + if ($null -ne $member.AdditionalProperties.displayName) { - if ($null -ne $member.AdditionalProperties.displayName) - { - $MemberOfValues += $member.AdditionalProperties.displayName - } + $MemberOfValues += $member.AdditionalProperties.displayName } + } - # AssignedToRole - $AssignedToRoleValues = $null - if ($Group.IsAssignableToRole -eq $true) + # AssignedToRole + $AssignedToRoleValues = $null + if ($Group.IsAssignableToRole -eq $true) + { + $AssignedToRoleValues = @() + $roleAssignments = Get-MgBetaRoleManagementDirectoryRoleAssignment -Filter "PrincipalId eq '$($Group.Id)'" + foreach ($assignment in $roleAssignments) { - $AssignedToRoleValues = @() - $roleAssignments = Get-MgBetaRoleManagementDirectoryRoleAssignment -Filter "PrincipalId eq '$($Group.Id)'" - foreach ($assignment in $roleAssignments) - { - $roleDefinition = Get-MgBetaRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $assignment.RoleDefinitionId - $AssignedToRoleValues += $roleDefinition.DisplayName - } + $roleDefinition = Get-MgBetaRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $assignment.RoleDefinitionId + $AssignedToRoleValues += $roleDefinition.DisplayName } + } - # Licenses - $assignedLicensesValues = $null - $uri = (Get-MSCloudLoginConnectionProfile -Workload MicrosoftGraph).ResourceUrl + "v1.0/groups/$($Group.Id)/assignedLicenses" - $assignedLicensesRequest = Invoke-MgGraphRequest -Method 'GET' ` - -Uri $uri + # Licenses + $assignedLicensesValues = $null + $uri = (Get-MSCloudLoginConnectionProfile -Workload MicrosoftGraph).ResourceUrl + "v1.0/groups/$($Group.Id)/assignedLicenses" + $assignedLicensesRequest = Invoke-MgGraphRequest -Method 'GET' ` + -Uri $uri - if ($assignedLicensesRequest.value.Length -gt 0) - { - $assignedLicensesValues = Get-M365DSCAzureADGroupLicenses -AssignedLicenses $assignedLicensesRequest.value + if ($assignedLicensesRequest.value.Length -gt 0) + { + $assignedLicensesValues = Get-M365DSCAzureADGroupLicenses -AssignedLicenses $assignedLicensesRequest.value - } + } $policySettings = @{ DisplayName = $Group.DisplayName @@ -306,8 +292,7 @@ function Get-TargetResource } $result += $policySettings - return $result - } + return $result } catch { @@ -1319,6 +1304,7 @@ function Export-TargetResource Managedidentity = $ManagedIdentity.IsPresent AccessTokens = $AccessTokens } + $Script:exportedInstance = $group $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADNamedLocationPolicy/MSFT_AADNamedLocationPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADNamedLocationPolicy/MSFT_AADNamedLocationPolicy.psm1 index af69cfc90b..0ec7c56c0c 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADNamedLocationPolicy/MSFT_AADNamedLocationPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADNamedLocationPolicy/MSFT_AADNamedLocationPolicy.psm1 @@ -72,91 +72,95 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message 'Getting configuration of AAD Named Location' + try + { + if (-not $Script:exportedInstance) + { + Write-Verbose -Message 'Getting configuration of AAD Named Location' - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - try - { - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - if ($Id) - { - $NamedLocation = Get-MgBetaIdentityConditionalAccessNamedLocation -NamedLocationId $Id -ErrorAction Stop - } - } - catch - { - Write-Verbose -Message "Could not retrieve AAD Named Location by ID {$Id}" - } - if ($null -eq $NamedLocation) - { + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' try { - $NamedLocation = Get-MgBetaIdentityConditionalAccessNamedLocation -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } - if ($NamedLocation.Length -gt 1) + if ($Id) { - throw "More than one instance of a Named Location Policy with name {$DisplayName} was found. Please provide the ID parameter." + $NamedLocation = Get-MgBetaIdentityConditionalAccessNamedLocation -NamedLocationId $Id -ErrorAction Stop } } catch { - New-M365DSCLogEntry -Message 'Error retrieving data:' ` - -Exception $_ ` - -Source $($MyInvocation.MyCommand.Source) ` - -TenantId $TenantId ` - -Credential $Credential + Write-Verbose -Message "Could not retrieve AAD Named Location by ID {$Id}" + } + + if ($null -eq $NamedLocation) + { + try + { + $NamedLocation = Get-MgBetaIdentityConditionalAccessNamedLocation -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } + if ($NamedLocation.Length -gt 1) + { + throw "More than one instance of a Named Location Policy with name {$DisplayName} was found. Please provide the ID parameter." + } + } + catch + { + New-M365DSCLogEntry -Message 'Error retrieving data:' ` + -Exception $_ ` + -Source $($MyInvocation.MyCommand.Source) ` + -TenantId $TenantId ` + -Credential $Credential + return $nullReturn + } + } + if ($null -eq $NamedLocation) + { + Write-Verbose "No existing AAD Named Location found with DisplayName {$DisplayName}" return $nullReturn } } - - if ($null -eq $NamedLocation) - { - Write-Verbose "No existing AAD Named Location found with DisplayName {$DisplayName}" - return $nullReturn - } else { - Write-Verbose "Found existing AAD Named Location {$($NamedLocation.DisplayName)}" - $Result = @{ - OdataType = $NamedLocation.AdditionalProperties.'@odata.type' - Id = $NamedLocation.Id - DisplayName = $NamedLocation.DisplayName - IpRanges = $NamedLocation.AdditionalProperties.ipRanges.cidrAddress - IsTrusted = $NamedLocation.AdditionalProperties.isTrusted - CountriesAndRegions = [String[]]$NamedLocation.AdditionalProperties.countriesAndRegions - CountryLookupMethod = $NamedLocation.AdditionalProperties.countryLookupMethod - IncludeUnknownCountriesAndRegions = $NamedLocation.AdditionalProperties.includeUnknownCountriesAndRegions - Ensure = 'Present' - ApplicationSecret = $ApplicationSecret - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - Credential = $Credential - Managedidentity = $ManagedIdentity.IsPresent - AccessTokens = $AccessTokens - } - - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + $NamedLocation = $Script:exportedInstance } + Write-Verbose "Found existing AAD Named Location {$($NamedLocation.DisplayName)}" + $Result = @{ + OdataType = $NamedLocation.AdditionalProperties.'@odata.type' + Id = $NamedLocation.Id + DisplayName = $NamedLocation.DisplayName + IpRanges = $NamedLocation.AdditionalProperties.ipRanges.cidrAddress + IsTrusted = $NamedLocation.AdditionalProperties.isTrusted + CountriesAndRegions = [String[]]$NamedLocation.AdditionalProperties.countriesAndRegions + CountryLookupMethod = $NamedLocation.AdditionalProperties.countryLookupMethod + IncludeUnknownCountriesAndRegions = $NamedLocation.AdditionalProperties.includeUnknownCountriesAndRegions + Ensure = 'Present' + ApplicationSecret = $ApplicationSecret + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + Credential = $Credential + Managedidentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens + } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -540,6 +544,7 @@ function Export-TargetResource Managedidentity = $ManagedIdentity.IsPresent AccessTokens = $AccessTokens } + $Script:exportedInstance = $AADNamedLocation $Results = Get-TargetResource @Params if ($Results.Ensure -eq 'Present') diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADRoleDefinition/MSFT_AADRoleDefinition.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADRoleDefinition/MSFT_AADRoleDefinition.psm1 index 772a68b2ca..1d77a478f7 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADRoleDefinition/MSFT_AADRoleDefinition.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADRoleDefinition/MSFT_AADRoleDefinition.psm1 @@ -69,83 +69,73 @@ function Get-TargetResource [System.String[]] $AccessTokens ) - - Write-Verbose -Message 'Getting configuration of Azure AD role definition' - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' try { - try + if (-not $Script:exportedInstance) { - if (($null -ne $Id) -and ($Id -ne '')) + Write-Verbose -Message 'Getting configuration of Azure AD role definition' + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + try { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $AADRoleDefinition = $Script:exportedInstances | Where-Object -FilterScript { $_.Id -eq $Id } - } - else + if (($null -ne $Id) -and ($Id -ne '')) { $AADRoleDefinition = Get-MgBetaRoleManagementDirectoryRoleDefinition -Filter "Id eq '$($Id)'" } } - } - catch - { - Write-Verbose -Message "Could not retrieve AAD roledefinition by Id: {$Id}" - } - if ($null -eq $AADRoleDefinition) - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) + catch { - $AADRoleDefinition = $Script:exportedInstances | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } + Write-Verbose -Message "Could not retrieve AAD roledefinition by Id: {$Id}" } - else + if ($null -eq $AADRoleDefinition) { $AADRoleDefinition = Get-MgBetaRoleManagementDirectoryRoleDefinition -Filter "DisplayName eq '$($DisplayName)'" } - } - if ($null -eq $AADRoleDefinition) - { - return $nullReturn + if ($null -eq $AADRoleDefinition) + { + return $nullReturn + } } else { - $result = @{ - Id = $AADRoleDefinition.Id - DisplayName = $AADRoleDefinition.DisplayName - Description = $AADRoleDefinition.Description - ResourceScopes = $AADRoleDefinition.ResourceScopes - IsEnabled = $AADRoleDefinition.IsEnabled - RolePermissions = $AADRoleDefinition.RolePermissions.AllowedResourceActions - TemplateId = $AADRoleDefinition.TemplateId - Version = $AADRoleDefinition.Version - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - ApplicationSecret = $ApplicationSecret - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - Managedidentity = $ManagedIdentity.IsPresent - AccessTokens = $AccessTokens - } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + $AADRoleDefinition = $Script:exportedInstance + } + $result = @{ + Id = $AADRoleDefinition.Id + DisplayName = $AADRoleDefinition.DisplayName + Description = $AADRoleDefinition.Description + ResourceScopes = $AADRoleDefinition.ResourceScopes + IsEnabled = $AADRoleDefinition.IsEnabled + RolePermissions = $AADRoleDefinition.RolePermissions.AllowedResourceActions + TemplateId = $AADRoleDefinition.TemplateId + Version = $AADRoleDefinition.Version + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + ApplicationSecret = $ApplicationSecret + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + Managedidentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens } + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -480,6 +470,7 @@ function Export-TargetResource RolePermissions = @('temp') AccessTokens = $AccessTokens } + $Script:exportedInstance = $AADRoleDefinition $Results = Get-TargetResource @Params if ($Results.Ensure -eq 'Present' -and ([array]$results.RolePermissions).Length -gt 0) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADRoleSetting/MSFT_AADRoleSetting.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADRoleSetting/MSFT_AADRoleSetting.psm1 index c3a63acd65..bafa544699 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADRoleSetting/MSFT_AADRoleSetting.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADRoleSetting/MSFT_AADRoleSetting.psm1 @@ -210,48 +210,48 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Role: $DisplayName" - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - Write-Verbose -Message 'Getting configuration of Role' - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - - $RoleDefintion = $null - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $RoleDefinition = $Script:exportedInstances | Where-Object -FilterScript { $_.Id -eq $Id } - } - elseif (-not [System.String]::IsNullOrEmpty($Id)) + if (-not $Script:exportedInstance) { - $RoleDefinition = Get-MgBetaRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $Id ` - -ErrorAction SilentlyContinue - } - - if ($null -eq $RoleDefinition -and -not [System.String]::IsNullOrEmpty($DisplayName)) - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) + Write-Verbose -Message "Getting configuration of Role: $DisplayName" + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + Write-Verbose -Message 'Getting configuration of Role' + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $RoleDefinition = $null + if (-not [System.String]::IsNullOrEmpty($Id)) { - $RoleDefinition = $Script:exportedInstances | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } + $RoleDefinition = Get-MgBetaRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $Id ` + -ErrorAction SilentlyContinue } - else + + if ($null -eq $RoleDefinition -and -not [System.String]::IsNullOrEmpty($DisplayName)) { $RoleDefinition = Get-MgBetaRoleManagementDirectoryRoleDefinition -Filter "displayName eq '$DisplayName'" } } + else + { + $RoleDefinition = $Script:exportedInstance + } + + $nullReturn = $PSBoundParameters + if ($null -eq $RoleDefinition) + { + return $nullReturn + } try { @@ -1492,6 +1492,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $role $Results = Get-TargetResource @Params if ($Results.Ensure -eq 'Present') diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADServicePrincipal/MSFT_AADServicePrincipal.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADServicePrincipal/MSFT_AADServicePrincipal.psm1 index cc05842a86..18dce4cf19 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADServicePrincipal/MSFT_AADServicePrincipal.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADServicePrincipal/MSFT_AADServicePrincipal.psm1 @@ -130,54 +130,44 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message 'Getting configuration of Azure AD ServicePrincipal' - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' try { - try + if (-not $Script:exportedInstance) { - if (-not [System.String]::IsNullOrEmpty($ObjectID)) + Write-Verbose -Message 'Getting configuration of Azure AD ServicePrincipal' + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + try { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $AADServicePrincipal = $Script:exportedInstances | Where-Object -FilterScript { $_.Id -eq $Id } - } - else + if (-not [System.String]::IsNullOrEmpty($ObjectID)) { $AADServicePrincipal = Get-MgServicePrincipal -ServicePrincipalId $ObjectId ` -Expand 'AppRoleAssignedTo' ` -ErrorAction Stop } } - } - catch - { - Write-Verbose -Message "Azure AD ServicePrincipal with ObjectID: $($ObjectID) could not be retrieved" - } - - if ($null -eq $AADServicePrincipal) - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) + catch { - $AADServicePrincipal = $Script:exportedInstances | Where-Object -FilterScript { $_.AppId -eq $AppId } + Write-Verbose -Message "Azure AD ServicePrincipal with ObjectID: $($ObjectID) could not be retrieved" } - else + + if ($null -eq $AADServicePrincipal) { $ObjectGuid = [System.Guid]::empty if (-not [System.Guid]::TryParse($AppId, [System.Management.Automation.PSReference]$ObjectGuid)) @@ -195,155 +185,150 @@ function Get-TargetResource -Expand 'AppRoleAssignedTo' } } + if ($null -eq $AADServicePrincipal) + { + return $nullReturn + } } - if ($null -eq $AADServicePrincipal) + else { - return $nullReturn + $AADServicePrincipal = $Script:exportedInstance } - else + + $AppRoleAssignedToValues = @() + foreach ($principal in $AADServicePrincipal.AppRoleAssignedTo) { - $AppRoleAssignedToValues = @() - foreach ($principal in $AADServicePrincipal.AppRoleAssignedTo) + $currentAssignment = @{ + PrincipalType = $null + Identity = $null + } + if ($principal.PrincipalType -eq 'User') { - $currentAssignment = @{ - PrincipalType = $null - Identity = $null - } - if ($principal.PrincipalType -eq 'User') - { - $user = Get-MgUser -UserId $principal.PrincipalId - $currentAssignment.PrincipalType = 'User' - $currentAssignment.Identity = $user.UserPrincipalName.Split('@')[0] - $AppRoleAssignedToValues += $currentAssignment - } - elseif ($principal.PrincipalType -eq 'Group') - { - $group = Get-MgGroup -GroupId $principal.PrincipalId - $currentAssignment.PrincipalType = 'Group' - $currentAssignment.Identity = $group.DisplayName - $AppRoleAssignedToValues += $currentAssignment - } + $user = Get-MgUser -UserId $principal.PrincipalId + $currentAssignment.PrincipalType = 'User' + $currentAssignment.Identity = $user.UserPrincipalName.Split('@')[0] + $AppRoleAssignedToValues += $currentAssignment } - - $ownersValues = @() - $ownersInfo = Get-MgServicePrincipalOwner -ServicePrincipalId $AADServicePrincipal.Id -ErrorAction SilentlyContinue - foreach ($ownerInfo in $ownersInfo) + elseif ($principal.PrincipalType -eq 'Group') { - $info = Get-MgUser -UserId $ownerInfo.Id -ErrorAction SilentlyContinue - if ($null -ne $info) - { - $ownersValues += $info.UserPrincipalName - } + $group = Get-MgGroup -GroupId $principal.PrincipalId + $currentAssignment.PrincipalType = 'Group' + $currentAssignment.Identity = $group.DisplayName + $AppRoleAssignedToValues += $currentAssignment } + } - [Array]$complexDelegatedPermissionClassifications = @() - $Uri = (Get-MSCloudLoginConnectionProfile -Workload MicrosoftGraph).ResourceUrl + "v1.0/servicePrincipals/$($AADServicePrincipal.Id)/delegatedPermissionClassifications" - $permissionClassifications = Invoke-MgGraphRequest -Uri $Uri -Method Get - foreach ($permissionClassification in $permissionClassifications.Value) + $ownersValues = @() + $ownersInfo = Get-MgServicePrincipalOwner -ServicePrincipalId $AADServicePrincipal.Id -ErrorAction SilentlyContinue + foreach ($ownerInfo in $ownersInfo) + { + $info = Get-MgUser -UserId $ownerInfo.Id -ErrorAction SilentlyContinue + if ($null -ne $info) { - $hashtable = @{ - classification = $permissionClassification.Classification - permissionName = $permissionClassification.permissionName - } - $complexDelegatedPermissionClassifications += $hashtable + $ownersValues += $info.UserPrincipalName } + } - $complexKeyCredentials = @() - foreach ($currentkeyCredentials in $AADServicePrincipal.keyCredentials) - { - $mykeyCredentials = @{} - if ($null -ne $currentkeyCredentials.customKeyIdentifier) - { - $mykeyCredentials.Add('CustomKeyIdentifier', [convert]::ToBase64String($currentkeyCredentials.customKeyIdentifier)) - } - $mykeyCredentials.Add('DisplayName', $currentkeyCredentials.displayName) - if ($null -ne $currentkeyCredentials.endDateTime) - { - $mykeyCredentials.Add('EndDateTime', ([DateTimeOffset]$currentkeyCredentials.endDateTime).ToString('o')) - } - $mykeyCredentials.Add('KeyId', $currentkeyCredentials.keyId) + [Array]$complexDelegatedPermissionClassifications = @() + $Uri = (Get-MSCloudLoginConnectionProfile -Workload MicrosoftGraph).ResourceUrl + "v1.0/servicePrincipals/$($AADServicePrincipal.Id)/delegatedPermissionClassifications" + $permissionClassifications = Invoke-MgGraphRequest -Uri $Uri -Method Get + foreach ($permissionClassification in $permissionClassifications.Value) + { + $hashtable = @{ + classification = $permissionClassification.Classification + permissionName = $permissionClassification.permissionName + } + $complexDelegatedPermissionClassifications += $hashtable + } + $complexKeyCredentials = @() + foreach ($currentkeyCredentials in $AADServicePrincipal.keyCredentials) + { + $mykeyCredentials = @{} + if ($null -ne $currentkeyCredentials.customKeyIdentifier) + { + $mykeyCredentials.Add('CustomKeyIdentifier', [convert]::ToBase64String($currentkeyCredentials.customKeyIdentifier)) + } + $mykeyCredentials.Add('DisplayName', $currentkeyCredentials.displayName) + if ($null -ne $currentkeyCredentials.endDateTime) + { + $mykeyCredentials.Add('EndDateTime', ([DateTimeOffset]$currentkeyCredentials.endDateTime).ToString('o')) + } + $mykeyCredentials.Add('KeyId', $currentkeyCredentials.keyId) - if ($null -ne $currentkeyCredentials.Key) - { - $mykeyCredentials.Add('Key', [convert]::ToBase64String($currentkeyCredentials.key)) - } - if ($null -ne $currentkeyCredentials.startDateTime) - { - $mykeyCredentials.Add('StartDateTime', ([DateTimeOffset]$currentkeyCredentials.startDateTime).ToString('o')) - } - $mykeyCredentials.Add('Type', $currentkeyCredentials.type) - $mykeyCredentials.Add('Usage', $currentkeyCredentials.usage) - if ($mykeyCredentials.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexKeyCredentials += $mykeyCredentials - } + if ($null -ne $currentkeyCredentials.Key) + { + $mykeyCredentials.Add('Key', [convert]::ToBase64String($currentkeyCredentials.key)) } - $complexPasswordCredentials = @() - foreach ($currentpasswordCredentials in $AADServicePrincipal.passwordCredentials) + if ($null -ne $currentkeyCredentials.startDateTime) { - $mypasswordCredentials = @{} - $mypasswordCredentials.Add('DisplayName', $currentpasswordCredentials.displayName) - if ($null -ne $currentpasswordCredentials.endDateTime) - { - $mypasswordCredentials.Add('EndDateTime', ([DateTimeOffset]$currentpasswordCredentials.endDateTime).ToString('o')) - } - $mypasswordCredentials.Add('Hint', $currentpasswordCredentials.hint) - $mypasswordCredentials.Add('KeyId', $currentpasswordCredentials.keyId) - if ($null -ne $currentpasswordCredentials.startDateTime) - { - $mypasswordCredentials.Add('StartDateTime', ([DateTimeOffset]$currentpasswordCredentials.startDateTime).ToString('o')) - } - if ($mypasswordCredentials.values.Where({ $null -ne $_ }).Count -gt 0) - { - $complexPasswordCredentials += $mypasswordCredentials - } + $mykeyCredentials.Add('StartDateTime', ([DateTimeOffset]$currentkeyCredentials.startDateTime).ToString('o')) } - - $complexCustomSecurityAttributes = [Array](Get-CustomSecurityAttributes -ServicePrincipalId $AADServicePrincipal.Id) - if ($null -eq $complexCustomSecurityAttributes) + $mykeyCredentials.Add('Type', $currentkeyCredentials.type) + $mykeyCredentials.Add('Usage', $currentkeyCredentials.usage) + if ($mykeyCredentials.values.Where({ $null -ne $_ }).Count -gt 0) { - $complexCustomSecurityAttributes = @() + $complexKeyCredentials += $mykeyCredentials } + } - $result = @{ - AppId = $AADServicePrincipal.AppId - AppRoleAssignedTo = $AppRoleAssignedToValues - ObjectID = $AADServicePrincipal.Id - DisplayName = $AADServicePrincipal.DisplayName - AlternativeNames = $AADServicePrincipal.AlternativeNames - AccountEnabled = [boolean]$AADServicePrincipal.AccountEnabled - AppRoleAssignmentRequired = $AADServicePrincipal.AppRoleAssignmentRequired - CustomSecurityAttributes = $complexCustomSecurityAttributes - DelegatedPermissionClassifications = [Array]$complexDelegatedPermissionClassifications - ErrorUrl = $AADServicePrincipal.ErrorUrl - Homepage = $AADServicePrincipal.Homepage - LogoutUrl = $AADServicePrincipal.LogoutUrl - Notes = $AADServicePrincipal.Notes - Owners = $ownersValues - PreferredSingleSignOnMode = $AADServicePrincipal.PreferredSingleSignOnMode - PublisherName = $AADServicePrincipal.PublisherName - ReplyURLs = $AADServicePrincipal.ReplyURLs - SamlMetadataURL = $AADServicePrincipal.SamlMetadataURL - ServicePrincipalNames = $AADServicePrincipal.ServicePrincipalNames - ServicePrincipalType = $AADServicePrincipal.ServicePrincipalType - Tags = $AADServicePrincipal.Tags - KeyCredentials = $complexKeyCredentials - PasswordCredentials = $complexPasswordCredentials - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - ApplicationSecret = $ApplicationSecret - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - Managedidentity = $ManagedIdentity.IsPresent - AccessTokens = $AccessTokens + $complexPasswordCredentials = @() + foreach ($currentpasswordCredentials in $AADServicePrincipal.passwordCredentials) + { + $mypasswordCredentials = @{} + $mypasswordCredentials.Add('DisplayName', $currentpasswordCredentials.displayName) + if ($null -ne $currentpasswordCredentials.endDateTime) + { + $mypasswordCredentials.Add('EndDateTime', ([DateTimeOffset]$currentpasswordCredentials.endDateTime).ToString('o')) + } + $mypasswordCredentials.Add('Hint', $currentpasswordCredentials.hint) + $mypasswordCredentials.Add('KeyId', $currentpasswordCredentials.keyId) + if ($null -ne $currentpasswordCredentials.startDateTime) + { + $mypasswordCredentials.Add('StartDateTime', ([DateTimeOffset]$currentpasswordCredentials.startDateTime).ToString('o')) + } + if ($mypasswordCredentials.values.Where({ $null -ne $_ }).Count -gt 0) + { + $complexPasswordCredentials += $mypasswordCredentials } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result } + + $complexCustomSecurityAttributes = [Array](Get-CustomSecurityAttributes -ServicePrincipalId $AADServicePrincipal.Id) + if ($null -eq $complexCustomSecurityAttributes) + { + $complexCustomSecurityAttributes = @() + } + + $result = @{ + AppId = $AADServicePrincipal.AppId + AppRoleAssignedTo = $AppRoleAssignedToValues + ObjectID = $AADServicePrincipal.Id + DisplayName = $AADServicePrincipal.DisplayName + AlternativeNames = $AADServicePrincipal.AlternativeNames + AccountEnabled = [boolean]$AADServicePrincipal.AccountEnabled + AppRoleAssignmentRequired = $AADServicePrincipal.AppRoleAssignmentRequired + CustomSecurityAttributes = $complexCustomSecurityAttributes + DelegatedPermissionClassifications = [Array]$complexDelegatedPermissionClassifications + ErrorUrl = $AADServicePrincipal.ErrorUrl + Homepage = $AADServicePrincipal.Homepage + LogoutUrl = $AADServicePrincipal.LogoutUrl + Notes = $AADServicePrincipal.Notes + Owners = $ownersValues + PreferredSingleSignOnMode = $AADServicePrincipal.PreferredSingleSignOnMode + PublisherName = $AADServicePrincipal.PublisherName + ReplyURLs = $AADServicePrincipal.ReplyURLs + SamlMetadataURL = $AADServicePrincipal.SamlMetadataURL + ServicePrincipalNames = $AADServicePrincipal.ServicePrincipalNames + ServicePrincipalType = $AADServicePrincipal.ServicePrincipalType + Tags = $AADServicePrincipal.Tags + KeyCredentials = $complexKeyCredentials + PasswordCredentials = $complexPasswordCredentials + Ensure = 'Present' + } + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -1028,6 +1013,7 @@ function Export-TargetResource AppID = $AADServicePrincipal.AppId AccessTokens = $AccessTokens } + $Script:exportedInstance = $AADServicePrincipal $Results = Get-TargetResource @Params if ($Results.Ensure -eq 'Present') diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADSocialIdentityProvider/MSFT_AADSocialIdentityProvider.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADSocialIdentityProvider/MSFT_AADSocialIdentityProvider.psm1 index 8dd43b269f..04793134bc 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADSocialIdentityProvider/MSFT_AADSocialIdentityProvider.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADSocialIdentityProvider/MSFT_AADSocialIdentityProvider.psm1 @@ -57,32 +57,40 @@ function Get-TargetResource try { - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters + if (-not $Script:exportedInstance) + { + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullResult = $PSBoundParameters - $nullResult.Ensure = 'Absent' + $nullResult = $PSBoundParameters + $nullResult.Ensure = 'Absent' - $getValue = Get-MgBetaIdentityProvider -Filter "Id eq '$ClientId'" ` - -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.socialIdentityProvider' } + $getValue = Get-MgBetaIdentityProvider -Filter "Id eq '$ClientId'" ` + -ErrorAction SilentlyContinue | Where-Object -FilterScript { $_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.socialIdentityProvider' } - if ($null -eq $getValue) + if ($null -eq $getValue) + { + Write-Verbose -Message "Could not find Social Identity Provider Client Id {$ClientId}" + return $nullResult + } + } + else { - Write-Verbose -Message "Could not find Social Identity Provider Client Id {$ClientId}" - return $nullResult + $getValue = $Script:exportedInstance } + Write-Verbose -Message "Social Identity Provider with ClientId {$ClientId} was found." $ClientSecretValue = $null @@ -398,6 +406,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $config $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADTokenLifetimePolicy/MSFT_AADTokenLifetimePolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADTokenLifetimePolicy/MSFT_AADTokenLifetimePolicy.psm1 index 9da74687ae..ebae24d74c 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADTokenLifetimePolicy/MSFT_AADTokenLifetimePolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADTokenLifetimePolicy/MSFT_AADTokenLifetimePolicy.psm1 @@ -57,79 +57,83 @@ function Get-TargetResource [System.String[]] $AccessTokens ) - - Write-Verbose -Message 'Getting configuration of AzureAD Token Lifetime Policy' - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - try { - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - if (-Not [System.String]::IsNullOrEMpty($Id)) - { - $Policy = Get-MgBetaPolicyTokenLifetimePolicy -TokenLifetimePolicyId $Id -ErrorAction SilentlyContinue - } - } - catch - { - Write-Verbose -Message "Could not retrieve AzureAD Token Lifetime Policy by ID {$Id}" - } - if ($null -eq $Policy) + if (-not $Script:exportedInstance) { + Write-Verbose -Message 'Getting configuration of AzureAD Token Lifetime Policy' + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' try { - $Policy = Get-MgBetaPolicyTokenLifetimePolicy -Filter "DisplayName eq '$DisplayName'" -ErrorAction SilentlyContinue + if (-Not [System.String]::IsNullOrEMpty($Id)) + { + $Policy = Get-MgBetaPolicyTokenLifetimePolicy -TokenLifetimePolicyId $Id -ErrorAction SilentlyContinue + } } catch { - New-M365DSCLogEntry -Message 'Error retrieving data:' ` - -Exception $_ ` - -Source $($MyInvocation.MyCommand.Source) ` - -TenantId $TenantId ` - -Credential $Credential + Write-Verbose -Message "Could not retrieve AzureAD Token Lifetime Policy by ID {$Id}" + } + if ($null -eq $Policy) + { + try + { + $Policy = Get-MgBetaPolicyTokenLifetimePolicy -Filter "DisplayName eq '$DisplayName'" -ErrorAction SilentlyContinue + } + catch + { + New-M365DSCLogEntry -Message 'Error retrieving data:' ` + -Exception $_ ` + -Source $($MyInvocation.MyCommand.Source) ` + -TenantId $TenantId ` + -Credential $Credential + } + } + if ($null -eq $Policy) + { + return $nullReturn } - } - if ($null -eq $Policy) - { - return $nullReturn } else { - Write-Verbose "Found existing AzureAD Policy {$($Policy.DisplayName)}" - $Result = @{ - Id = $Policy.Id - Description = $Policy.Description - Definition = $Policy.Definition - DisplayName = $Policy.DisplayName - IsOrganizationDefault = $Policy.IsOrganizationDefault - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - ApplicationSecret = $ApplicationSecret - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - Managedidentity = $ManagedIdentity.IsPresent - AccessTokens = $AccessTokens - } + $Policy = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing AzureAD Policy {$($Policy.DisplayName)}" + $Result = @{ + Id = $Policy.Id + Description = $Policy.Description + Definition = $Policy.Definition + DisplayName = $Policy.DisplayName + IsOrganizationDefault = $Policy.IsOrganizationDefault + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + ApplicationSecret = $ApplicationSecret + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + Managedidentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -415,6 +419,7 @@ function Export-TargetResource ID = $AADPolicy.ID AccessTokens = $AccessTokens } + $Script:exportedInstance = $AADPolicy $Results = Get-TargetResource @Params # Fix quotes inside the Definition's JSON; diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AADUser/MSFT_AADUser.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AADUser/MSFT_AADUser.psm1 index 288e5aea9c..269d5bc1ca 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AADUser/MSFT_AADUser.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AADUser/MSFT_AADUser.psm1 @@ -134,46 +134,46 @@ function Get-TargetResource [System.String[]] $AccessTokens ) - Write-Verbose -Message "Getting configuration of Office 365 User $UserPrincipalName" - - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = @{ - UserPrincipalName = $null - DisplayName = $null - FirstName = $null - LastName = $null - UsageLocation = $null - LicenseAssignment = $null - MemberOf = $null - Password = $null - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - Managedidentity = $ManagedIdentity.IsPresent - ApplicationSecret = $ApplicationSecret - Ensure = 'Absent' - AccessTokens = $AccessTokens - } - try { - if (-not $Script:ExportMode) + if (-not $Script:exportedInstance) { + Write-Verbose -Message "Getting configuration of Office 365 User $UserPrincipalName" + + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = @{ + UserPrincipalName = $null + DisplayName = $null + FirstName = $null + LastName = $null + UsageLocation = $null + LicenseAssignment = $null + MemberOf = $null + Password = $null + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + Managedidentity = $ManagedIdentity.IsPresent + ApplicationSecret = $ApplicationSecret + Ensure = 'Absent' + AccessTokens = $AccessTokens + } + Write-Verbose -Message "Getting Office 365 User $UserPrincipalName" $propertiesToRetrieve = @('Id', 'UserPrincipalName', 'DisplayName', 'GivenName', 'Surname', 'UsageLocation', 'City', 'Country', 'Department', 'FacsimileTelephoneNumber', 'Mobile', 'OfficeLocation', 'TelephoneNumber', 'PostalCode', 'PreferredLanguage', 'State', 'StreetAddress', 'JobTitle', 'UserType', 'PasswordPolicies') $user = Get-MgUser -UserId $UserPrincipalName -Property $propertiesToRetrieve -ErrorAction SilentlyContinue @@ -186,7 +186,7 @@ function Get-TargetResource else { Write-Verbose -Message 'Retrieving user from the exported instances' - $user = $Script:M365DSCExportInstances | Where-Object -FilterScript { $_.UserPrincipalName -eq $UserPrincipalName } + $user = $Script:exportedInstance } Write-Verbose -Message "Found User $($UserPrincipalName)" @@ -1091,6 +1091,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $user $Results = Get-TargetResource @Params $Results.Password = "New-Object System.Management.Automation.PSCredential('Password', (ConvertTo-SecureString ((New-Guid).ToString()) -AsPlainText -Force));" if ($null -ne $Results.UserPrincipalName) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOAddressList/MSFT_EXOAddressList.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOAddressList/MSFT_EXOAddressList.psm1 index 0ed8e06cd9..dc4023235d 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOAddressList/MSFT_EXOAddressList.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOAddressList/MSFT_EXOAddressList.psm1 @@ -130,106 +130,95 @@ function Get-TargetResource [System.String[]] $AccessTokens ) + try + { + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of AddressList for $Name" - Write-Verbose -Message "Getting configuration of AddressList for $Name" + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + if ($null -eq (Get-Command 'Get-AddressList' -ErrorAction SilentlyContinue)) + { + return $nullReturn + } - try - { - if ($null -eq (Get-Command 'Get-AddressList' -ErrorAction SilentlyContinue)) - { - return $nullReturn - } - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $AddressLists = $Script:exportedInstances | Where-Object -FilterScript { $_.Name -eq $Name } + $AddressLists = Get-AddressList -ErrorAction Stop + $AddressList = $AddressLists | Where-Object -FilterScript { $_.Name -eq $Name } + + if ($null -eq $AddressList) + { + Write-Verbose -Message "Address List $($Name) does not exist." + return $nullReturn + } } else { - $AddressLists = Get-AddressList -ErrorAction Stop - $AddressList = $AddressLists | Where-Object -FilterScript { $_.Name -eq $Name } + $AddressList = $Script:exportedInstance } - if ($null -eq $AddressList) + if ($null -eq $AddressList.IncludedRecipients) { - Write-Verbose -Message "Address List $($Name) does not exist." - return $nullReturn + $IncludedRecipients = @() } else { - if ($null -eq $AddressList.IncludedRecipients) - { - $IncludedRecipients = @() - } - else - { - $IncludedRecipients = $AddressList.IncludedRecipients - } - - $result = @{ - Name = $Name - ConditionalCompany = $AddressList.ConditionalCompany - ConditionalCustomAttribute1 = $AddressList.ConditionalCustomAttribute1 - ConditionalCustomAttribute10 = $AddressList.ConditionalCustomAttribute10 - ConditionalCustomAttribute11 = $AddressList.ConditionalCustomAttribute11 - ConditionalCustomAttribute12 = $AddressList.ConditionalCustomAttribute12 - ConditionalCustomAttribute13 = $AddressList.ConditionalCustomAttribute13 - ConditionalCustomAttribute14 = $AddressList.ConditionalCustomAttribute14 - ConditionalCustomAttribute15 = $AddressList.ConditionalCustomAttribute15 - ConditionalCustomAttribute2 = $AddressList.ConditionalCustomAttribute2 - ConditionalCustomAttribute3 = $AddressList.ConditionalCustomAttribute3 - ConditionalCustomAttribute4 = $AddressList.ConditionalCustomAttribute4 - ConditionalCustomAttribute5 = $AddressList.ConditionalCustomAttribute5 - ConditionalCustomAttribute6 = $AddressList.ConditionalCustomAttribute6 - ConditionalCustomAttribute7 = $AddressList.ConditionalCustomAttribute7 - ConditionalCustomAttribute8 = $AddressList.ConditionalCustomAttribute8 - ConditionalCustomAttribute9 = $AddressList.ConditionalCustomAttribute9 - ConditionalDepartment = $AddressList.ConditionalDepartment - ConditionalStateOrProvince = $AddressList.ConditionalStateOrProvince - DisplayName = $AddressList.DisplayName - IncludedRecipients = $IncludedRecipients - RecipientFilter = $AddressList.RecipientFilter - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } + $IncludedRecipients = $AddressList.IncludedRecipients + } - Write-Verbose -Message "Found AddressList $($Name)" - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + $result = @{ + Name = $Name + ConditionalCompany = $AddressList.ConditionalCompany + ConditionalCustomAttribute1 = $AddressList.ConditionalCustomAttribute1 + ConditionalCustomAttribute10 = $AddressList.ConditionalCustomAttribute10 + ConditionalCustomAttribute11 = $AddressList.ConditionalCustomAttribute11 + ConditionalCustomAttribute12 = $AddressList.ConditionalCustomAttribute12 + ConditionalCustomAttribute13 = $AddressList.ConditionalCustomAttribute13 + ConditionalCustomAttribute14 = $AddressList.ConditionalCustomAttribute14 + ConditionalCustomAttribute15 = $AddressList.ConditionalCustomAttribute15 + ConditionalCustomAttribute2 = $AddressList.ConditionalCustomAttribute2 + ConditionalCustomAttribute3 = $AddressList.ConditionalCustomAttribute3 + ConditionalCustomAttribute4 = $AddressList.ConditionalCustomAttribute4 + ConditionalCustomAttribute5 = $AddressList.ConditionalCustomAttribute5 + ConditionalCustomAttribute6 = $AddressList.ConditionalCustomAttribute6 + ConditionalCustomAttribute7 = $AddressList.ConditionalCustomAttribute7 + ConditionalCustomAttribute8 = $AddressList.ConditionalCustomAttribute8 + ConditionalCustomAttribute9 = $AddressList.ConditionalCustomAttribute9 + ConditionalDepartment = $AddressList.ConditionalDepartment + ConditionalStateOrProvince = $AddressList.ConditionalStateOrProvince + DisplayName = $AddressList.DisplayName + IncludedRecipients = $IncludedRecipients + RecipientFilter = $AddressList.RecipientFilter + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found AddressList $($Name)" + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -765,6 +754,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $addressList $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXODataClassification/MSFT_EXODataClassification.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXODataClassification/MSFT_EXODataClassification.psm1 index 6e42aebac8..6ba5dfac4f 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXODataClassification/MSFT_EXODataClassification.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXODataClassification/MSFT_EXODataClassification.psm1 @@ -65,59 +65,51 @@ function Get-TargetResource [System.String[]] $AccessTokens ) - Write-Verbose -Message "Getting Data classification policy for $($Identity)" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Data classification policy for $($Identity)" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - try - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $DataClassification = $Script:exportedInstances | Where-Object -FilterScript { $_.Identity -eq $Identity } - } - else - { - $DataClassification = Get-DataClassification -Identity $Identity -ErrorAction Stop - } - if ($null -eq $DataClassification) - { - if (-not [System.String]::IsNullOrEmpty($Name)) - { - Write-Verbose -Message "Couldn't retrieve data classification by Identity. Trying by Name {$Name}." - $DataClassification = Get-DataClassification -Identity $Name - } + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + $DataClassification = Get-DataClassification -Identity $Identity -ErrorAction Stop if ($null -eq $DataClassification) { - Write-Verbose -Message "Data classification $($Identity) does not exist." - return $nullReturn + if (-not [System.String]::IsNullOrEmpty($Name)) + { + Write-Verbose -Message "Couldn't retrieve data classification by Identity. Trying by Name {$Name}." + $DataClassification = Get-DataClassification -Identity $Name + } + + if ($null -eq $DataClassification) + { + Write-Verbose -Message "Data classification $($Identity) does not exist." + return $nullReturn + } } } + else + { + $DataClassification = $Script:exportedInstance + } + $currentDefaultCultureName = ([system.globalization.cultureinfo]$DataClassification.DefaultCulture).Name $DataClassificationLocale = $currentDefaultCultureName $DataClassificationIsDefault = $false @@ -475,6 +467,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $DataClassification $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXODistributionGroup/MSFT_EXODistributionGroup.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXODistributionGroup/MSFT_EXODistributionGroup.psm1 index f758ab9a57..041414d56e 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXODistributionGroup/MSFT_EXODistributionGroup.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXODistributionGroup/MSFT_EXODistributionGroup.psm1 @@ -217,183 +217,165 @@ function Get-TargetResource [System.String[]] $AccessTokens ) - - Write-Verbose -Message "Getting configuration of Distribution Group for $Identity" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of Distribution Group for $Identity" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { if ($null -ne $PrimarySmtpAddress) { - $distributionGroup = $Script:exportedInstances | Where-Object -FilterScript { $_.PrimarySmtpAddress -eq $PrimarySmtpAddress } - $distributionGroupMembers = Get-DistributionGroupMember -Identity $PrimarySmtpAddress ` - -ErrorAction 'Stop' ` - -ResultSize 'Unlimited' + $distributionGroup = Get-DistributionGroup -Identity $PrimarySmtpAddress -ErrorAction Stop } else { - $distributionGroup = $Script:exportedInstances | Where-Object -FilterScript { $_.Identity -eq $Identity } - $distributionGroupMembers = Get-DistributionGroupMember -Identity $Identity ` - -ErrorAction 'Stop' ` - -ResultSize 'Unlimited' + $distributionGroup = Get-DistributionGroup -Identity $Identity -ErrorAction Stop + } + + if ($null -eq $distributionGroup) + { + Write-Verbose -Message "Distribution Group $($Identity) does not exist." + return $nullReturn } } else { - if ($null -ne $PrimarySmtpAddress) - { - $distributionGroup = Get-DistributionGroup -Identity $PrimarySmtpAddress -ErrorAction Stop - $distributionGroupMembers = Get-DistributionGroupMember -Identity $PrimarySmtpAddress ` - -ErrorAction 'Stop' ` - -ResultSize 'Unlimited' - } - else - { - $distributionGroup = Get-DistributionGroup -Identity $Identity -ErrorAction Stop - $distributionGroupMembers = Get-DistributionGroupMember -Identity $Identity ` - -ErrorAction 'Stop' ` - -ResultSize 'Unlimited' - } + $distributionGroup = $Script:exportedInstance } - if ($null -eq $distributionGroup) + if ($null -ne $PrimarySmtpAddress) { - Write-Verbose -Message "Distribution Group $($Identity) does not exist." - return $nullReturn + $distributionGroupMembers = Get-DistributionGroupMember -Identity $PrimarySmtpAddress ` + -ErrorAction 'Stop' ` + -ResultSize 'Unlimited' } else { - Write-Verbose -Message "Found existing Distribution Group {$Identity}." - $descriptionValue = $null - if ($distributionGroup.Description.Length -gt 0) - { - $descriptionValue = $distributionGroup.Description[0].Replace("`r", '').Replace("`n", '') - } + $distributionGroupMembers = Get-DistributionGroupMember -Identity $Identity ` + -ErrorAction 'Stop' ` + -ResultSize 'Unlimited' + } - $groupTypeValue = 'Distribution' - if (([Array]$distributionGroup.GroupType.Replace(' ', '').Split(',')).Contains('SecurityEnabled')) - { - $groupTypeValue = 'Security' - } + Write-Verbose -Message "Found existing Distribution Group {$Identity}." + $descriptionValue = $null + if ($distributionGroup.Description.Length -gt 0) + { + $descriptionValue = $distributionGroup.Description[0].Replace("`r", '').Replace("`n", '') + } - $ManagedByValue = @() - if ($null -ne $distributionGroup.ManagedBy) + $groupTypeValue = 'Distribution' + if (([Array]$distributionGroup.GroupType.Replace(' ', '').Split(',')).Contains('SecurityEnabled')) + { + $groupTypeValue = 'Security' + } + + $ManagedByValue = @() + if ($null -ne $distributionGroup.ManagedBy) + { + foreach ($user in $distributionGroup.ManagedBy) { - foreach ($user in $distributionGroup.ManagedBy) + try + { + $user = Get-MgUser -UserId $user -ErrorAction Stop + $ManagedByValue += $user.UserPrincipalName + } + catch { - try - { - $user = Get-MgUser -UserId $user -ErrorAction Stop - $ManagedByValue += $user.UserPrincipalName - } - catch - { - Write-Verbose -Message "Couldn't retrieve user {$user}" - } + Write-Verbose -Message "Couldn't retrieve user {$user}" } } + } - $ModeratedByValue = @() - if ($null -ne $distributionGroup.ModeratedBy) + $ModeratedByValue = @() + if ($null -ne $distributionGroup.ModeratedBy) + { + foreach ($user in $distributionGroup.ModeratedBy) { - foreach ($user in $distributionGroup.ModeratedBy) + try { - try - { - $user = Get-MgUser -UserId $user -ErrorAction Stop - $ModeratedByValue += $user.UserPrincipalName - } - catch - { - Write-Verbose -Message "Couldn't retrieve moderating user {$user}" - } + $user = Get-MgUser -UserId $user -ErrorAction Stop + $ModeratedByValue += $user.UserPrincipalName + } + catch + { + Write-Verbose -Message "Couldn't retrieve moderating user {$user}" } } - $result = @{ - Identity = $distributionGroup.Identity - Alias = $distributionGroup.Alias - BccBlocked = $distributionGroup.BccBlocked - BypassNestedModerationEnabled = $distributionGroup.BypassNestedModerationEnabled - Description = $descriptionValue - DisplayName = $distributionGroup.DisplayName - HiddenGroupMembershipEnabled = $distributionGroup.HiddenGroupMembershipEnabled - ManagedBy = $ManagedByValue - MemberDepartRestriction = $distributionGroup.MemberDepartRestriction - MemberJoinRestriction = $distributionGroup.MemberJoinRestriction - Members = $distributionGroupMembers.Name - ModeratedBy = $ModeratedByValue - ModerationEnabled = $distributionGroup.ModerationEnabled - Name = $distributionGroup.Name - Notes = $distributionGroup.Notes - OrganizationalUnit = $distributionGroup.OrganizationalUnit - PrimarySmtpAddress = $distributionGroup.PrimarySmtpAddress - RequireSenderAuthenticationEnabled = $distributionGroup.RequireSenderAuthenticationEnabled - RoomList = $distributionGroup.RoomList - SendModerationNotifications = $distributionGroup.SendModerationNotifications - AcceptMessagesOnlyFrom = [Array]$distributionGroup.AcceptMessagesOnlyFrom - AcceptMessagesOnlyFromDLMembers = [Array]$distributionGroup.AcceptMessagesOnlyFromDLMembers - AcceptMessagesOnlyFromSendersOrMembers = [Array]$distributionGroup.AcceptMessagesOnlyFromSendersOrMembers - CustomAttribute1 = $distributionGroup.CustomAttribute1 - CustomAttribute2 = $distributionGroup.CustomAttribute2 - CustomAttribute3 = $distributionGroup.CustomAttribute3 - CustomAttribute4 = $distributionGroup.CustomAttribute4 - CustomAttribute5 = $distributionGroup.CustomAttribute5 - CustomAttribute6 = $distributionGroup.CustomAttribute6 - CustomAttribute7 = $distributionGroup.CustomAttribute7 - CustomAttribute8 = $distributionGroup.CustomAttribute8 - CustomAttribute9 = $distributionGroup.CustomAttribute9 - CustomAttribute10 = $distributionGroup.CustomAttribute10 - CustomAttribute11 = $distributionGroup.CustomAttribute11 - CustomAttribute12 = $distributionGroup.CustomAttribute12 - CustomAttribute13 = $distributionGroup.CustomAttribute13 - CustomAttribute14 = $distributionGroup.CustomAttribute14 - CustomAttribute15 = $distributionGroup.CustomAttribute15 - EmailAddresses = [Array]$distributionGroup.EmailAddresses - GrantSendOnBehalfTo = [Array]$distributionGroup.GrantSendOnBehalfTo - HiddenFromAddressListsEnabled = [Boolean]$distributionGroup.HiddenFromAddressListsEnabled - SendOofMessageToOriginatorEnabled = [Boolean]$distributionGroup.SendOofMessageToOriginatorEnabled - Type = $groupTypeValue - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } - - return $result } + $result = @{ + Identity = $distributionGroup.Identity + Alias = $distributionGroup.Alias + BccBlocked = $distributionGroup.BccBlocked + BypassNestedModerationEnabled = $distributionGroup.BypassNestedModerationEnabled + Description = $descriptionValue + DisplayName = $distributionGroup.DisplayName + HiddenGroupMembershipEnabled = $distributionGroup.HiddenGroupMembershipEnabled + ManagedBy = $ManagedByValue + MemberDepartRestriction = $distributionGroup.MemberDepartRestriction + MemberJoinRestriction = $distributionGroup.MemberJoinRestriction + Members = $distributionGroupMembers.Name + ModeratedBy = $ModeratedByValue + ModerationEnabled = $distributionGroup.ModerationEnabled + Name = $distributionGroup.Name + Notes = $distributionGroup.Notes + OrganizationalUnit = $distributionGroup.OrganizationalUnit + PrimarySmtpAddress = $distributionGroup.PrimarySmtpAddress + RequireSenderAuthenticationEnabled = $distributionGroup.RequireSenderAuthenticationEnabled + RoomList = $distributionGroup.RoomList + SendModerationNotifications = $distributionGroup.SendModerationNotifications + AcceptMessagesOnlyFrom = [Array]$distributionGroup.AcceptMessagesOnlyFrom + AcceptMessagesOnlyFromDLMembers = [Array]$distributionGroup.AcceptMessagesOnlyFromDLMembers + AcceptMessagesOnlyFromSendersOrMembers = [Array]$distributionGroup.AcceptMessagesOnlyFromSendersOrMembers + CustomAttribute1 = $distributionGroup.CustomAttribute1 + CustomAttribute2 = $distributionGroup.CustomAttribute2 + CustomAttribute3 = $distributionGroup.CustomAttribute3 + CustomAttribute4 = $distributionGroup.CustomAttribute4 + CustomAttribute5 = $distributionGroup.CustomAttribute5 + CustomAttribute6 = $distributionGroup.CustomAttribute6 + CustomAttribute7 = $distributionGroup.CustomAttribute7 + CustomAttribute8 = $distributionGroup.CustomAttribute8 + CustomAttribute9 = $distributionGroup.CustomAttribute9 + CustomAttribute10 = $distributionGroup.CustomAttribute10 + CustomAttribute11 = $distributionGroup.CustomAttribute11 + CustomAttribute12 = $distributionGroup.CustomAttribute12 + CustomAttribute13 = $distributionGroup.CustomAttribute13 + CustomAttribute14 = $distributionGroup.CustomAttribute14 + CustomAttribute15 = $distributionGroup.CustomAttribute15 + EmailAddresses = [Array]$distributionGroup.EmailAddresses + GrantSendOnBehalfTo = [Array]$distributionGroup.GrantSendOnBehalfTo + HiddenFromAddressListsEnabled = [Boolean]$distributionGroup.HiddenFromAddressListsEnabled + SendOofMessageToOriginatorEnabled = [Boolean]$distributionGroup.SendOofMessageToOriginatorEnabled + Type = $groupTypeValue + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens + } + + return $result } catch { @@ -1076,6 +1058,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $distributionGroup $Results = Get-TargetResource @Params if ($Results.AcceptMessagesOnlyFromSendersOrMembers.Length -eq 0) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOGlobalAddressList/MSFT_EXOGlobalAddressList.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOGlobalAddressList/MSFT_EXOGlobalAddressList.psm1 index c321c4e7a0..ae51f94cdc 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOGlobalAddressList/MSFT_EXOGlobalAddressList.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOGlobalAddressList/MSFT_EXOGlobalAddressList.psm1 @@ -128,97 +128,91 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Global Address List configuration for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - - if ($null -eq (Get-Command 'Get-GlobalAddressList' -ErrorAction SilentlyContinue)) - { - return $nullReturn - } - try { - $AllGlobalAddressLists = Get-GlobalAddressList -ErrorAction Stop - - $GlobalAddressList = $AllGlobalAddressLists | Where-Object -FilterScript { $_.Name -eq $Name } - - if ($null -eq $GlobalAddressList) - { - Write-Verbose -Message "Global Address List $($Name) does not exist." - return $nullReturn - } - else + if (-not $Script:exportedInstance) { - if ($null -eq $GlobalAddressList.IncludedRecipients) + Write-Verbose -Message "Getting Global Address List configuration for $Name" + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + if ($null -eq (Get-Command 'Get-GlobalAddressList' -ErrorAction SilentlyContinue)) { - $IncludedRecipients = ''.ToString() + return $nullReturn } - else + + $GlobalAddressList = Get-GlobalAddressList -Identity $Name -ErrorAction Stop + + if ($null -eq $GlobalAddressList) { - $IncludedRecipients = $GlobalAddressList.IncludedRecipients + Write-Verbose -Message "Global Address List $($Name) does not exist." + return $nullReturn } + } + else + { + $GlobalAddressList = $Script:exportedInstance + } - $result = @{ - Name = $GlobalAddressList.Name - ConditionalCompany = $GlobalAddressList.ConditionalCompany - ConditionalCustomAttribute1 = $GlobalAddressList.ConditionalCustomAttribute1 - ConditionalCustomAttribute10 = $GlobalAddressList.ConditionalCustomAttribute10 - ConditionalCustomAttribute11 = $GlobalAddressList.ConditionalCustomAttribute11 - ConditionalCustomAttribute12 = $GlobalAddressList.ConditionalCustomAttribute12 - ConditionalCustomAttribute13 = $GlobalAddressList.ConditionalCustomAttribute13 - ConditionalCustomAttribute14 = $GlobalAddressList.ConditionalCustomAttribute14 - ConditionalCustomAttribute15 = $GlobalAddressList.ConditionalCustomAttribute15 - ConditionalCustomAttribute2 = $GlobalAddressList.ConditionalCustomAttribute2 - ConditionalCustomAttribute3 = $GlobalAddressList.ConditionalCustomAttribute3 - ConditionalCustomAttribute4 = $GlobalAddressList.ConditionalCustomAttribute4 - ConditionalCustomAttribute5 = $GlobalAddressList.ConditionalCustomAttribute5 - ConditionalCustomAttribute6 = $GlobalAddressList.ConditionalCustomAttribute6 - ConditionalCustomAttribute7 = $GlobalAddressList.ConditionalCustomAttribute7 - ConditionalCustomAttribute8 = $GlobalAddressList.ConditionalCustomAttribute8 - ConditionalCustomAttribute9 = $GlobalAddressList.ConditionalCustomAttribute9 - ConditionalDepartment = $GlobalAddressList.ConditionalDepartment - ConditionalStateOrProvince = $GlobalAddressList.ConditionalStateOrProvince - IncludedRecipients = $IncludedRecipients - RecipientFilter = $GlobalAddressList.RecipientFilter - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } + if ($null -eq $GlobalAddressList.IncludedRecipients) + { + $IncludedRecipients = ''.ToString() + } + else + { + $IncludedRecipients = $GlobalAddressList.IncludedRecipients + } - Write-Verbose -Message "Found Global Address List $($Name)" - return $result + $result = @{ + Name = $GlobalAddressList.Name + ConditionalCompany = $GlobalAddressList.ConditionalCompany + ConditionalCustomAttribute1 = $GlobalAddressList.ConditionalCustomAttribute1 + ConditionalCustomAttribute10 = $GlobalAddressList.ConditionalCustomAttribute10 + ConditionalCustomAttribute11 = $GlobalAddressList.ConditionalCustomAttribute11 + ConditionalCustomAttribute12 = $GlobalAddressList.ConditionalCustomAttribute12 + ConditionalCustomAttribute13 = $GlobalAddressList.ConditionalCustomAttribute13 + ConditionalCustomAttribute14 = $GlobalAddressList.ConditionalCustomAttribute14 + ConditionalCustomAttribute15 = $GlobalAddressList.ConditionalCustomAttribute15 + ConditionalCustomAttribute2 = $GlobalAddressList.ConditionalCustomAttribute2 + ConditionalCustomAttribute3 = $GlobalAddressList.ConditionalCustomAttribute3 + ConditionalCustomAttribute4 = $GlobalAddressList.ConditionalCustomAttribute4 + ConditionalCustomAttribute5 = $GlobalAddressList.ConditionalCustomAttribute5 + ConditionalCustomAttribute6 = $GlobalAddressList.ConditionalCustomAttribute6 + ConditionalCustomAttribute7 = $GlobalAddressList.ConditionalCustomAttribute7 + ConditionalCustomAttribute8 = $GlobalAddressList.ConditionalCustomAttribute8 + ConditionalCustomAttribute9 = $GlobalAddressList.ConditionalCustomAttribute9 + ConditionalDepartment = $GlobalAddressList.ConditionalDepartment + ConditionalStateOrProvince = $GlobalAddressList.ConditionalStateOrProvince + IncludedRecipients = $IncludedRecipients + RecipientFilter = $GlobalAddressList.RecipientFilter + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found Global Address List $($Name)" + return $result } catch { @@ -740,6 +734,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $GlobalAddressList $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOGroupSettings/MSFT_EXOGroupSettings.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOGroupSettings/MSFT_EXOGroupSettings.psm1 index f1a55013b8..53ca107e7b 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOGroupSettings/MSFT_EXOGroupSettings.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOGroupSettings/MSFT_EXOGroupSettings.psm1 @@ -247,44 +247,31 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Office 365 Group Settings for $DisplayName" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of Office 365 Group Settings for $DisplayName" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = @{ - DisplayName = $DisplayName - } + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = @{ + DisplayName = $DisplayName + } - try - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - [Array]$group = $Script:exportedInstances | Where-Object -FilterScript { $_.Id -eq $Id } - } - else - { Write-Verbose -Message "Retrieving group by id {$Id}" [Array]$group = Get-UnifiedGroup -Identity $Id -IncludeAllProperties -ErrorAction Stop @@ -293,25 +280,28 @@ function Get-TargetResource Write-Verbose -Message "Couldn't retrieve group by ID. Trying by DisplayName {$DisplayName}" [Array]$group = Get-UnifiedGroup -Identity $DisplayName -IncludeAllProperties -ErrorAction Stop } - } - if ($group.Length -gt 1) + if ($group.Length -gt 1) + { + Write-Warning -Message "Multiple instances of a group named {$DisplayName} was discovered which could result in inconsistencies retrieving its values." + } + $group = $group[0] + if ($null -eq $group) + { + Write-Verbose -Message "The specified group {$DisplayName} doesn't already exist." + return $nullReturn + } + } + else { - Write-Warning -Message "Multiple instances of a group named {$DisplayName} was discovered which could result in inconsistencies retrieving its values." + $group = $Script:exportedInstance } - $group = $group[0] } catch { return $nullReturn } - if ($null -eq $group) - { - Write-Verbose -Message "The specified group {$DisplayName} doesn't already exist." - return $nullReturn - } - $result = @{ DisplayName = $DisplayName Id = $group.Id @@ -1032,6 +1022,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $group $Results = Get-TargetResource @Params if ($Results -is [System.Collections.Hashtable] -and $Results.Count -gt 1) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOMailboxPermission/MSFT_EXOMailboxPermission.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOMailboxPermission/MSFT_EXOMailboxPermission.psm1 index f89dd48825..d97fa4e9ea 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOMailboxPermission/MSFT_EXOMailboxPermission.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOMailboxPermission/MSFT_EXOMailboxPermission.psm1 @@ -68,55 +68,53 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting permissions for Mailbox {$Identity}" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting permissions for Mailbox {$Identity}" + + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullResult = @{ + Identity = $Identity + Ensure = 'Absent' + } - $nullResult = @{ - Identity = $Identity - Ensure = 'Absent' - } + [Array]$permission = Get-MailboxPermission -Identity $Identity -ErrorAction Stop - try - { - [Array]$permission = Get-MailboxPermission -Identity $Identity -ErrorAction Stop + if ($permission.Length -gt 1) + { + $permission = $permission | Where-Object -FilterScript { $_.User -eq $User -and (Compare-Object -ReferenceObject $_.AccessRights.Replace(' ', '').Split(',') -DifferenceObject $AccessRights).Count -eq 0 } + } - if ($permission.Length -gt 1) - { - $permission = $permission | Where-Object -FilterScript { $_.User -eq $User -and (Compare-Object -ReferenceObject $_.AccessRights.Replace(' ', '').Split(',') -DifferenceObject $AccessRights).Count -eq 0 } - } + if ($permission.Length -gt 1) + { + $permission = $permission[0] + } - if ($permission.Length -gt 1) - { - $permission = $permission[0] + if ($null -eq $permission) + { + Write-Verbose -Message "Permission for mailbox {$($Identity)} do not exist." + return $nullResult + } } - - if ($null -eq $permission) + else { - Write-Verbose -Message "Permission for mailbox {$($Identity)} do not exist." - return $nullResult + $permission = $Script:exportedInstance } $result = @{ @@ -461,6 +459,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $permission $Results = Get-TargetResource @Params if ($Results -is [System.Collections.Hashtable] -and $Results.Count -gt 1) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRole/MSFT_EXOManagementRole.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRole/MSFT_EXOManagementRole.psm1 index 6053feec9b..a46721ad0e 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRole/MSFT_EXOManagementRole.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRole/MSFT_EXOManagementRole.psm1 @@ -55,72 +55,61 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Management Role configuration for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Management Role configuration for $Name" + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $AllManagementRoles = $Script:exportedInstances | Where-Object -FilterScript { $_.Identity -eq $Name } - } - else - { $AllManagementRoles = Get-ManagementRole -ErrorAction Stop - } - $ManagementRole = $AllManagementRoles | Where-Object -FilterScript { $_.Name -eq $Name } + $ManagementRole = $AllManagementRoles | Where-Object -FilterScript { $_.Name -eq $Name } - if ($null -eq $ManagementRole) - { - Write-Verbose -Message "Management Role $($Name) does not exist." - return $nullReturn + if ($null -eq $ManagementRole) + { + Write-Verbose -Message "Management Role $($Name) does not exist." + return $nullReturn + } } else { - $result = @{ - Name = $ManagementRole.Name - Parent = $ManagementRole.Parent - Description = $ManagementRole.Description - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } + $ManagementRole = $Script:exportedInstance + } - Write-Verbose -Message "Found Management Role $($Name)" - return $result + $result = @{ + Name = $ManagementRole.Name + Parent = $ManagementRole.Parent + Description = $ManagementRole.Description + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found Management Role $($Name)" + return $result } catch { @@ -419,6 +408,7 @@ function Export-TargetResource Parent = $ManagementRole.Parent AccessTokens = $AccessTokens } + $Script:exportedInstance = $ManagementRole $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRoleAssignment/MSFT_EXOManagementRoleAssignment.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRoleAssignment/MSFT_EXOManagementRoleAssignment.psm1 index 079b515252..4eb32acd7f 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRoleAssignment/MSFT_EXOManagementRoleAssignment.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRoleAssignment/MSFT_EXOManagementRoleAssignment.psm1 @@ -91,110 +91,99 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Management Role Assignment for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Management Role Assignment for $Name" + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $roleAssignment = $Script:exportedInstances | Where-Object -FilterScript { $_.Identity -eq $Name } - } - else - { $roleAssignment = Get-ManagementRoleAssignment -Identity $Name -ErrorAction SilentlyContinue - } - if ($null -eq $roleAssignment) - { - Write-Verbose -Message "Management Role Assignment $($Name) does not exist." - return $nullReturn + if ($null -eq $roleAssignment) + { + Write-Verbose -Message "Management Role Assignment $($Name) does not exist." + return $nullReturn + } } else { - $RecipientAdministrativeUnitScopeValue = $null - if ($roleAssignment.RecipientWriteScope -eq 'AdministrativeUnit') - { - $adminUnit = Get-AdministrativeUnit -Identity $roleAssignment.CustomRecipientWriteScope - - if ($RecipientAdministrativeUnitScope -eq $adminUnit.Id) - { - $RecipientAdministrativeUnitScopeValue = $RecipientAdministrativeUnitScope - } - else - { - $RecipientAdministrativeUnitScopeValue = $adminUnit.DisplayName - } - } + $roleAssignment = $Script:exportedInstance + } - $result = @{ - Name = $roleAssignment.Name - CustomRecipientWriteScope = $roleAssignment.CustomRecipientWriteScope - CustomResourceScope = $roleAssignment.CustomResourceScope - ExclusiveRecipientWriteScope = $roleAssignment.ExclusiveRecipientWriteScope - RecipientAdministrativeUnitScope = $RecipientAdministrativeUnitScopeValue - RecipientOrganizationalUnitScope = $roleAssignment.RecipientOrganizationalUnitScope - RecipientRelativeWriteScope = $roleAssignment.RecipientRelativeWriteScope - Role = $roleAssignment.Role - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } + $RecipientAdministrativeUnitScopeValue = $null + if ($roleAssignment.RecipientWriteScope -eq 'AdministrativeUnit') + { + $adminUnit = Get-AdministrativeUnit -Identity $roleAssignment.CustomRecipientWriteScope - if ($roleAssignment.RoleAssigneeType -eq 'SecurityGroup' -or $roleAssignment.RoleAssigneeType -eq 'RoleGroup') - { - $result.Add('SecurityGroup', $roleAssignment.RoleAssignee) - } - elseif ($roleAssignment.RoleAssigneeType -eq 'RoleAssignmentPolicy') - { - $result.Add('Policy', $roleAssignment.RoleAssignee) - } - elseif ($roleAssignment.RoleAssigneeType -eq 'ServicePrincipal') + if ($RecipientAdministrativeUnitScope -eq $adminUnit.Id) { - $result.Add('App', $roleAssignment.RoleAssignee) + $RecipientAdministrativeUnitScopeValue = $RecipientAdministrativeUnitScope } - elseif ($roleAssignment.RoleAssigneeType -eq 'User') + else { - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - $userInfo = Get-MgUser -UserId ($roleAssignment.RoleAssignee) - $result.Add('User', $userInfo.UserPrincipalName) + $RecipientAdministrativeUnitScopeValue = $adminUnit.DisplayName } + } + + $result = @{ + Name = $roleAssignment.Name + CustomRecipientWriteScope = $roleAssignment.CustomRecipientWriteScope + CustomResourceScope = $roleAssignment.CustomResourceScope + ExclusiveRecipientWriteScope = $roleAssignment.ExclusiveRecipientWriteScope + RecipientAdministrativeUnitScope = $RecipientAdministrativeUnitScopeValue + RecipientOrganizationalUnitScope = $roleAssignment.RecipientOrganizationalUnitScope + RecipientRelativeWriteScope = $roleAssignment.RecipientRelativeWriteScope + Role = $roleAssignment.Role + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens + } - Write-Verbose -Message "Found Management Role Assignment $($Name)" - return $result + if ($roleAssignment.RoleAssigneeType -eq 'SecurityGroup' -or $roleAssignment.RoleAssigneeType -eq 'RoleGroup') + { + $result.Add('SecurityGroup', $roleAssignment.RoleAssignee) + } + elseif ($roleAssignment.RoleAssigneeType -eq 'RoleAssignmentPolicy') + { + $result.Add('Policy', $roleAssignment.RoleAssignee) } + elseif ($roleAssignment.RoleAssigneeType -eq 'ServicePrincipal') + { + $result.Add('App', $roleAssignment.RoleAssignee) + } + elseif ($roleAssignment.RoleAssigneeType -eq 'User') + { + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + $userInfo = Get-MgUser -UserId ($roleAssignment.RoleAssignee) + $result.Add('User', $userInfo.UserPrincipalName) + } + + Write-Verbose -Message "Found Management Role Assignment $($Name)" + return $result } catch { @@ -607,6 +596,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $assignment $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRoleEntry/MSFT_EXOManagementRoleEntry.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRoleEntry/MSFT_EXOManagementRoleEntry.psm1 index 01be59dfff..e1ac63c5f1 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRoleEntry/MSFT_EXOManagementRoleEntry.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOManagementRoleEntry/MSFT_EXOManagementRoleEntry.psm1 @@ -50,66 +50,54 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Management Role Entry configuration for {$Identity}" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - try { - $IdentityParts = $Identity.Split('\') - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $roleEntry = $Script:exportedInstances | Where-Object -FilterScript { $_.Identity -eq $IdentityParts[0] -and $_.Name -eq $IdentityParts[1] } - } - else + if (-not $Script:exportedInstance) { + Write-Verbose -Message "Getting Management Role Entry configuration for {$Identity}" + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + $roleEntry = Get-ManagementRoleEntry -Identity $Identity -ResultSize 'Unlimited' -ErrorAction Stop - } - if ($null -eq $roleEntry) - { - throw "Management Role Entry {$Identity} does not exist." + if ($null -eq $roleEntry) + { + throw "Management Role Entry {$Identity} does not exist." + } } else { - $result = @{ - Identity = $Identity - Parameters = $roleEntry.Parameters - Type = $roleEntry.Type - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - ManagedIdentity = $ManagedIdentity - AccessTokens = $AccessTokens - } + $roleEntry = $Script:exportedInstance + } - Write-Verbose -Message "Found Management Role Entry {$Identity}." - return $result + $result = @{ + Identity = $Identity + Parameters = $roleEntry.Parameters + Type = $roleEntry.Type + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + ManagedIdentity = $ManagedIdentity + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found Management Role Entry {$Identity}." + return $result } catch { @@ -391,6 +379,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $roleEntry $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOMessageClassification/MSFT_EXOMessageClassification.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOMessageClassification/MSFT_EXOMessageClassification.psm1 index 26afd542c2..c0e2a83f82 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOMessageClassification/MSFT_EXOMessageClassification.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOMessageClassification/MSFT_EXOMessageClassification.psm1 @@ -79,50 +79,48 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Message Classification Configuration for $($Identity)" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Message Classification Configuration for $($Identity)" + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - $MessageClassification = Get-MessageClassification -Identity $Identity -ErrorAction Stop + $MessageClassification = Get-MessageClassification -Identity $Identity -ErrorAction Stop - if ($null -eq $MessageClassification) - { - if (-not [System.String]::IsNullOrEmpty($DisplayName)) - { - Write-Verbose -Message "Couldn't retrieve Message Classification policy by Id {$($Identity)}. Trying by DisplayName." - $MessageClassification = Get-MessageClassification -Identity $DisplayName - } if ($null -eq $MessageClassification) { - return $nullReturn + if (-not [System.String]::IsNullOrEmpty($DisplayName)) + { + Write-Verbose -Message "Couldn't retrieve Message Classification policy by Id {$($Identity)}. Trying by DisplayName." + $MessageClassification = Get-MessageClassification -Identity $DisplayName + } + if ($null -eq $MessageClassification) + { + return $nullReturn + } } } + else + { + $MessageClassification = $Script:exportedInstance + } $result = @{ Identity = $Identity @@ -526,6 +524,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $MessageClassification $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXORoleAssignmentPolicy/MSFT_EXORoleAssignmentPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXORoleAssignmentPolicy/MSFT_EXORoleAssignmentPolicy.psm1 index 37a5795d20..9e3f4591d9 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXORoleAssignmentPolicy/MSFT_EXORoleAssignmentPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXORoleAssignmentPolicy/MSFT_EXORoleAssignmentPolicy.psm1 @@ -59,67 +59,63 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Role Assignment Policy configuration for $Name" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Role Assignment Policy configuration for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - try - { - $AllRoleAssignmentPolicies = Get-RoleAssignmentPolicy -ErrorAction Stop + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - $RoleAssignmentPolicy = $AllRoleAssignmentPolicies | Where-Object -FilterScript { $_.Name -eq $Name } + $AllRoleAssignmentPolicies = Get-RoleAssignmentPolicy -ErrorAction Stop - if ($null -eq $RoleAssignmentPolicy) - { - Write-Verbose -Message "Role Assignment Policy $($Name) does not exist." - return $nullReturn + $RoleAssignmentPolicy = $AllRoleAssignmentPolicies | Where-Object -FilterScript { $_.Name -eq $Name } + + if ($null -eq $RoleAssignmentPolicy) + { + Write-Verbose -Message "Role Assignment Policy $($Name) does not exist." + return $nullReturn + } } else { - $result = @{ - Name = $RoleAssignmentPolicy.Name - Description = $RoleAssignmentPolicy.Description - IsDefault = $RoleAssignmentPolicy.IsDefault - Roles = $RoleAssignmentPolicy.AssignedRoles - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } + $RoleAssignmentPolicy = $Script:exportedInstance + } - Write-Verbose -Message "Found Role Assignment Policy $($Name)" - return $result + $result = @{ + Name = $RoleAssignmentPolicy.Name + Description = $RoleAssignmentPolicy.Description + IsDefault = $RoleAssignmentPolicy.IsDefault + Roles = $RoleAssignmentPolicy.AssignedRoles + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found Role Assignment Policy $($Name)" + return $result } catch { @@ -454,6 +450,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $RoleAssignmentPolicy $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXORoleGroup/MSFT_EXORoleGroup.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXORoleGroup/MSFT_EXORoleGroup.psm1 index 040ebe5990..ca53609d6e 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXORoleGroup/MSFT_EXORoleGroup.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXORoleGroup/MSFT_EXORoleGroup.psm1 @@ -59,66 +59,64 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Role Group configuration for $Name" - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters + try + { + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Role Group configuration for $Name" + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $RoleGroup = $Script:exportedInstances | Where-Object -FilterScript { $_.Name -eq $Name } - } - else - { $AllRoleGroups = Get-RoleGroup -ErrorAction Stop $RoleGroup = $AllRoleGroups | Where-Object -FilterScript { $_.Name -eq $Name } - } - if ($null -eq $RoleGroup) - { - Write-Verbose -Message "Role Group $($Name) does not exist." - return $nullReturn + if ($null -eq $RoleGroup) + { + Write-Verbose -Message "Role Group $($Name) does not exist." + return $nullReturn + } } else { - # Get RoleGroup Members DN if RoleGroup exists. This is required especially when adding Members like "Exchange Administrator" or "Global Administrator" that have different Names across Tenants - $roleGroupMember = Get-RoleGroupMember -Identity $Name | Select-Object DisplayName - - $result = @{ - Name = $RoleGroup.Name - Description = $RoleGroup.Description - Members = $roleGroupMember.DisplayName - Roles = $RoleGroup.Roles - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } + $RoleGroup = $Script:exportedInstance + } - Write-Verbose -Message "Found Role Group $($Name)" - return $result + # Get RoleGroup Members DN if RoleGroup exists. This is required especially when adding Members like "Exchange Administrator" or "Global Administrator" that have different Names across Tenants + $roleGroupMember = Get-RoleGroupMember -Identity $Name | Select-Object DisplayName + + $result = @{ + Name = $RoleGroup.Name + Description = $RoleGroup.Description + Members = $roleGroupMember.DisplayName + Roles = $RoleGroup.Roles + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found Role Group $($Name)" + return $result } catch { @@ -458,6 +456,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $RoleGroup $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOSharedMailbox/MSFT_EXOSharedMailbox.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOSharedMailbox/MSFT_EXOSharedMailbox.psm1 index 54ee8e009f..63c35441ce 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOSharedMailbox/MSFT_EXOSharedMailbox.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOSharedMailbox/MSFT_EXOSharedMailbox.psm1 @@ -62,60 +62,40 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Office 365 Shared Mailbox $DisplayName" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try { - try + if (-not $Script:exportedInstance) { - if (-not [System.String]::IsNullOrEmpty($Identity)) + Write-Verbose -Message "Getting configuration of Office 365 Shared Mailbox $DisplayName" + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + try { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $mailbox = $Script:exportedInstances | Where-Object -FilterScript { $_.Identity -eq $Identity } - } - else + if (-not [System.String]::IsNullOrEmpty($Identity)) { $mailbox = $mailbox = Get-Mailbox -Identity $Identity ` -RecipientTypeDetails 'SharedMailbox' ` -ResultSize Unlimited ` -ErrorAction Stop } - } - if ($null -eq $mailbox) - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $mailbox = $Script:exportedInstances | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } - } - else + if ($null -eq $mailbox) { $mailbox = $mailbox = Get-Mailbox -Identity $DisplayName ` -RecipientTypeDetails 'SharedMailbox' ` @@ -123,16 +103,20 @@ function Get-TargetResource -ErrorAction Stop } } - } - catch - { - Write-Verbose -Message "Could not retrieve AAD roledefinition by Id: {$Id}" - } + catch + { + Write-Verbose -Message "Could not retrieve AAD roledefinition by Id: {$Id}" + } - if ($null -eq $mailbox) + if ($null -eq $mailbox) + { + Write-Verbose -Message "The specified Shared Mailbox doesn't already exist." + return $nullReturn + } + } + else { - Write-Verbose -Message "The specified Shared Mailbox doesn't already exist." - return $nullReturn + $mailbox = $Script:exportedInstance } #region EmailAddresses @@ -554,6 +538,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $mailbox $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOTransportRule/MSFT_EXOTransportRule.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOTransportRule/MSFT_EXOTransportRule.psm1 index de0953b922..135dca0b4a 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_EXOTransportRule/MSFT_EXOTransportRule.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_EXOTransportRule/MSFT_EXOTransportRule.psm1 @@ -739,258 +739,255 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Transport Rule configuration for $Name" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Transport Rule configuration for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $TransportRule = Get-TransportRule -Identity $Name -ErrorAction 'SilentlyContinue' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - try - { - if ($null -eq $TransportRule) - { - Write-Verbose -Message "Transport Rule $($Name) does not exist." - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - return $nullReturn + $TransportRule = Get-TransportRule -Identity $Name -ErrorAction 'SilentlyContinue' + + if ($null -eq $TransportRule) + { + Write-Verbose -Message "Transport Rule $($Name) does not exist." + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + return $nullReturn + } } else { - $MessageContainsDataClassificationsValue = $null - if ($null -ne $TransportRule.MessageContainsDataClassifications) - { - $MessageContainsDataClassificationsValue = $TransportRule.MessageContainsDataClassifications.Replace('"', "'") - } + $TransportRule = $Script:exportedInstance + } - if ($TransportRule.State -eq 'Enabled') - { - $enabled = $true - } - else - { - $enabled = $false - } - $result = @{ - Name = $TransportRule.Name - ADComparisonAttribute = $TransportRule.ADComparisonAttribute - ADComparisonOperator = $TransportRule.ADComparisonOperator - ActivationDate = $TransportRule.ActivationDate - AddManagerAsRecipientType = $TransportRule.AddManagerAsRecipientType - AddToRecipients = $TransportRule.AddToRecipients - AnyOfCcHeader = $TransportRule.AnyOfCcHeader - AnyOfCcHeaderMemberOf = $TransportRule.AnyOfCcHeaderMemberOf - AnyOfRecipientAddressContainsWords = $TransportRule.AnyOfRecipientAddressContainsWords - AnyOfRecipientAddressMatchesPatterns = $TransportRule.AnyOfRecipientAddressMatchesPatterns - AnyOfToCcHeader = $TransportRule.AnyOfToCcHeader - AnyOfToCcHeaderMemberOf = $TransportRule.AnyOfToCcHeaderMemberOf - AnyOfToHeader = $TransportRule.AnyOfToHeader - AnyOfToHeaderMemberOf = $TransportRule.AnyOfToHeaderMemberOf - ApplyClassification = $TransportRule.ApplyClassification - ApplyHtmlDisclaimerFallbackAction = $TransportRule.ApplyHtmlDisclaimerFallbackAction - ApplyHtmlDisclaimerLocation = $TransportRule.ApplyHtmlDisclaimerLocation - ApplyHtmlDisclaimerText = $TransportRule.ApplyHtmlDisclaimerText - ApplyOME = $TransportRule.ApplyOME - ApplyRightsProtectionCustomizationTemplate = $TransportRule.ApplyRightsProtectionCustomizationTemplate - ApplyRightsProtectionTemplate = $TransportRule.ApplyRightsProtectionTemplate - AttachmentContainsWords = $TransportRule.AttachmentContainsWords - AttachmentExtensionMatchesWords = $TransportRule.AttachmentExtensionMatchesWords - AttachmentHasExecutableContent = $TransportRule.AttachmentHasExecutableContent - AttachmentIsPasswordProtected = $TransportRule.AttachmentIsPasswordProtected - AttachmentIsUnsupported = $TransportRule.AttachmentIsUnsupported - AttachmentMatchesPatterns = $TransportRule.AttachmentMatchesPatterns - AttachmentNameMatchesPatterns = $TransportRule.AttachmentNameMatchesPatterns - AttachmentPropertyContainsWords = $TransportRule.AttachmentPropertyContainsWords - AttachmentProcessingLimitExceeded = $TransportRule.AttachmentProcessingLimitExceeded - AttachmentSizeOver = $TransportRule.AttachmentSizeOver - BetweenMemberOf1 = $TransportRule.BetweenMemberOf1 - BetweenMemberOf2 = $TransportRule.BetweenMemberOf2 - BlindCopyTo = $TransportRule.BlindCopyTo - Comments = $TransportRule.Comments - ContentCharacterSetContainsWords = $TransportRule.ContentCharacterSetContainsWords - CopyTo = $TransportRule.CopyTo - DeleteMessage = $TransportRule.DeleteMessage - DlpPolicy = $TransportRule.DlpPolicy - Enabled = $enabled - ExceptIfADComparisonAttribute = $TransportRule.ExceptIfADComparisonAttribute - ExceptIfADComparisonOperator = $TransportRule.ExceptIfADComparisonOperator - ExceptIfAnyOfCcHeader = $TransportRule.ExceptIfAnyOfCcHeader - ExceptIfAnyOfCcHeaderMemberOf = $TransportRule.ExceptIfAnyOfCcHeaderMemberOf - ExceptIfAnyOfRecipientAddressContainsWords = $TransportRule.ExceptIfAnyOfRecipientAddressContainsWords - ExceptIfAnyOfRecipientAddressMatchesPatterns = $TransportRule.ExceptIfAnyOfRecipientAddressMatchesPatterns - ExceptIfAnyOfToCcHeader = $TransportRule.ExceptIfAnyOfToCcHeader - ExceptIfAnyOfToCcHeaderMemberOf = $TransportRule.ExceptIfAnyOfToCcHeaderMemberOf - ExceptIfAnyOfToHeader = $TransportRule.ExceptIfAnyOfToHeader - ExceptIfAnyOfToHeaderMemberOf = $TransportRule.ExceptIfAnyOfToHeaderMemberOf - ExceptIfAttachmentContainsWords = $TransportRule.ExceptIfAttachmentContainsWords - ExceptIfAttachmentExtensionMatchesWords = $TransportRule.ExceptIfAttachmentExtensionMatchesWords - ExceptIfAttachmentHasExecutableContent = $TransportRule.ExceptIfAttachmentHasExecutableContent - ExceptIfAttachmentIsPasswordProtected = $TransportRule.ExceptIfAttachmentIsPasswordProtected - ExceptIfAttachmentIsUnsupported = $TransportRule.ExceptIfAttachmentIsUnsupported - ExceptIfAttachmentMatchesPatterns = $TransportRule.ExceptIfAttachmentMatchesPatterns - ExceptIfAttachmentNameMatchesPatterns = $TransportRule.ExceptIfAttachmentNameMatchesPatterns - ExceptIfAttachmentPropertyContainsWords = $TransportRule.ExceptIfAttachmentPropertyContainsWords - ExceptIfAttachmentProcessingLimitExceeded = $TransportRule.ExceptIfAttachmentProcessingLimitExceeded - ExceptIfAttachmentSizeOver = $TransportRule.ExceptIfAttachmentSizeOver - ExceptIfBetweenMemberOf1 = $TransportRule.ExceptIfBetweenMemberOf1 - ExceptIfBetweenMemberOf2 = $TransportRule.ExceptIfBetweenMemberOf2 - ExceptIfContentCharacterSetContainsWords = $TransportRule.ExceptIfContentCharacterSetContainsWords - ExceptIfFrom = $TransportRule.ExceptIfFrom - ExceptIfFromAddressContainsWords = $TransportRule.ExceptIfFromAddressContainsWords - ExceptIfFromAddressMatchesPatterns = $TransportRule.ExceptIfFromAddressMatchesPatterns - ExceptIfFromMemberOf = $TransportRule.ExceptIfFromMemberOf - ExceptIfFromScope = $TransportRule.ExceptIfFromScope - ExceptIfHasClassification = $TransportRule.ExceptIfHasClassification - ExceptIfHasNoClassification = $TransportRule.ExceptIfHasNoClassification - ExceptIfHeaderContainsMessageHeader = $TransportRule.ExceptIfHeaderContainsMessageHeader - ExceptIfHeaderContainsWords = $TransportRule.ExceptIfHeaderContainsWords - ExceptIfHeaderMatchesMessageHeader = $TransportRule.ExceptIfHeaderMatchesMessageHeader - ExceptIfHeaderMatchesPatterns = $TransportRule.ExceptIfHeaderMatchesPatterns - ExceptIfManagerAddresses = $TransportRule.ExceptIfManagerAddresses - ExceptIfManagerForEvaluatedUser = $TransportRule.ExceptIfManagerForEvaluatedUser - ExceptIfMessageTypeMatches = $TransportRule.ExceptIfMessageTypeMatches - ExceptIfMessageSizeOver = $TransportRule.ExceptIfMessageSizeOver - ExceptIfRecipientADAttributeContainsWords = $TransportRule.ExceptIfRecipientADAttributeContainsWords - ExceptIfRecipientADAttributeMatchesPatterns = $TransportRule.ExceptIfRecipientADAttributeMatchesPatterns - ExceptIfRecipientAddressContainsWords = $TransportRule.ExceptIfRecipientAddressContainsWords - ExceptIfRecipientAddressMatchesPatterns = $TransportRule.ExceptIfRecipientAddressMatchesPatterns - ExceptIfRecipientDomainIs = $TransportRule.ExceptIfRecipientDomainIs - ExceptIfRecipientInSenderList = $TransportRule.ExceptIfRecipientInSenderList - ExceptIfSCLOver = $TransportRule.ExceptIfSCLOver - ExceptIfSenderADAttributeContainsWords = $TransportRule.ExceptIfSenderADAttributeContainsWords - ExceptIfSenderADAttributeMatchesPatterns = $TransportRule.ExceptIfSenderADAttributeMatchesPatterns - ExceptIfSenderDomainIs = $TransportRule.ExceptIfSenderDomainIs - ExceptIfSenderInRecipientList = $TransportRule.ExceptIfSenderInRecipientList - ExceptIfSenderIpRanges = $TransportRule.ExceptIfSenderIpRanges - ExceptIfSenderManagementRelationship = $TransportRule.ExceptIfSenderManagementRelationship - ExceptIfSentTo = $TransportRule.ExceptIfSentTo - ExceptIfSentToMemberOf = $TransportRule.ExceptIfSentToMemberOf - ExceptIfSentToScope = $TransportRule.ExceptIfSentToScope - ExceptIfSubjectContainsWords = $TransportRule.ExceptIfSubjectContainsWords - ExceptIfSubjectMatchesPatterns = $TransportRule.ExceptIfSubjectMatchesPatterns - ExceptIfSubjectOrBodyContainsWords = $TransportRule.ExceptIfSubjectOrBodyContainsWords - ExceptIfSubjectOrBodyMatchesPatterns = $TransportRule.ExceptIfSubjectOrBodyMatchesPatterns - ExceptIfWithImportance = $TransportRule.ExceptIfWithImportance - ExpiryDate = $TransportRule.ExpiryDate - From = $TransportRule.From - FromAddressContainsWords = $TransportRule.FromAddressContainsWords - FromAddressMatchesPatterns = $TransportRule.FromAddressMatchesPatterns - FromMemberOf = $TransportRule.FromMemberOf - FromScope = $TransportRule.FromScope - GenerateIncidentReport = $TransportRule.GenerateIncidentReport - GenerateNotification = $TransportRule.GenerateNotification - HasClassification = $TransportRule.HasClassification - HasNoClassification = $TransportRule.HasNoClassification - HeaderContainsMessageHeader = $TransportRule.HeaderContainsMessageHeader - HeaderContainsWords = $TransportRule.HeaderContainsWords - HeaderMatchesMessageHeader = $TransportRule.HeaderMatchesMessageHeader - HeaderMatchesPatterns = $TransportRule.HeaderMatchesPatterns - IncidentReportContent = $TransportRule.IncidentReportContent - ManagerAddresses = $TransportRule.ManagerAddresses - ManagerForEvaluatedUser = $TransportRule.ManagerForEvaluatedUser - MessageSizeOver = $TransportRule.MessageSizeOver - MessageTypeMatches = $TransportRule.MessageTypeMatches - Mode = $TransportRule.Mode - ModerateMessageByManager = $TransportRule.ModerateMessageByManager - ModerateMessageByUser = $TransportRule.ModerateMessageByUser - PrependSubject = $TransportRule.PrependSubject - Priority = $TransportRule.Priority - Quarantine = $TransportRule.Quarantine - RecipientADAttributeContainsWords = $TransportRule.RecipientADAttributeContainsWords - RecipientADAttributeMatchesPatterns = $TransportRule.RecipientADAttributeMatchesPatterns - RecipientAddressContainsWords = $TransportRule.RecipientAddressContainsWords - RecipientAddressMatchesPatterns = $TransportRule.RecipientAddressMatchesPatterns - RecipientAddressType = $TransportRule.RecipientAddressType - RecipientDomainIs = $TransportRule.RecipientDomainIs - RecipientInSenderList = $TransportRule.RecipientInSenderList - RedirectMessageTo = $TransportRule.RedirectMessageTo - RejectMessageEnhancedStatusCode = $TransportRule.RejectMessageEnhancedStatusCode - RejectMessageReasonText = $TransportRule.RejectMessageReasonText - RemoveHeader = $TransportRule.RemoveHeader - RemoveOME = $TransportRule.RemoveOME - RemoveOMEv2 = $TransportRule.RemoveOMEv2 - RemoveRMSAttachmentEncryption = $TransportRule.RemoveRMSAttachmentEncryption - RouteMessageOutboundConnector = $TransportRule.RouteMessageOutboundConnector - RouteMessageOutboundRequireTls = $TransportRule.RouteMessageOutboundRequireTls - RuleErrorAction = $TransportRule.RuleErrorAction - RuleSubType = $TransportRule.RuleSubType - SCLOver = $TransportRule.SCLOver - SenderADAttributeContainsWords = $TransportRule.SenderADAttributeContainsWords - SenderADAttributeMatchesPatterns = $TransportRule.SenderADAttributeMatchesPatterns - SenderAddressLocation = $TransportRule.SenderAddressLocation - SenderDomainIs = $TransportRule.SenderDomainIs - SenderInRecipientList = $TransportRule.SenderInRecipientList - SenderIpRanges = $TransportRule.SenderIpRanges - SenderManagementRelationship = $TransportRule.SenderManagementRelationship - SentTo = $TransportRule.SentTo - SentToMemberOf = $TransportRule.SentToMemberOf - SentToScope = $TransportRule.SentToScope - SetAuditSeverity = $TransportRule.SetAuditSeverity - SetHeaderName = $TransportRule.SetHeaderName - SetHeaderValue = $TransportRule.SetHeaderValue - SetSCL = $TransportRule.SetSCL - StopRuleProcessing = $TransportRule.StopRuleProcessing - SubjectContainsWords = $TransportRule.SubjectContainsWords - SubjectMatchesPatterns = $TransportRule.SubjectMatchesPatterns - SubjectOrBodyContainsWords = $TransportRule.SubjectOrBodyContainsWords - SubjectOrBodyMatchesPatterns = $TransportRule.SubjectOrBodyMatchesPatterns - WithImportance = $TransportRule.WithImportance - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } - $inputParams = (Get-Command 'Get-TargetResource').Parameters - foreach ($key in $inputParams.Keys) - { - $propertyInfo = $inputParams.$key - $curVar = $TransportRule.$key - if ($propertyInfo.ParameterType.Name -eq 'String[]' -and $curVar -eq $null) - { - $result.$key = @() - } - } + $MessageContainsDataClassificationsValue = $null + if ($null -ne $TransportRule.MessageContainsDataClassifications) + { + $MessageContainsDataClassificationsValue = $TransportRule.MessageContainsDataClassifications.Replace('"', "'") + } - # Formats DateTime as String - if ($null -ne $result.ActivationDate) - { - $result.ActivationDate = $TransportRule.ActivationDate.ToUniversalTime().ToString() - } - if ($null -ne $result.ExpiryDate) + if ($TransportRule.State -eq 'Enabled') + { + $enabled = $true + } + else + { + $enabled = $false + } + + $result = @{ + Name = $TransportRule.Name + ADComparisonAttribute = $TransportRule.ADComparisonAttribute + ADComparisonOperator = $TransportRule.ADComparisonOperator + ActivationDate = $TransportRule.ActivationDate + AddManagerAsRecipientType = $TransportRule.AddManagerAsRecipientType + AddToRecipients = $TransportRule.AddToRecipients + AnyOfCcHeader = $TransportRule.AnyOfCcHeader + AnyOfCcHeaderMemberOf = $TransportRule.AnyOfCcHeaderMemberOf + AnyOfRecipientAddressContainsWords = $TransportRule.AnyOfRecipientAddressContainsWords + AnyOfRecipientAddressMatchesPatterns = $TransportRule.AnyOfRecipientAddressMatchesPatterns + AnyOfToCcHeader = $TransportRule.AnyOfToCcHeader + AnyOfToCcHeaderMemberOf = $TransportRule.AnyOfToCcHeaderMemberOf + AnyOfToHeader = $TransportRule.AnyOfToHeader + AnyOfToHeaderMemberOf = $TransportRule.AnyOfToHeaderMemberOf + ApplyClassification = $TransportRule.ApplyClassification + ApplyHtmlDisclaimerFallbackAction = $TransportRule.ApplyHtmlDisclaimerFallbackAction + ApplyHtmlDisclaimerLocation = $TransportRule.ApplyHtmlDisclaimerLocation + ApplyHtmlDisclaimerText = $TransportRule.ApplyHtmlDisclaimerText + ApplyOME = $TransportRule.ApplyOME + ApplyRightsProtectionCustomizationTemplate = $TransportRule.ApplyRightsProtectionCustomizationTemplate + ApplyRightsProtectionTemplate = $TransportRule.ApplyRightsProtectionTemplate + AttachmentContainsWords = $TransportRule.AttachmentContainsWords + AttachmentExtensionMatchesWords = $TransportRule.AttachmentExtensionMatchesWords + AttachmentHasExecutableContent = $TransportRule.AttachmentHasExecutableContent + AttachmentIsPasswordProtected = $TransportRule.AttachmentIsPasswordProtected + AttachmentIsUnsupported = $TransportRule.AttachmentIsUnsupported + AttachmentMatchesPatterns = $TransportRule.AttachmentMatchesPatterns + AttachmentNameMatchesPatterns = $TransportRule.AttachmentNameMatchesPatterns + AttachmentPropertyContainsWords = $TransportRule.AttachmentPropertyContainsWords + AttachmentProcessingLimitExceeded = $TransportRule.AttachmentProcessingLimitExceeded + AttachmentSizeOver = $TransportRule.AttachmentSizeOver + BetweenMemberOf1 = $TransportRule.BetweenMemberOf1 + BetweenMemberOf2 = $TransportRule.BetweenMemberOf2 + BlindCopyTo = $TransportRule.BlindCopyTo + Comments = $TransportRule.Comments + ContentCharacterSetContainsWords = $TransportRule.ContentCharacterSetContainsWords + CopyTo = $TransportRule.CopyTo + DeleteMessage = $TransportRule.DeleteMessage + DlpPolicy = $TransportRule.DlpPolicy + Enabled = $enabled + ExceptIfADComparisonAttribute = $TransportRule.ExceptIfADComparisonAttribute + ExceptIfADComparisonOperator = $TransportRule.ExceptIfADComparisonOperator + ExceptIfAnyOfCcHeader = $TransportRule.ExceptIfAnyOfCcHeader + ExceptIfAnyOfCcHeaderMemberOf = $TransportRule.ExceptIfAnyOfCcHeaderMemberOf + ExceptIfAnyOfRecipientAddressContainsWords = $TransportRule.ExceptIfAnyOfRecipientAddressContainsWords + ExceptIfAnyOfRecipientAddressMatchesPatterns = $TransportRule.ExceptIfAnyOfRecipientAddressMatchesPatterns + ExceptIfAnyOfToCcHeader = $TransportRule.ExceptIfAnyOfToCcHeader + ExceptIfAnyOfToCcHeaderMemberOf = $TransportRule.ExceptIfAnyOfToCcHeaderMemberOf + ExceptIfAnyOfToHeader = $TransportRule.ExceptIfAnyOfToHeader + ExceptIfAnyOfToHeaderMemberOf = $TransportRule.ExceptIfAnyOfToHeaderMemberOf + ExceptIfAttachmentContainsWords = $TransportRule.ExceptIfAttachmentContainsWords + ExceptIfAttachmentExtensionMatchesWords = $TransportRule.ExceptIfAttachmentExtensionMatchesWords + ExceptIfAttachmentHasExecutableContent = $TransportRule.ExceptIfAttachmentHasExecutableContent + ExceptIfAttachmentIsPasswordProtected = $TransportRule.ExceptIfAttachmentIsPasswordProtected + ExceptIfAttachmentIsUnsupported = $TransportRule.ExceptIfAttachmentIsUnsupported + ExceptIfAttachmentMatchesPatterns = $TransportRule.ExceptIfAttachmentMatchesPatterns + ExceptIfAttachmentNameMatchesPatterns = $TransportRule.ExceptIfAttachmentNameMatchesPatterns + ExceptIfAttachmentPropertyContainsWords = $TransportRule.ExceptIfAttachmentPropertyContainsWords + ExceptIfAttachmentProcessingLimitExceeded = $TransportRule.ExceptIfAttachmentProcessingLimitExceeded + ExceptIfAttachmentSizeOver = $TransportRule.ExceptIfAttachmentSizeOver + ExceptIfBetweenMemberOf1 = $TransportRule.ExceptIfBetweenMemberOf1 + ExceptIfBetweenMemberOf2 = $TransportRule.ExceptIfBetweenMemberOf2 + ExceptIfContentCharacterSetContainsWords = $TransportRule.ExceptIfContentCharacterSetContainsWords + ExceptIfFrom = $TransportRule.ExceptIfFrom + ExceptIfFromAddressContainsWords = $TransportRule.ExceptIfFromAddressContainsWords + ExceptIfFromAddressMatchesPatterns = $TransportRule.ExceptIfFromAddressMatchesPatterns + ExceptIfFromMemberOf = $TransportRule.ExceptIfFromMemberOf + ExceptIfFromScope = $TransportRule.ExceptIfFromScope + ExceptIfHasClassification = $TransportRule.ExceptIfHasClassification + ExceptIfHasNoClassification = $TransportRule.ExceptIfHasNoClassification + ExceptIfHeaderContainsMessageHeader = $TransportRule.ExceptIfHeaderContainsMessageHeader + ExceptIfHeaderContainsWords = $TransportRule.ExceptIfHeaderContainsWords + ExceptIfHeaderMatchesMessageHeader = $TransportRule.ExceptIfHeaderMatchesMessageHeader + ExceptIfHeaderMatchesPatterns = $TransportRule.ExceptIfHeaderMatchesPatterns + ExceptIfManagerAddresses = $TransportRule.ExceptIfManagerAddresses + ExceptIfManagerForEvaluatedUser = $TransportRule.ExceptIfManagerForEvaluatedUser + ExceptIfMessageTypeMatches = $TransportRule.ExceptIfMessageTypeMatches + ExceptIfMessageSizeOver = $TransportRule.ExceptIfMessageSizeOver + ExceptIfRecipientADAttributeContainsWords = $TransportRule.ExceptIfRecipientADAttributeContainsWords + ExceptIfRecipientADAttributeMatchesPatterns = $TransportRule.ExceptIfRecipientADAttributeMatchesPatterns + ExceptIfRecipientAddressContainsWords = $TransportRule.ExceptIfRecipientAddressContainsWords + ExceptIfRecipientAddressMatchesPatterns = $TransportRule.ExceptIfRecipientAddressMatchesPatterns + ExceptIfRecipientDomainIs = $TransportRule.ExceptIfRecipientDomainIs + ExceptIfRecipientInSenderList = $TransportRule.ExceptIfRecipientInSenderList + ExceptIfSCLOver = $TransportRule.ExceptIfSCLOver + ExceptIfSenderADAttributeContainsWords = $TransportRule.ExceptIfSenderADAttributeContainsWords + ExceptIfSenderADAttributeMatchesPatterns = $TransportRule.ExceptIfSenderADAttributeMatchesPatterns + ExceptIfSenderDomainIs = $TransportRule.ExceptIfSenderDomainIs + ExceptIfSenderInRecipientList = $TransportRule.ExceptIfSenderInRecipientList + ExceptIfSenderIpRanges = $TransportRule.ExceptIfSenderIpRanges + ExceptIfSenderManagementRelationship = $TransportRule.ExceptIfSenderManagementRelationship + ExceptIfSentTo = $TransportRule.ExceptIfSentTo + ExceptIfSentToMemberOf = $TransportRule.ExceptIfSentToMemberOf + ExceptIfSentToScope = $TransportRule.ExceptIfSentToScope + ExceptIfSubjectContainsWords = $TransportRule.ExceptIfSubjectContainsWords + ExceptIfSubjectMatchesPatterns = $TransportRule.ExceptIfSubjectMatchesPatterns + ExceptIfSubjectOrBodyContainsWords = $TransportRule.ExceptIfSubjectOrBodyContainsWords + ExceptIfSubjectOrBodyMatchesPatterns = $TransportRule.ExceptIfSubjectOrBodyMatchesPatterns + ExceptIfWithImportance = $TransportRule.ExceptIfWithImportance + ExpiryDate = $TransportRule.ExpiryDate + From = $TransportRule.From + FromAddressContainsWords = $TransportRule.FromAddressContainsWords + FromAddressMatchesPatterns = $TransportRule.FromAddressMatchesPatterns + FromMemberOf = $TransportRule.FromMemberOf + FromScope = $TransportRule.FromScope + GenerateIncidentReport = $TransportRule.GenerateIncidentReport + GenerateNotification = $TransportRule.GenerateNotification + HasClassification = $TransportRule.HasClassification + HasNoClassification = $TransportRule.HasNoClassification + HeaderContainsMessageHeader = $TransportRule.HeaderContainsMessageHeader + HeaderContainsWords = $TransportRule.HeaderContainsWords + HeaderMatchesMessageHeader = $TransportRule.HeaderMatchesMessageHeader + HeaderMatchesPatterns = $TransportRule.HeaderMatchesPatterns + IncidentReportContent = $TransportRule.IncidentReportContent + ManagerAddresses = $TransportRule.ManagerAddresses + ManagerForEvaluatedUser = $TransportRule.ManagerForEvaluatedUser + MessageSizeOver = $TransportRule.MessageSizeOver + MessageTypeMatches = $TransportRule.MessageTypeMatches + Mode = $TransportRule.Mode + ModerateMessageByManager = $TransportRule.ModerateMessageByManager + ModerateMessageByUser = $TransportRule.ModerateMessageByUser + PrependSubject = $TransportRule.PrependSubject + Priority = $TransportRule.Priority + Quarantine = $TransportRule.Quarantine + RecipientADAttributeContainsWords = $TransportRule.RecipientADAttributeContainsWords + RecipientADAttributeMatchesPatterns = $TransportRule.RecipientADAttributeMatchesPatterns + RecipientAddressContainsWords = $TransportRule.RecipientAddressContainsWords + RecipientAddressMatchesPatterns = $TransportRule.RecipientAddressMatchesPatterns + RecipientAddressType = $TransportRule.RecipientAddressType + RecipientDomainIs = $TransportRule.RecipientDomainIs + RecipientInSenderList = $TransportRule.RecipientInSenderList + RedirectMessageTo = $TransportRule.RedirectMessageTo + RejectMessageEnhancedStatusCode = $TransportRule.RejectMessageEnhancedStatusCode + RejectMessageReasonText = $TransportRule.RejectMessageReasonText + RemoveHeader = $TransportRule.RemoveHeader + RemoveOME = $TransportRule.RemoveOME + RemoveOMEv2 = $TransportRule.RemoveOMEv2 + RemoveRMSAttachmentEncryption = $TransportRule.RemoveRMSAttachmentEncryption + RouteMessageOutboundConnector = $TransportRule.RouteMessageOutboundConnector + RouteMessageOutboundRequireTls = $TransportRule.RouteMessageOutboundRequireTls + RuleErrorAction = $TransportRule.RuleErrorAction + RuleSubType = $TransportRule.RuleSubType + SCLOver = $TransportRule.SCLOver + SenderADAttributeContainsWords = $TransportRule.SenderADAttributeContainsWords + SenderADAttributeMatchesPatterns = $TransportRule.SenderADAttributeMatchesPatterns + SenderAddressLocation = $TransportRule.SenderAddressLocation + SenderDomainIs = $TransportRule.SenderDomainIs + SenderInRecipientList = $TransportRule.SenderInRecipientList + SenderIpRanges = $TransportRule.SenderIpRanges + SenderManagementRelationship = $TransportRule.SenderManagementRelationship + SentTo = $TransportRule.SentTo + SentToMemberOf = $TransportRule.SentToMemberOf + SentToScope = $TransportRule.SentToScope + SetAuditSeverity = $TransportRule.SetAuditSeverity + SetHeaderName = $TransportRule.SetHeaderName + SetHeaderValue = $TransportRule.SetHeaderValue + SetSCL = $TransportRule.SetSCL + StopRuleProcessing = $TransportRule.StopRuleProcessing + SubjectContainsWords = $TransportRule.SubjectContainsWords + SubjectMatchesPatterns = $TransportRule.SubjectMatchesPatterns + SubjectOrBodyContainsWords = $TransportRule.SubjectOrBodyContainsWords + SubjectOrBodyMatchesPatterns = $TransportRule.SubjectOrBodyMatchesPatterns + WithImportance = $TransportRule.WithImportance + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens + } + $inputParams = (Get-Command 'Get-TargetResource').Parameters + foreach ($key in $inputParams.Keys) + { + $propertyInfo = $inputParams.$key + $curVar = $TransportRule.$key + if ($propertyInfo.ParameterType.Name -eq 'String[]' -and $curVar -eq $null) { - $result.ExpiryDate = $TransportRule.ExpiryDate.ToUniversalTime().ToString() + $result.$key = @() } + } - Write-Verbose -Message "Found Transport Rule $($Name)" - return $result + # Formats DateTime as String + if ($null -ne $result.ActivationDate) + { + $result.ActivationDate = $TransportRule.ActivationDate.ToUniversalTime().ToString() + } + if ($null -ne $result.ExpiryDate) + { + $result.ExpiryDate = $TransportRule.ExpiryDate.ToUniversalTime().ToString() } + + Write-Verbose -Message "Found Transport Rule $($Name)" + return $result } catch { @@ -1823,7 +1820,7 @@ function Set-TargetResource } # CASE: Transport Rule exists and it should, but has different values than the desired ones elseif ($Ensure -eq 'Present' -and $currentTransportRuleConfig.Ensure -eq 'Present') - { + { if ($null -ne $HeaderContainsMessageHeader -and $null -eq $currentTransportRuleConfig.HeaderContainsMessageHeader) { $SetTransportRuleParams.Add("HeaderContainsMessageHeader",$null) @@ -1835,7 +1832,7 @@ function Set-TargetResource if ($null -ne $ExceptIfHeaderContainsWords -and $null -eq $currentTransportRuleConfig.ExceptIfHeaderContainsMessageHeader) { $SetTransportRuleParams.Add("ExceptIfHeaderContainsMessageHeader",$null) - } + } if ($null -ne $ExceptIfHeaderMatchesPatterns -and $null -eq $currentTransportRuleConfig.ExceptIfHeaderMatchesMessageHeader) { $SetTransportRuleParams.Add("ExceptIfHeaderMatchesMessageHeader",$null) @@ -2715,6 +2712,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $TransportRule $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_O365Group/MSFT_O365Group.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_O365Group/MSFT_O365Group.psm1 index 43d40e0b40..3b2e779975 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_O365Group/MSFT_O365Group.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_O365Group/MSFT_O365Group.psm1 @@ -58,54 +58,62 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Setting configuration of Office 365 Group $DisplayName" - $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try { - Write-Verbose -Message "Retrieving AzureADGroup by MailNickName {$MailNickName}" - [array]$ADGroup = Get-MgGroup -All:$true | Where-Object -FilterScript { $_.MailNickName -eq $MailNickName } - if ($null -eq $ADGroup) + if (-not $Script:exportedInstance) { - Write-Verbose -Message "Retrieving AzureADGroup by DisplayName {$DisplayName}" - [array]$ADGroup = Get-MgGroup -All:$true | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } + Write-Verbose -Message "Setting configuration of Office 365 Group $DisplayName" + $ConnectionMode = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + Write-Verbose -Message "Retrieving AzureADGroup by MailNickName {$MailNickName}" + [array]$ADGroup = Get-MgGroup -All:$true | Where-Object -FilterScript { $_.MailNickName -eq $MailNickName } if ($null -eq $ADGroup) { - Write-Verbose -Message "Office 365 Group {$DisplayName} was not found." - return $nullReturn + Write-Verbose -Message "Retrieving AzureADGroup by DisplayName {$DisplayName}" + [array]$ADGroup = Get-MgGroup -All:$true | Where-Object -FilterScript { $_.DisplayName -eq $DisplayName } + if ($null -eq $ADGroup) + { + Write-Verbose -Message "Office 365 Group {$DisplayName} was not found." + return $nullReturn + } } - elseif ($ADGroup.Length -gt 1) + if ($ADGroup.Length -gt 1) { $Message = "Multiple O365 groups were found with DisplayName {$DisplayName}. Please specify the MailNickName parameter to uniquely identify the group." New-M365DSCLogEntry -Message $Message ` -Exception $_ ` -Source $MyInvocation.MyCommand.ModuleName } + $ADGroup = $ADGroup[0] + } + else + { + $ADGroup = $Script:exportedInstance } Write-Verbose -Message "Found Existing Instance of Group {$($ADGroup.DisplayName)}" try { - $membersList = Get-MgGroupMember -GroupId $ADGroup[0].Id - Write-Verbose -Message "Found Members for Group {$($ADGroup[0].DisplayName)}" - $owners = Get-MgGroupOwner -GroupId $ADGroup[0].Id - Write-Verbose -Message "Found Owners for Group {$($ADGroup[0].DisplayName)}" + $membersList = Get-MgGroupMember -GroupId $ADGroup.Id + Write-Verbose -Message "Found Members for Group {$($ADGroup.DisplayName)}" + $owners = Get-MgGroupOwner -GroupId $ADGroup.Id + Write-Verbose -Message "Found Owners for Group {$($ADGroup.DisplayName)}" $ownersUPN = @() if ($null -ne $owners) { @@ -129,14 +137,14 @@ function Get-TargetResource } $description = '' - if ($null -ne $ADGroup[0].Description) + if ($null -ne $ADGroup.Description) { - $description = $ADGroup[0].Description.ToString() + $description = $ADGroup.Description.ToString() } $returnValue = @{ - DisplayName = $ADGroup[0].DisplayName - MailNickName = $ADGroup[0].MailNickName + DisplayName = $ADGroup.DisplayName + MailNickName = $ADGroup.MailNickName Members = $newMemberList ManagedBy = $ownersUPN Description = $description @@ -612,6 +620,7 @@ function Export-TargetResource MailNickName = $group.MailNickName AccessTokens = $AccessTokens } + $Script:exportedInstance = $group $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCAuditConfigurationPolicy/MSFT_SCAuditConfigurationPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCAuditConfigurationPolicy/MSFT_SCAuditConfigurationPolicy.psm1 index d8a9cd9b03..1f84087395 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCAuditConfigurationPolicy/MSFT_SCAuditConfigurationPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCAuditConfigurationPolicy/MSFT_SCAuditConfigurationPolicy.psm1 @@ -43,72 +43,69 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCAuditConfigurationPolicy for Workload {$Workload}" - Write-Verbose -Message 'Connecting to Security and Compliance Center' - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCAuditConfigurationPolicy for Workload {$Workload}" + Write-Verbose -Message 'Connecting to Security and Compliance Center' - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - try - { - $PolicyObject = $null - Write-Verbose -Message "Current Workload = {$Workload}" + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($Workload -eq 'OneDriveForBusiness') - { - $PolicyObject = Get-AuditConfigurationPolicy | Where-Object -FilterScript { $_.Name -eq 'a415dcce-19a0-4153-b137-eb6fd67995b5' } + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $PolicyObject = $null + Write-Verbose -Message "Current Workload = {$Workload}" + + if ($Workload -eq 'OneDriveForBusiness') + { + $PolicyObject = Get-AuditConfigurationPolicy | Where-Object -FilterScript { $_.Name -eq 'a415dcce-19a0-4153-b137-eb6fd67995b5' } + } + else + { + $PolicyObject = Get-AuditConfigurationPolicy | Where-Object -FilterScript { $_.Workload -eq $Workload } + } + + if ($null -eq $PolicyObject) + { + Write-Verbose -Message "SCAuditConfigurationPolicy $Workload does not exist." + return $nullReturn + } } else { - $PolicyObject = Get-AuditConfigurationPolicy | Where-Object -FilterScript { $_.Workload -eq $Workload } + $PolicyObject = $Script:exportedInstance } - if ($null -eq $PolicyObject) - { - Write-Verbose -Message "SCAuditConfigurationPolicy $Workload does not exist." - return $nullReturn + Write-Verbose -Message "Found existing SCAuditConfigurationPolicy $Workload" + $result = @{ + Ensure = 'Present' + Workload = $Workload + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens } - else - { - Write-Verbose -Message "Found existing SCAuditConfigurationPolicy $Workload" - $result = @{ - Ensure = 'Present' - Workload = $Workload - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result - } + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -366,6 +363,7 @@ function Export-TargetResource Write-Host " |---[$i/$($policies.Length)] $($policy.Workload)" -NoNewline + $Script:exportedInstance = $policy $Results = Get-TargetResource @PSBoundParameters -Workload $policy.Workload $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCAutoSensitivityLabelPolicy/MSFT_SCAutoSensitivityLabelPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCAutoSensitivityLabelPolicy/MSFT_SCAutoSensitivityLabelPolicy.psm1 index 94d0e7ceab..92469a7800 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCAutoSensitivityLabelPolicy/MSFT_SCAutoSensitivityLabelPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCAutoSensitivityLabelPolicy/MSFT_SCAutoSensitivityLabelPolicy.psm1 @@ -135,90 +135,86 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Auto sensitivity Label Policy for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' try { - try + if (-not $Script:exportedInstance) { - # There is a bug with the Get-AutoSensitivityLabelPolicy where if you get by Identity, the priority is an invalid number. - # Threfore we get it by name. - $policy = Get-AutoSensitivityLabelPolicy | Where-Object -FilterScript { $_.Name -eq $Name } - } - catch - { - throw $_ - } + Write-Verbose -Message "Getting configuration of Auto sensitivity Label Policy for $Name" - if ($null -eq $policy) - { - Write-Verbose -Message "Auto Sensitivity label policy $($Name) does not exist." - return $nullReturn - } - else - { + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - Write-Verbose "Found existing Auto Sensitivity label policy $($Name)" - $result = @{ - Name = $policy.Name - Comment = $policy.Comment - ApplySensitivityLabel = $policy.ApplySensitivityLabel - Credential = $Credential - Ensure = 'Present' - ExchangeSender = $policy.ExchangeSender - ExchangeSenderException = $policy.ExchangeSenderException - ExchangeSenderMemberOf = $policy.ExchangeSenderMemberOf - ExchangeSenderMemberOfException = $policy.ExchangeSenderMemberOfException - ExchangeLocation = $policy.ExchangeLocation - AddExchangeLocation = $policy.AddExchangeLocation - RemoveExchangeLocation = $policy.RemoveExchangeLocation - Mode = $policy.Mode - OneDriveLocation = $policy.OneDriveLocation - AddOneDriveLocation = $policy.AddOneDriveLocation - RemoveOneDriveLocation = $policy.RemoveOneDriveLocation - OneDriveLocationException = $policy.OneDriveLocationException - AddOneDriveLocationException = $policy.AddOneDriveLocationException - RemoveOneDriveLocationException = $policy.RemoveOneDriveLocationException - Priority = $policy.Priority - SharePointLocation = $policy.SharePointLocation - SharePointLocationException = $policy.SharePointLocationException - AddSharePointLocationException = $policy.AddSharePointLocationException - RemoveSharePointLocationException = $policy.RemoveSharePointLocationException - AddSharePointLocation = $policy.AddSharePointLocation - RemoveSharePointLocation = $policy.RemoveSharePointLocation - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + try + { + # There is a bug with the Get-AutoSensitivityLabelPolicy where if you get by Identity, the priority is an invalid number. + # Threfore we get it by name. + $policy = Get-AutoSensitivityLabelPolicy | Where-Object -FilterScript { $_.Name -eq $Name } + } + catch + { + throw $_ } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + if ($null -eq $policy) + { + Write-Verbose -Message "Auto Sensitivity label policy $($Name) does not exist." + return $nullReturn + } } + else + { + $policy = $Script:exportedInstance + } + + Write-Verbose "Found existing Auto Sensitivity label policy $($Name)" + $result = @{ + Name = $policy.Name + Comment = $policy.Comment + ApplySensitivityLabel = $policy.ApplySensitivityLabel + Credential = $Credential + Ensure = 'Present' + ExchangeSender = $policy.ExchangeSender + ExchangeSenderException = $policy.ExchangeSenderException + ExchangeSenderMemberOf = $policy.ExchangeSenderMemberOf + ExchangeSenderMemberOfException = $policy.ExchangeSenderMemberOfException + ExchangeLocation = $policy.ExchangeLocation + AddExchangeLocation = $policy.AddExchangeLocation + RemoveExchangeLocation = $policy.RemoveExchangeLocation + Mode = $policy.Mode + OneDriveLocation = $policy.OneDriveLocation + AddOneDriveLocation = $policy.AddOneDriveLocation + RemoveOneDriveLocation = $policy.RemoveOneDriveLocation + OneDriveLocationException = $policy.OneDriveLocationException + AddOneDriveLocationException = $policy.AddOneDriveLocationException + RemoveOneDriveLocationException = $policy.RemoveOneDriveLocationException + Priority = $policy.Priority + SharePointLocation = $policy.SharePointLocation + SharePointLocationException = $policy.SharePointLocationException + AddSharePointLocationException = $policy.AddSharePointLocationException + RemoveSharePointLocationException = $policy.RemoveSharePointLocationException + AddSharePointLocation = $policy.AddSharePointLocation + RemoveSharePointLocation = $policy.RemoveSharePointLocation + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens + } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -855,6 +851,7 @@ function Export-TargetResource Write-Host " |---[$i/$($policies.Count)] $($policy.Name)" -NoNewline + $Script:exportedInstance = $policy $Results = Get-TargetResource @PSBoundParameters -Name $policy.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCAutoSensitivityLabelRule/MSFT_SCAutoSensitivityLabelRule.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCAutoSensitivityLabelRule/MSFT_SCAutoSensitivityLabelRule.psm1 index ccca329b0f..8460c67ed5 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCAutoSensitivityLabelRule/MSFT_SCAutoSensitivityLabelRule.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCAutoSensitivityLabelRule/MSFT_SCAutoSensitivityLabelRule.psm1 @@ -225,156 +225,152 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of DLPCompliancePolicy for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' try { - $PolicyRule = Get-AutoSensitivityLabelRule -Identity $Name -ErrorAction SilentlyContinue - - if ($null -eq $PolicyRule) + if (-not $Script:exportedInstance) { - Write-Verbose -Message "AutoSensitivityLabelRule $($Name) does not exist." - return $nullReturn + Write-Verbose -Message "Getting configuration of DLPCompliancePolicy for $Name" + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + $PolicyRule = Get-AutoSensitivityLabelRule -Identity $Name -ErrorAction SilentlyContinue + + if ($null -eq $PolicyRule) + { + Write-Verbose -Message "AutoSensitivityLabelRule $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing AutoSensitivityLabelRule $($Name)" + $PolicyRule = $Script:exportedInstance + } - if ($null -ne $PolicyRule.AnyOfRecipientAddressContainsWords -and $PolicyRule.AnyOfRecipientAddressContainsWords.count -gt 0) - { - $AnyOfRecipientAddressContainsWords = $PolicyRule.AnyOfRecipientAddressContainsWords.Replace(' ', '').Split(',') - } + Write-Verbose "Found existing AutoSensitivityLabelRule $($Name)" - if ($null -ne $PolicyRule.AnyOfRecipientAddressMatchesPatterns -and $PolicyRule.AnyOfRecipientAddressMatchesPatterns -gt 0) - { - $AnyOfRecipientAddressMatchesPatterns = $PolicyRule.AnyOfRecipientAddressMatchesPatterns.Replace(' ', '').Split(',') - } + if ($null -ne $PolicyRule.AnyOfRecipientAddressContainsWords -and $PolicyRule.AnyOfRecipientAddressContainsWords.count -gt 0) + { + $AnyOfRecipientAddressContainsWords = $PolicyRule.AnyOfRecipientAddressContainsWords.Replace(' ', '').Split(',') + } - if ($null -ne $PolicyRule.ContentExtensionMatchesWords -and $PolicyRule.ContentExtensionMatchesWords.count -gt 0) - { - $ContentExtensionMatchesWords = $PolicyRule.ContentExtensionMatchesWords.Replace(' ', '').Split(',') - } + if ($null -ne $PolicyRule.AnyOfRecipientAddressMatchesPatterns -and $PolicyRule.AnyOfRecipientAddressMatchesPatterns -gt 0) + { + $AnyOfRecipientAddressMatchesPatterns = $PolicyRule.AnyOfRecipientAddressMatchesPatterns.Replace(' ', '').Split(',') + } - if ($null -ne $PolicyRule.ExceptIfContentExtensionMatchesWords -and $PolicyRule.ExceptIfContentExtensionMatchesWords.count -gt 0) - { - $ExceptIfContentExtensionMatchesWords = $PolicyRule.ExceptIfContentExtensionMatchesWords.Replace(' ', '').Split(',') - } - if ($null -ne $HeaderMatchesPatterns -and $null -ne $HeaderMatchesPatterns.Name) + if ($null -ne $PolicyRule.ContentExtensionMatchesWords -and $PolicyRule.ContentExtensionMatchesWords.count -gt 0) + { + $ContentExtensionMatchesWords = $PolicyRule.ContentExtensionMatchesWords.Replace(' ', '').Split(',') + } + + if ($null -ne $PolicyRule.ExceptIfContentExtensionMatchesWords -and $PolicyRule.ExceptIfContentExtensionMatchesWords.count -gt 0) + { + $ExceptIfContentExtensionMatchesWords = $PolicyRule.ExceptIfContentExtensionMatchesWords.Replace(' ', '').Split(',') + } + if ($null -ne $HeaderMatchesPatterns -and $null -ne $HeaderMatchesPatterns.Name) + { + $HeaderMatchesPatternsValue = @{} + foreach ($value in $HeaderMatchesPatterns[($HeaderMatchesPatterns.Name)]) { - $HeaderMatchesPatternsValue = @{} - foreach ($value in $HeaderMatchesPatterns[($HeaderMatchesPatterns.Name)]) + if ($HeaderMatchesPatternsValue.ContainsKey($HeaderMatchesPatterns.Name)) { - if ($HeaderMatchesPatternsValue.ContainsKey($HeaderMatchesPatterns.Name)) - { - $HeaderMatchesPatternsValue[$HeaderMatchesPatterns.Name] += $value - } - else - { - $HeaderMatchesPatternsValue.Add($HeaderMatchesPatterns.Name, @($value)) - } + $HeaderMatchesPatternsValue[$HeaderMatchesPatterns.Name] += $value } - } - foreach ($pattern in $PolicyRule.HeaderMatchesPatterns.Keys) - { - $HeaderMatchesPatternsValue += @{ - Name = $pattern - Value = $PolicyRule.HeaderMatchesPatterns.$pattern + else + { + $HeaderMatchesPatternsValue.Add($HeaderMatchesPatterns.Name, @($value)) } } - - $result = @{ - Name = $PolicyRule.Name - Policy = $PolicyRule.ParentPolicyName - Workload = $Workload - AccessScope = $PolicyRule.AccessScope - AnyOfRecipientAddressContainsWords = $AnyOfRecipientAddressContainsWords - AnyOfRecipientAddressMatchesPatterns = $AnyOfRecipientAddressMatchesPatterns - Comment = $PolicyRule.Comment - ContentContainsSensitiveInformation = $PolicyRule.ContentContainsSensitiveInformation - ContentExtensionMatchesWords = $ContentExtensionMatchesWords - Disabled = $PolicyRule.Disabled - DocumentIsPasswordProtected = $PolicyRule.DocumentIsPasswordProtected - DocumentIsUnsupported = $PolicyRule.DocumentIsUnsupported - ExceptIfAccessScope = $PolicyRule.ExceptIfAccessScope - ExceptIfAnyOfRecipientAddressContainsWords = $PolicyRule.ExceptIfAnyOfRecipientAddressContainsWords - ExceptIfAnyOfRecipientAddressMatchesPatterns = $PolicyRule.ExceptIfAnyOfRecipientAddressMatchesPatterns - ExceptIfContentContainsSensitiveInformation = $PolicyRule.ExceptIfContentContainsSensitiveInformation - ExceptIfContentExtensionMatchesWords = $ExceptIfContentExtensionMatchesWords - ExceptIfDocumentIsPasswordProtected = $PolicyRule.ExceptIfDocumentIsPasswordProtected - ExceptIfDocumentIsUnsupported = $PolicyRule.ExceptIfDocumentIsUnsupported - ExceptIfFrom = $PolicyRule.ExceptIfFrom - ExceptIfFromAddressContainsWords = $PolicyRule.ExceptIfFromAddressContainsWords - ExceptIfFromAddressMatchesPatterns = $PolicyRule.ExceptIfFromAddressMatchesPatterns - ExceptIfFromMemberOf = $PolicyRule.ExceptIfFromMemberOf - ExceptIfHeaderMatchesPatterns = $PolicyRule.ExceptIfHeaderMatchesPatterns - ExceptIfProcessingLimitExceeded = $PolicyRule.ExceptIfProcessingLimitExceeded - ExceptIfRecipientDomainIs = $PolicyRule.ExceptIfRecipientDomainIs - ExceptIfSenderDomainIs = $PolicyRule.ExceptIfSenderDomainIs - ExceptIfSenderIPRanges = $PolicyRule.ExceptIfSenderIPRanges - ExceptIfSentTo = $PolicyRule.ExceptIfSentTo - ExceptIfSentToMemberOf = $PolicyRule.ExceptIfSentToMemberOf - ExceptIfSubjectMatchesPatterns = $PolicyRule.ExceptIfSubjectMatchesPatterns - FromAddressContainsWords = $PolicyRule.FromAddressContainsWords - FromAddressMatchesPatterns = $PolicyRule.FromAddressMatchesPatterns - HeaderMatchesPatterns = $HeaderMatchesPatternsValue - ProcessingLimitExceeded = $PolicyRule.ProcessingLimitExceeded - RecipientDomainIs = $PolicyRule.RecipientDomainIs - ReportSeverityLevel = $PolicyRule.ReportSeverityLevel - RuleErrorAction = $PolicyRule.RuleErrorAction - SenderDomainIs = $PolicyRule.SenderDomainIs - SenderIPRanges = $PolicyRule.SenderIPRanges - SentTo = $PolicyRule.SentTo - SentToMemberOf = $PolicyRule.SentToMemberOf - SubjectMatchesPatterns = $PolicyRule.SubjectMatchesPatterns - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens + } + foreach ($pattern in $PolicyRule.HeaderMatchesPatterns.Keys) + { + $HeaderMatchesPatternsValue += @{ + Name = $pattern + Value = $PolicyRule.HeaderMatchesPatterns.$pattern } + } - $paramsToRemove = @() - foreach ($paramName in $result.Keys) - { - if ($null -eq $result[$paramName] -or '' -eq $result[$paramName] -or @() -eq $result[$paramName]) - { - $paramsToRemove += $paramName - } - } + $result = @{ + Name = $PolicyRule.Name + Policy = $PolicyRule.ParentPolicyName + Workload = $Workload + AccessScope = $PolicyRule.AccessScope + AnyOfRecipientAddressContainsWords = $AnyOfRecipientAddressContainsWords + AnyOfRecipientAddressMatchesPatterns = $AnyOfRecipientAddressMatchesPatterns + Comment = $PolicyRule.Comment + ContentContainsSensitiveInformation = $PolicyRule.ContentContainsSensitiveInformation + ContentExtensionMatchesWords = $ContentExtensionMatchesWords + Disabled = $PolicyRule.Disabled + DocumentIsPasswordProtected = $PolicyRule.DocumentIsPasswordProtected + DocumentIsUnsupported = $PolicyRule.DocumentIsUnsupported + ExceptIfAccessScope = $PolicyRule.ExceptIfAccessScope + ExceptIfAnyOfRecipientAddressContainsWords = $PolicyRule.ExceptIfAnyOfRecipientAddressContainsWords + ExceptIfAnyOfRecipientAddressMatchesPatterns = $PolicyRule.ExceptIfAnyOfRecipientAddressMatchesPatterns + ExceptIfContentContainsSensitiveInformation = $PolicyRule.ExceptIfContentContainsSensitiveInformation + ExceptIfContentExtensionMatchesWords = $ExceptIfContentExtensionMatchesWords + ExceptIfDocumentIsPasswordProtected = $PolicyRule.ExceptIfDocumentIsPasswordProtected + ExceptIfDocumentIsUnsupported = $PolicyRule.ExceptIfDocumentIsUnsupported + ExceptIfFrom = $PolicyRule.ExceptIfFrom + ExceptIfFromAddressContainsWords = $PolicyRule.ExceptIfFromAddressContainsWords + ExceptIfFromAddressMatchesPatterns = $PolicyRule.ExceptIfFromAddressMatchesPatterns + ExceptIfFromMemberOf = $PolicyRule.ExceptIfFromMemberOf + ExceptIfHeaderMatchesPatterns = $PolicyRule.ExceptIfHeaderMatchesPatterns + ExceptIfProcessingLimitExceeded = $PolicyRule.ExceptIfProcessingLimitExceeded + ExceptIfRecipientDomainIs = $PolicyRule.ExceptIfRecipientDomainIs + ExceptIfSenderDomainIs = $PolicyRule.ExceptIfSenderDomainIs + ExceptIfSenderIPRanges = $PolicyRule.ExceptIfSenderIPRanges + ExceptIfSentTo = $PolicyRule.ExceptIfSentTo + ExceptIfSentToMemberOf = $PolicyRule.ExceptIfSentToMemberOf + ExceptIfSubjectMatchesPatterns = $PolicyRule.ExceptIfSubjectMatchesPatterns + FromAddressContainsWords = $PolicyRule.FromAddressContainsWords + FromAddressMatchesPatterns = $PolicyRule.FromAddressMatchesPatterns + HeaderMatchesPatterns = $HeaderMatchesPatternsValue + ProcessingLimitExceeded = $PolicyRule.ProcessingLimitExceeded + RecipientDomainIs = $PolicyRule.RecipientDomainIs + ReportSeverityLevel = $PolicyRule.ReportSeverityLevel + RuleErrorAction = $PolicyRule.RuleErrorAction + SenderDomainIs = $PolicyRule.SenderDomainIs + SenderIPRanges = $PolicyRule.SenderIPRanges + SentTo = $PolicyRule.SentTo + SentToMemberOf = $PolicyRule.SentToMemberOf + SubjectMatchesPatterns = $PolicyRule.SubjectMatchesPatterns + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens + } - foreach ($paramName in $paramsToRemove) + $paramsToRemove = @() + foreach ($paramName in $result.Keys) + { + if ($null -eq $result[$paramName] -or '' -eq $result[$paramName] -or @() -eq $result[$paramName]) { - $result.Remove($paramName) + $paramsToRemove += $paramName } + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + foreach ($paramName in $paramsToRemove) + { + $result.Remove($paramName) } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -1149,6 +1145,7 @@ function Export-TargetResource } Write-Host " |---[$i/$($rules.Length)] $($rule.Name)" -NoNewline + $Script:exportedInstance = $rule $Results = Get-TargetResource @PSBoundParameters ` -Name $rule.name ` -Policy $rule.ParentPolicyName ` diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCCaseHoldPolicy/MSFT_SCCaseHoldPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCCaseHoldPolicy/MSFT_SCCaseHoldPolicy.psm1 index cc98385f55..6420562be2 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCCaseHoldPolicy/MSFT_SCCaseHoldPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCCaseHoldPolicy/MSFT_SCCaseHoldPolicy.psm1 @@ -66,67 +66,63 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCCaseHoldPolicy for $Name" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCCaseHoldPolicy for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $PolicyObject = Get-CaseHoldPolicy -Case $Case -Identity $Name -ErrorAction SilentlyContinue + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $PolicyObject) - { - Write-Verbose -Message "SCCaseHoldPolicy $Name does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + $PolicyObject = Get-CaseHoldPolicy -Case $Case -Identity $Name -ErrorAction SilentlyContinue + + if ($null -eq $PolicyObject) + { + Write-Verbose -Message "SCCaseHoldPolicy $Name does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCCaseHoldPolicy $($Name)" - $result = @{ - Ensure = 'Present' - Name = $PolicyObject.Name - Case = $Case - Enabled = $PolicyObject.Enabled - Comment = $PolicyObject.Comment - ExchangeLocation = $PolicyObject.ExchangeLocation.Name - PublicFolderLocation = $PolicyObject.PublicFolderLocation.Name - SharePointLocation = $PolicyObject.SharePointLocation.Name - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } + $PolicyObject = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCCaseHoldPolicy $($Name)" + $result = @{ + Ensure = 'Present' + Name = $PolicyObject.Name + Case = $Case + Enabled = $PolicyObject.Enabled + Comment = $PolicyObject.Comment + ExchangeLocation = $PolicyObject.ExchangeLocation.Name + PublicFolderLocation = $PolicyObject.PublicFolderLocation.Name + SharePointLocation = $PolicyObject.SharePointLocation.Name + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -517,6 +513,7 @@ function Export-TargetResource Write-Host " |---[$j/$($policies.Count)] $($policy.Name)" -NoNewline + $Script:exportedInstance = $policy $Results = Get-TargetResource @PSBoundParameters ` -Name $policy.Name ` -Case $case.Name diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCCaseHoldRule/MSFT_SCCaseHoldRule.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCCaseHoldRule/MSFT_SCCaseHoldRule.psm1 index a5e9e1ed8e..ef9f56b911 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCCaseHoldRule/MSFT_SCCaseHoldRule.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCCaseHoldRule/MSFT_SCCaseHoldRule.psm1 @@ -58,70 +58,65 @@ function Get-TargetResource $AccessTokens ) - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - Write-Verbose -Message "Getting configuration of SCCaseHoldRule for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' try { - $Rules = Get-CaseHoldRule -Policy $Policy -ErrorAction 'SilentlyContinue' - $Rule = $Rules | Where-Object { $_.Name -eq $Name } - - if ($null -eq $Rule) + if (-not $Script:exportedInstance) { - Write-Verbose -Message "SCCaseHoldRule $($Name) does not exist." - return $nullReturn + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + Write-Verbose -Message "Getting configuration of SCCaseHoldRule for $Name" + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + $Rules = Get-CaseHoldRule -Policy $Policy -ErrorAction 'SilentlyContinue' + $Rule = $Rules | Where-Object { $_.Name -eq $Name } + + if ($null -eq $Rule) + { + Write-Verbose -Message "SCCaseHoldRule $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCCaseHoldRule $($Name)" - - $result = @{ - Name = $Rule.Name - Policy = $Policy - Comment = $Rule.Comment - Disabled = $Rule.Disabled - ContentMatchQuery = $Rule.ContentMatchQuery - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $Rule = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCCaseHoldRule $($Name)" + + $result = @{ + Name = $Rule.Name + Policy = $Policy + Comment = $Rule.Comment + Disabled = $Rule.Disabled + ContentMatchQuery = $Rule.ContentMatchQuery + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { - New-M365DSCLogEntry -Message 'Error retrieving data:' ` -Exception $_ ` -Source $($MyInvocation.MyCommand.Source) ` @@ -412,6 +407,7 @@ function Export-TargetResource { $policy = Get-CaseHoldPolicy -Identity $Rule.Policy -ErrorAction Stop + $Script:exportedInstance = $Rule $Results = Get-TargetResource @PSBoundParameters ` -Name $Rule.Name ` -Policy $policy.Name diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceCase/MSFT_SCComplianceCase.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceCase/MSFT_SCComplianceCase.psm1 index 765c2e59f0..a7428b5b52 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceCase/MSFT_SCComplianceCase.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceCase/MSFT_SCComplianceCase.psm1 @@ -51,67 +51,65 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCComplianceCase for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCComplianceCase for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $Case = Get-ComplianceCase -Identity $Name -ErrorAction SilentlyContinue + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $Case) - { - Write-Verbose -Message "SCComplianceCase $($Name) does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $Case = Get-ComplianceCase -Identity $Name -ErrorAction SilentlyContinue + + if ($null -eq $Case) + { + Write-Verbose -Message "SCComplianceCase $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCComplianceCase $($Name)" - $Status = $Case.Status - if ('Closing' -eq $Status) - { - $Status = 'Closed' - } - $result = @{ - Name = $Case.Name - Description = $Case.Description - Status = $Status - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $Case = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCComplianceCase $($Name)" + $Status = $Case.Status + if ('Closing' -eq $Status) + { + $Status = 'Closed' + } + $result = @{ + Name = $Case.Name + Description = $Case.Description + Status = $Status + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -405,6 +403,7 @@ function Export-TargetResource Write-Host " eDiscovery: [$i/$($Cases.Count)] $($Case.Name)" -NoNewline + $Script:exportedInstance = $Case $Results = Get-TargetResource @PSBoundParameters -Name $Case.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceSearch/MSFT_SCComplianceSearch.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceSearch/MSFT_SCComplianceSearch.psm1 index 7cf411e732..983dba9f12 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceSearch/MSFT_SCComplianceSearch.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceSearch/MSFT_SCComplianceSearch.psm1 @@ -90,93 +90,98 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCComplianceSearch for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try { - if ($null -eq $Case) + if (-not $Script:exportedInstance) { - $Search = Get-ComplianceSearch -Identity $Name -ErrorAction SilentlyContinue + Write-Verbose -Message "Getting configuration of SCComplianceSearch for $Name" + if ($Global:CurrentModeIsExport) + { + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters ` + -SkipModuleReload $true + } + else + { + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters + } + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + if ($null -eq $Case) + { + $Search = Get-ComplianceSearch -Identity $Name -ErrorAction SilentlyContinue + } + else + { + $Search = Get-ComplianceSearch -Identity $Name -Case $Case -ErrorAction SilentlyContinue + } + + if ($null -eq $Search) + { + Write-Verbose -Message "SCComplianceSearch $($Name) does not exist." + return $nullReturn + } } else { - $Search = Get-ComplianceSearch -Identity $Name -Case $Case -ErrorAction SilentlyContinue + $Search = $Script:exportedInstance } - if ($null -eq $Search) - { - Write-Verbose -Message "SCComplianceSearch $($Name) does not exist." - return $nullReturn + Write-Verbose "Found existing SCComplianceSearch $($Name)" + $result = @{ + Name = $Name + Case = $Case + AllowNotFoundExchangeLocationsEnabled = $Search.AllowNotFoundExchangeLocationsEnabled + ContentMatchQuery = $Search.ContentMatchQuery + Description = $Search.Description + ExchangeLocation = $Search.ExchangeLocation + ExchangeLocationExclusion = $Search.ExchangeLocationExclusion + HoldNames = $Search.HoldNames + IncludeUserAppContent = $Search.IncludeUserAppContent + Language = $Search.Language.TwoLetterISOLanguageName + PublicFolderLocation = $Search.PublicFolderLocation + SharePointLocation = $Search.SharePointLocation + SharePointLocationExclusion = $Search.SharePointLocationExclusion + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } - else - { - Write-Verbose "Found existing SCComplianceSearch $($Name)" - $result = @{ - Name = $Name - Case = $Case - AllowNotFoundExchangeLocationsEnabled = $Search.AllowNotFoundExchangeLocationsEnabled - ContentMatchQuery = $Search.ContentMatchQuery - Description = $Search.Description - ExchangeLocation = $Search.ExchangeLocation - ExchangeLocationExclusion = $Search.ExchangeLocationExclusion - HoldNames = $Search.HoldNames - IncludeUserAppContent = $Search.IncludeUserAppContent - Language = $Search.Language.TwoLetterISOLanguageName - PublicFolderLocation = $Search.PublicFolderLocation - SharePointLocation = $Search.SharePointLocation - SharePointLocationExclusion = $Search.SharePointLocationExclusion - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } - - $nullParams = @() - foreach ($parameter in $result.Keys) - { - if ($null -eq $result.$parameter) - { - $nullParams += $parameter - } - } - foreach ($paramToRemove in $nullParams) + $nullParams = @() + foreach ($parameter in $result.Keys) + { + if ($null -eq $result.$parameter) { - $result.Remove($paramToRemove) + $nullParams += $parameter } + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + foreach ($paramToRemove in $nullParams) + { + $result.Remove($paramToRemove) } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -543,6 +548,7 @@ function Export-TargetResource Write-Host " |---[$i/$($searches.Name.Count)] $($search.Name)" -NoNewline + $Script:exportedInstance = $search $Results = Get-TargetResource @PSBoundParameters -Name $search.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceSearchAction/MSFT_SCComplianceSearchAction.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceSearchAction/MSFT_SCComplianceSearchAction.psm1 index 1c1e7d4495..36aaea95cf 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceSearchAction/MSFT_SCComplianceSearchAction.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceSearchAction/MSFT_SCComplianceSearchAction.psm1 @@ -76,115 +76,111 @@ function Get-TargetResource [System.String[]] $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCComplianceSearchAction for $SearchName - $Action" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion - - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try { - $currentAction = Get-CurrentAction -SearchName $SearchName -Action $Action ` - -ErrorAction Stop - - if ($null -eq $currentAction) - { - Write-Verbose -Message "SCComplianceSearchAction $ActionName does not exist." - return $nullReturn + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCComplianceSearchAction for $SearchName - $Action" + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $currentAction = Get-CurrentAction -SearchName $SearchName -Action $Action ` + -ErrorAction Stop + + if ($null -eq $currentAction) + { + Write-Verbose -Message "SCComplianceSearchAction $ActionName does not exist." + return $nullReturn + } } else { - if ('Purge' -ne $Action) - { - $Scenario = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Scenario' - $FileTypeExclusion = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'File type exclusions for unindexed' - $EnableDedupe = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Enable dedupe' - $IncludeCreds = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'SAS token' - $IncludeSP = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Include SharePoint versions' - $ScopeValue = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Scope' - - $ActionName = $Action - if ('RetentionReports' -eq $Scenario) - { - $ActionName = 'Retention' - } + $currentAction = $Script:exportedInstance + } - $result = @{ - Action = $ActionName - SearchName = $currentAction.SearchName - FileTypeExclusionsForUnindexedItems = $FileTypeExclusion - EnableDedupe = $EnableDedupe - IncludeSharePointDocumentVersions = $IncludeSP - RetryOnError = $currentAction.Retry - ActionScope = $ScopeValue - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } - if ($ActionName -eq 'Preview') - { - $result.Remove('EnableDedupe') | Out-Null - } - } - else + if ('Purge' -ne $Action) + { + $Scenario = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Scenario' + $FileTypeExclusion = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'File type exclusions for unindexed' + $EnableDedupe = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Enable dedupe' + $IncludeCreds = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'SAS token' + $IncludeSP = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Include SharePoint versions' + $ScopeValue = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Scope' + + $ActionName = $Action + if ('RetentionReports' -eq $Scenario) { - $PurgeTP = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Purge Type' - $result = @{ - Action = $currentAction.Action - SearchName = $currentAction.SearchName - PurgeType = $PurgeTP - RetryOnError = $currentAction.Retry - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $ActionName = 'Retention' } - if ('' -eq $IncludeCreds -or 'Purge' -eq $Action) - { - $result.Add('IncludeCredential', $false) + $result = @{ + Action = $ActionName + SearchName = $currentAction.SearchName + FileTypeExclusionsForUnindexedItems = $FileTypeExclusion + EnableDedupe = $EnableDedupe + IncludeSharePointDocumentVersions = $IncludeSP + RetryOnError = $currentAction.Retry + ActionScope = $ScopeValue + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } - elseif ('Purge' -ne $Action) + if ($ActionName -eq 'Preview') { - $result.Add('IncludeCredential', $true) + $result.Remove('EnableDedupe') | Out-Null } + } + else + { + $PurgeTP = Get-ResultProperty -ResultString $currentAction.Results -PropertyName 'Purge Type' + $result = @{ + Action = $currentAction.Action + SearchName = $currentAction.SearchName + PurgeType = $PurgeTP + RetryOnError = $currentAction.Retry + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens + } + } - Write-Verbose "Found existing $Action SCComplianceSearchAction for Search $SearchName" - - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + if ('' -eq $IncludeCreds -or 'Purge' -eq $Action) + { + $result.Add('IncludeCredential', $false) + } + elseif ('Purge' -ne $Action) + { + $result.Add('IncludeCredential', $true) } + + Write-Verbose "Found existing $Action SCComplianceSearchAction for Search $SearchName" + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch @@ -582,6 +578,7 @@ function Export-TargetResource { $Params.Action = 'Retention' } + $Script:exportedInstance = $action $Results = Get-TargetResource @PSBoundParameters @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceTag/MSFT_SCComplianceTag.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceTag/MSFT_SCComplianceTag.psm1 index 89ca1e87d3..dc98e40394 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceTag/MSFT_SCComplianceTag.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCComplianceTag/MSFT_SCComplianceTag.psm1 @@ -84,75 +84,73 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of ComplianceTag for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of ComplianceTag for $Name" - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - try - { - $tagObject = Get-ComplianceTag -Identity $Name -ErrorAction SilentlyContinue + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $tagObject) - { - Write-Verbose -Message "ComplianceTag $($Name) does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $tagObject = Get-ComplianceTag -Identity $Name -ErrorAction SilentlyContinue + + if ($null -eq $tagObject) + { + Write-Verbose -Message "ComplianceTag $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing ComplianceTag $($Name)" - $result = @{ - Name = $tagObject.Name - Comment = $tagObject.Comment - RetentionDuration = $tagObject.RetentionDuration - IsRecordLabel = $tagObject.IsRecordLabel - Regulatory = $tagObject.Regulatory - Notes = $tagObject.Notes - ReviewerEmail = $tagObject.ReviewerEmail - RetentionAction = $tagObject.RetentionAction - EventType = $tagObject.EventType - RetentionType = $tagObject.RetentionType - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $tagObject = $Script:exportedInstance + } - if (-not [System.String]::IsNullOrEmpty($tagObject.FilePlanMetadata)) - { - $ConvertedFilePlanProperty = Get-SCFilePlanProperty $tagObject.FilePlanMetadata - $result.Add('FilePlanProperty', $ConvertedFilePlanProperty) - } + Write-Verbose "Found existing ComplianceTag $($Name)" + $result = @{ + Name = $tagObject.Name + Comment = $tagObject.Comment + RetentionDuration = $tagObject.RetentionDuration + IsRecordLabel = $tagObject.IsRecordLabel + Regulatory = $tagObject.Regulatory + Notes = $tagObject.Notes + ReviewerEmail = $tagObject.ReviewerEmail + RetentionAction = $tagObject.RetentionAction + EventType = $tagObject.EventType + RetentionType = $tagObject.RetentionType + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + if (-not [System.String]::IsNullOrEmpty($tagObject.FilePlanMetadata)) + { + $ConvertedFilePlanProperty = Get-SCFilePlanProperty $tagObject.FilePlanMetadata + $result.Add('FilePlanProperty', $ConvertedFilePlanProperty) } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -564,6 +562,7 @@ function Export-TargetResource } Write-Host " |---[$i/$($totalTags)] $($tag.Name)" -NoNewline + $Script:exportedInstance = $tag $Results = Get-TargetResource @PSBoundParameters -Name $tag.Name $Results.FilePlanProperty = Get-SCFilePlanPropertyAsString $Results.FilePlanProperty $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDLPCompliancePolicy/MSFT_SCDLPCompliancePolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDLPCompliancePolicy/MSFT_SCDLPCompliancePolicy.psm1 index f4f0c868b8..b1838b303d 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDLPCompliancePolicy/MSFT_SCDLPCompliancePolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDLPCompliancePolicy/MSFT_SCDLPCompliancePolicy.psm1 @@ -123,99 +123,97 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of DLPCompliancePolicy for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of DLPCompliancePolicy for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $PolicyObject = Get-DlpCompliancePolicy -Identity $Name -ErrorAction SilentlyContinue + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $PolicyObject) - { - Write-Verbose -Message "DLPCompliancePolicy $($Name) does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $PolicyObject = Get-DlpCompliancePolicy -Identity $Name -ErrorAction SilentlyContinue + + if ($null -eq $PolicyObject) + { + Write-Verbose -Message "DLPCompliancePolicy $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing DLPCompliancePolicy $($Name)" - - $ExchangeSenderMemberOfValue = @() - if ($null -ne $PolicyObject.ExchangeSenderMemberOf) - { - foreach ($member in $PolicyObject.ExchangeSenderMemberOf) - { - $ExchangeSenderMemberOfValue += (ConvertFrom-Json $member).PrimarySmtpAddress - } - } - - $ExchangeSenderMemberOfExceptionValue = @() - if ($null -ne $PolicyObject.ExchangeSenderMemberOfException) - { - foreach ($member in $PolicyObject.ExchangeSenderMemberOfException) - { - $ExchangeSenderMemberOfExceptionValue += (ConvertFrom-Json $member).PrimarySmtpAddress - } - } - - $result = @{ - Ensure = 'Present' - Name = $PolicyObject.Name - Comment = $PolicyObject.Comment - EndpointDlpLocation = $PolicyObject.EndpointDlpLocation.Name - EndpointDlpLocationException = $PolicyObject.EndpointDlpLocationException - ExchangeLocation = $PolicyObject.ExchangeLocation.Name - ExchangeSenderMemberOf = $ExchangeSenderMemberOfValue - ExchangeSenderMemberOfException = $ExchangeSenderMemberOfExceptionValue - Mode = $PolicyObject.Mode - OneDriveLocation = $PolicyObject.OneDriveLocation.Name - OneDriveLocationException = $PolicyObject.OneDriveLocationException - OnPremisesScannerDlpLocation = $PolicyObject.OnPremisesScannerDlpLocation.Name - OnPremisesScannerDlpLocationException = $PolicyObject.OnPremisesScannerDlpLocationException - PowerBIDlpLocation = $PolicyObject.PowerBIDlpLocation.Name - PowerBIDlpLocationException = $PolicyObject.PowerBIDlpLocationException - Priority = $PolicyObject.Priority - SharePointLocation = $PolicyObject.SharePointLocation.Name - SharePointLocationException = $PolicyObject.SharePointLocationException - TeamsLocation = $PolicyObject.TeamsLocation.Name - TeamsLocationException = $PolicyObject.TeamsLocationException - ThirdPartyAppDlpLocation = $PolicyObject.ThirdPartyAppDlpLocation.Name - ThirdPartyAppDlpLocationException = $PolicyObject.ThirdPartyAppDlpLocationException - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } - - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + $PolicyObject = $Script:exportedInstance + } + + Write-Verbose "Found existing DLPCompliancePolicy $($Name)" + + $ExchangeSenderMemberOfValue = @() + if ($null -ne $PolicyObject.ExchangeSenderMemberOf) + { + foreach ($member in $PolicyObject.ExchangeSenderMemberOf) + { + $ExchangeSenderMemberOfValue += (ConvertFrom-Json $member).PrimarySmtpAddress + } + } + + $ExchangeSenderMemberOfExceptionValue = @() + if ($null -ne $PolicyObject.ExchangeSenderMemberOfException) + { + foreach ($member in $PolicyObject.ExchangeSenderMemberOfException) + { + $ExchangeSenderMemberOfExceptionValue += (ConvertFrom-Json $member).PrimarySmtpAddress + } + } + + $result = @{ + Ensure = 'Present' + Name = $PolicyObject.Name + Comment = $PolicyObject.Comment + EndpointDlpLocation = $PolicyObject.EndpointDlpLocation.Name + EndpointDlpLocationException = $PolicyObject.EndpointDlpLocationException + ExchangeLocation = $PolicyObject.ExchangeLocation.Name + ExchangeSenderMemberOf = $ExchangeSenderMemberOfValue + ExchangeSenderMemberOfException = $ExchangeSenderMemberOfExceptionValue + Mode = $PolicyObject.Mode + OneDriveLocation = $PolicyObject.OneDriveLocation.Name + OneDriveLocationException = $PolicyObject.OneDriveLocationException + OnPremisesScannerDlpLocation = $PolicyObject.OnPremisesScannerDlpLocation.Name + OnPremisesScannerDlpLocationException = $PolicyObject.OnPremisesScannerDlpLocationException + PowerBIDlpLocation = $PolicyObject.PowerBIDlpLocation.Name + PowerBIDlpLocationException = $PolicyObject.PowerBIDlpLocationException + Priority = $PolicyObject.Priority + SharePointLocation = $PolicyObject.SharePointLocation.Name + SharePointLocationException = $PolicyObject.SharePointLocationException + TeamsLocation = $PolicyObject.TeamsLocation.Name + TeamsLocationException = $PolicyObject.TeamsLocationException + ThirdPartyAppDlpLocation = $PolicyObject.ThirdPartyAppDlpLocation.Name + ThirdPartyAppDlpLocationException = $PolicyObject.ThirdPartyAppDlpLocationException + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -974,6 +972,7 @@ function Export-TargetResource } Write-Host " |---[$i/$($policies.Count)] $($policy.Name)" -NoNewline + $Script:exportedInstance = $policy $Results = Get-TargetResource @PSBoundParameters -Name $policy.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDLPComplianceRule/MSFT_SCDLPComplianceRule.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDLPComplianceRule/MSFT_SCDLPComplianceRule.psm1 index f4b5814d2a..57eddccd1c 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDLPComplianceRule/MSFT_SCDLPComplianceRule.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDLPComplianceRule/MSFT_SCDLPComplianceRule.psm1 @@ -318,202 +318,200 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of DLPCompliancePolicy for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of DLPCompliancePolicy for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $PolicyRule = Get-DlpComplianceRule -Identity $Name -ErrorAction SilentlyContinue + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $PolicyRule) - { - Write-Verbose -Message "DLPComplianceRule $($Name) does not exist." - return $nullReturn - } - else - { - Write-Verbose "Found existing DLPComplianceRule $($Name)" + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - # Cmdlet returns a string, but in order to properly validate valid values, we need to convert - # to a String array - $ArrayIncidentReportContent = @() + $PolicyRule = Get-DlpComplianceRule -Identity $Name -ErrorAction SilentlyContinue - if ($null -ne $PolicyRule.IncidentReportContent) + if ($null -eq $PolicyRule) { - $ArrayIncidentReportContent = $PolicyRule.IncidentReportContent.Replace(' ', '').Split(',') + Write-Verbose -Message "DLPComplianceRule $($Name) does not exist." + return $nullReturn } + } + else + { + $PolicyRule = $Script:exportedInstance + } - if ($null -ne $PolicyRule.NotifyAllowOverride) - { - $NotifyAllowOverrideValue = $PolicyRule.NotifyAllowOverride.Replace(' ', '').Split(',') - } + Write-Verbose "Found existing DLPComplianceRule $($Name)" - if ($null -ne $PolicyRule.AnyOfRecipientAddressContainsWords -and $PolicyRule.AnyOfRecipientAddressContainsWords.count -gt 0) - { - $AnyOfRecipientAddressContainsWords = $PolicyRule.AnyOfRecipientAddressContainsWords.Replace(' ', '').Split(',') - } + # Cmdlet returns a string, but in order to properly validate valid values, we need to convert + # to a String array + $ArrayIncidentReportContent = @() - if ($null -ne $PolicyRule.ExceptIfAnyOfRecipientAddressContainsWords -and $PolicyRule.ExceptIfAnyOfRecipientAddressContainsWords.count -gt 0) - { - $ExceptIfAnyOfRecipientAddressContainsWords = $PolicyRule.ExceptIfAnyOfRecipientAddressContainsWords.Replace(' ', '').Split(',') - } + if ($null -ne $PolicyRule.IncidentReportContent) + { + $ArrayIncidentReportContent = $PolicyRule.IncidentReportContent.Replace(' ', '').Split(',') + } - if ($null -ne $PolicyRule.AnyOfRecipientAddressMatchesPatterns -and $PolicyRule.AnyOfRecipientAddressMatchesPatterns -gt 0) - { - $AnyOfRecipientAddressMatchesPatterns = $PolicyRule.AnyOfRecipientAddressMatchesPatterns.Replace(' ', '').Split(',') - } + if ($null -ne $PolicyRule.NotifyAllowOverride) + { + $NotifyAllowOverrideValue = $PolicyRule.NotifyAllowOverride.Replace(' ', '').Split(',') + } - if ($null -ne $PolicyRule.ContentExtensionMatchesWords -and $PolicyRule.ContentExtensionMatchesWords.count -gt 0) - { - $ContentExtensionMatchesWords = $PolicyRule.ContentExtensionMatchesWords.Replace(' ', '').Split(',') - } + if ($null -ne $PolicyRule.AnyOfRecipientAddressContainsWords -and $PolicyRule.AnyOfRecipientAddressContainsWords.count -gt 0) + { + $AnyOfRecipientAddressContainsWords = $PolicyRule.AnyOfRecipientAddressContainsWords.Replace(' ', '').Split(',') + } - if ($null -ne $PolicyRule.ExceptIfContentExtensionMatchesWords -and $PolicyRule.ExceptIfContentExtensionMatchesWords.count -gt 0) - { - $ExceptIfContentExtensionMatchesWords = $PolicyRule.ExceptIfContentExtensionMatchesWords.Replace(' ', '').Split(',') - } + if ($null -ne $PolicyRule.ExceptIfAnyOfRecipientAddressContainsWords -and $PolicyRule.ExceptIfAnyOfRecipientAddressContainsWords.count -gt 0) + { + $ExceptIfAnyOfRecipientAddressContainsWords = $PolicyRule.ExceptIfAnyOfRecipientAddressContainsWords.Replace(' ', '').Split(',') + } - if ($null -ne $PolicyRule.AdvancedRule -and $PolicyRule.AdvancedRule.Count -gt 0) - { - $ruleobject = $PolicyRule.AdvancedRule | ConvertFrom-Json - $index = $ruleobject.Condition.SubConditions.ConditionName.IndexOf('ContentContainsSensitiveInformation') - if ($index -ne -1) - { - if ($null -eq $ruleobject.Condition.SubConditions[$index].value.groups) - { - $ruleobject.Condition.SubConditions[$index].Value = $ruleobject.Condition.SubConditions[$index].Value | Select-Object * -ExcludeProperty Id - } - elseif ($null -ne $ruleObject.Condition.SubConditions[$index].Value.Groups.Sensitivetypes) - { - $ruleobject.Condition.SubConditions[$index].Value.Groups.Sensitivetypes = @($ruleobject.Condition.SubConditions[$index].Value.Groups.Sensitivetypes | Select-Object * -ExcludeProperty Id) - } - } + if ($null -ne $PolicyRule.AnyOfRecipientAddressMatchesPatterns -and $PolicyRule.AnyOfRecipientAddressMatchesPatterns -gt 0) + { + $AnyOfRecipientAddressMatchesPatterns = $PolicyRule.AnyOfRecipientAddressMatchesPatterns.Replace(' ', '').Split(',') + } - $newAdvancedRule = $ruleobject | ConvertTo-Json -Depth 32 | Format-Json - $newAdvancedRule = $newAdvancedRule | ConvertTo-Json -Compress - } - else - { - $newAdvancedRule = $null - } + if ($null -ne $PolicyRule.ContentExtensionMatchesWords -and $PolicyRule.ContentExtensionMatchesWords.count -gt 0) + { + $ContentExtensionMatchesWords = $PolicyRule.ContentExtensionMatchesWords.Replace(' ', '').Split(',') + } - $fancyDoubleQuotes = '[\u201C\u201D]' - $result = @{ - Ensure = 'Present' - Name = $PolicyRule.Name - Policy = $PolicyRule.ParentPolicyName - AccessScope = $PolicyRule.AccessScope - BlockAccess = $PolicyRule.BlockAccess - BlockAccessScope = $PolicyRule.BlockAccessScope - Comment = $PolicyRule.Comment - AdvancedRule = $newAdvancedRule - ContentContainsSensitiveInformation = $PolicyRule.ContentContainsSensitiveInformation - ExceptIfContentContainsSensitiveInformation = $PolicyRule.ExceptIfContentContainsSensitiveInformation - ContentPropertyContainsWords = $PolicyRule.ContentPropertyContainsWords - Disabled = $PolicyRule.Disabled - GenerateAlert = $PolicyRule.GenerateAlert - GenerateIncidentReport = $PolicyRule.GenerateIncidentReport - IncidentReportContent = $ArrayIncidentReportContent - NotifyAllowOverride = $NotifyAllowOverrideValue - NotifyEmailCustomText = [regex]::Replace($PolicyRule.NotifyEmailCustomText, $fancyDoubleQuotes, "`"") - NotifyPolicyTipCustomText = [regex]::Replace($PolicyRule.NotifyPolicyTipCustomText, $fancyDoubleQuotes, "`"") - NotifyUser = $PolicyRule.NotifyUser - ReportSeverityLevel = $PolicyRule.ReportSeverityLevel - RuleErrorAction = $PolicyRule.RuleErrorAction - RemoveRMSTemplate = $PolicyRule.RemoveRMSTemplate - StopPolicyProcessing = $PolicyRule.StopPolicyProcessing - DocumentIsUnsupported = $PolicyRule.DocumentIsUnsupported - ExceptIfDocumentIsUnsupported = $PolicyRule.ExceptIfDocumentIsUnsupported - HasSenderOverride = $PolicyRule.HasSenderOverride - ExceptIfHasSenderOverride = $PolicyRule.ExceptIfHasSenderOverride - ProcessingLimitExceeded = $PolicyRule.ProcessingLimitExceeded - ExceptIfProcessingLimitExceeded = $PolicyRule.ExceptIfProcessingLimitExceeded - DocumentIsPasswordProtected = $PolicyRule.DocumentIsPasswordProtected - ExceptIfDocumentIsPasswordProtected = $PolicyRule.ExceptIfDocumentIsPasswordProtected - MessageTypeMatches = $PolicyRule.MessageTypeMatches - ExceptIfMessageTypeMatches = $PolicyRule.ExceptIfMessageTypeMatches - FromScope = $PolicyRule.FromScope - ExceptIfFromScope = $PolicyRule.ExceptIfFromScope - SubjectContainsWords = $PolicyRule.SubjectContainsWords - SubjectMatchesPatterns = $PolicyRule.SubjectMatchesPatterns - SubjectOrBodyContainsWords = $PolicyRule.SubjectOrBodyContainsWords - SubjectOrBodyMatchesPatterns = $PolicyRule.SubjectOrBodyMatchesPatterns - ContentCharacterSetContainsWords = $PolicyRule.ContentCharacterSetContainsWords - DocumentNameMatchesPatterns = $PolicyRule.DocumentNameMatchesPatterns - DocumentNameMatchesWords = $PolicyRule.DocumentNameMatchesWords - ExceptIfAnyOfRecipientAddressMatchesPatterns = $PolicyRule.ExceptIfAnyOfRecipientAddressMatchesPatterns - ExceptIfContentCharacterSetContainsWords = $PolicyRule.ExceptIfContentCharacterSetContainsWords - ExceptIfContentPropertyContainsWords = $PolicyRule.ExceptIfContentPropertyContainsWords - ExceptIfDocumentNameMatchesPatterns = $PolicyRule.ExceptIfDocumentNameMatchesPatterns - ExceptIfDocumentNameMatchesWords = $PolicyRule.ExceptIfDocumentNameMatchesWords - RecipientDomainIs = $PolicyRule.RecipientDomainIs - ExceptIfRecipientDomainIs = $PolicyRule.ExceptIfRecipientDomainIs - ExceptIfSenderDomainIs = $PolicyRule.ExceptIfSenderDomainIs - ExceptIfSenderIPRanges = $PolicyRule.ExceptIfSenderIPRanges - ExceptIfSentTo = $PolicyRule.ExceptIfSentTo - ExceptIfSubjectContainsWords = $PolicyRule.ExceptIfSubjectContainsWords - ExceptIfSubjectMatchesPatterns = $PolicyRule.ExceptIfSubjectMatchesPatterns - ExceptIfSubjectOrBodyContainsWords = $PolicyRule.ExceptIfSubjectOrBodyContainsWords - ExceptIfSubjectOrBodyMatchesPatterns = $PolicyRule.ExceptIfSubjectOrBodyMatchesPatterns - FromAddressMatchesPatterns = $PolicyRule.FromAddressMatchesPatterns - SentToMemberOf = $PolicyRule.FromAddressMatchesPatterns - DocumentContainsWords = $PolicyRule.DocumentContainsWords - ContentIsNotLabeled = $PolicyRule.ContentIsNotLabeled - SetHeader = $PolicyRule.SetHeader - AnyOfRecipientAddressContainsWords = $AnyOfRecipientAddressContainsWords - AnyOfRecipientAddressMatchesPatterns = $AnyOfRecipientAddressMatchesPatterns - ContentExtensionMatchesWords = $ContentExtensionMatchesWords - ExceptIfContentExtensionMatchesWords = $ExceptIfContentExtensionMatchesWords - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } + if ($null -ne $PolicyRule.ExceptIfContentExtensionMatchesWords -and $PolicyRule.ExceptIfContentExtensionMatchesWords.count -gt 0) + { + $ExceptIfContentExtensionMatchesWords = $PolicyRule.ExceptIfContentExtensionMatchesWords.Replace(' ', '').Split(',') + } - $paramsToRemove = @() - foreach ($paramName in $result.Keys) + if ($null -ne $PolicyRule.AdvancedRule -and $PolicyRule.AdvancedRule.Count -gt 0) + { + $ruleobject = $PolicyRule.AdvancedRule | ConvertFrom-Json + $index = $ruleobject.Condition.SubConditions.ConditionName.IndexOf('ContentContainsSensitiveInformation') + if ($index -ne -1) { - if ($null -eq $result[$paramName] -or '' -eq $result[$paramName] -or @() -eq $result[$paramName]) + if ($null -eq $ruleobject.Condition.SubConditions[$index].value.groups) { - $paramsToRemove += $paramName + $ruleobject.Condition.SubConditions[$index].Value = $ruleobject.Condition.SubConditions[$index].Value | Select-Object * -ExcludeProperty Id + } + elseif ($null -ne $ruleObject.Condition.SubConditions[$index].Value.Groups.Sensitivetypes) + { + $ruleobject.Condition.SubConditions[$index].Value.Groups.Sensitivetypes = @($ruleobject.Condition.SubConditions[$index].Value.Groups.Sensitivetypes | Select-Object * -ExcludeProperty Id) } } - foreach ($paramName in $paramsToRemove) + $newAdvancedRule = $ruleobject | ConvertTo-Json -Depth 32 | Format-Json + $newAdvancedRule = $newAdvancedRule | ConvertTo-Json -Compress + } + else + { + $newAdvancedRule = $null + } + + $fancyDoubleQuotes = '[\u201C\u201D]' + $result = @{ + Ensure = 'Present' + Name = $PolicyRule.Name + Policy = $PolicyRule.ParentPolicyName + AccessScope = $PolicyRule.AccessScope + BlockAccess = $PolicyRule.BlockAccess + BlockAccessScope = $PolicyRule.BlockAccessScope + Comment = $PolicyRule.Comment + AdvancedRule = $newAdvancedRule + ContentContainsSensitiveInformation = $PolicyRule.ContentContainsSensitiveInformation + ExceptIfContentContainsSensitiveInformation = $PolicyRule.ExceptIfContentContainsSensitiveInformation + ContentPropertyContainsWords = $PolicyRule.ContentPropertyContainsWords + Disabled = $PolicyRule.Disabled + GenerateAlert = $PolicyRule.GenerateAlert + GenerateIncidentReport = $PolicyRule.GenerateIncidentReport + IncidentReportContent = $ArrayIncidentReportContent + NotifyAllowOverride = $NotifyAllowOverrideValue + NotifyEmailCustomText = [regex]::Replace($PolicyRule.NotifyEmailCustomText, $fancyDoubleQuotes, "`"") + NotifyPolicyTipCustomText = [regex]::Replace($PolicyRule.NotifyPolicyTipCustomText, $fancyDoubleQuotes, "`"") + NotifyUser = $PolicyRule.NotifyUser + ReportSeverityLevel = $PolicyRule.ReportSeverityLevel + RuleErrorAction = $PolicyRule.RuleErrorAction + RemoveRMSTemplate = $PolicyRule.RemoveRMSTemplate + StopPolicyProcessing = $PolicyRule.StopPolicyProcessing + DocumentIsUnsupported = $PolicyRule.DocumentIsUnsupported + ExceptIfDocumentIsUnsupported = $PolicyRule.ExceptIfDocumentIsUnsupported + HasSenderOverride = $PolicyRule.HasSenderOverride + ExceptIfHasSenderOverride = $PolicyRule.ExceptIfHasSenderOverride + ProcessingLimitExceeded = $PolicyRule.ProcessingLimitExceeded + ExceptIfProcessingLimitExceeded = $PolicyRule.ExceptIfProcessingLimitExceeded + DocumentIsPasswordProtected = $PolicyRule.DocumentIsPasswordProtected + ExceptIfDocumentIsPasswordProtected = $PolicyRule.ExceptIfDocumentIsPasswordProtected + MessageTypeMatches = $PolicyRule.MessageTypeMatches + ExceptIfMessageTypeMatches = $PolicyRule.ExceptIfMessageTypeMatches + FromScope = $PolicyRule.FromScope + ExceptIfFromScope = $PolicyRule.ExceptIfFromScope + SubjectContainsWords = $PolicyRule.SubjectContainsWords + SubjectMatchesPatterns = $PolicyRule.SubjectMatchesPatterns + SubjectOrBodyContainsWords = $PolicyRule.SubjectOrBodyContainsWords + SubjectOrBodyMatchesPatterns = $PolicyRule.SubjectOrBodyMatchesPatterns + ContentCharacterSetContainsWords = $PolicyRule.ContentCharacterSetContainsWords + DocumentNameMatchesPatterns = $PolicyRule.DocumentNameMatchesPatterns + DocumentNameMatchesWords = $PolicyRule.DocumentNameMatchesWords + ExceptIfAnyOfRecipientAddressMatchesPatterns = $PolicyRule.ExceptIfAnyOfRecipientAddressMatchesPatterns + ExceptIfContentCharacterSetContainsWords = $PolicyRule.ExceptIfContentCharacterSetContainsWords + ExceptIfContentPropertyContainsWords = $PolicyRule.ExceptIfContentPropertyContainsWords + ExceptIfDocumentNameMatchesPatterns = $PolicyRule.ExceptIfDocumentNameMatchesPatterns + ExceptIfDocumentNameMatchesWords = $PolicyRule.ExceptIfDocumentNameMatchesWords + RecipientDomainIs = $PolicyRule.RecipientDomainIs + ExceptIfRecipientDomainIs = $PolicyRule.ExceptIfRecipientDomainIs + ExceptIfSenderDomainIs = $PolicyRule.ExceptIfSenderDomainIs + ExceptIfSenderIPRanges = $PolicyRule.ExceptIfSenderIPRanges + ExceptIfSentTo = $PolicyRule.ExceptIfSentTo + ExceptIfSubjectContainsWords = $PolicyRule.ExceptIfSubjectContainsWords + ExceptIfSubjectMatchesPatterns = $PolicyRule.ExceptIfSubjectMatchesPatterns + ExceptIfSubjectOrBodyContainsWords = $PolicyRule.ExceptIfSubjectOrBodyContainsWords + ExceptIfSubjectOrBodyMatchesPatterns = $PolicyRule.ExceptIfSubjectOrBodyMatchesPatterns + FromAddressMatchesPatterns = $PolicyRule.FromAddressMatchesPatterns + SentToMemberOf = $PolicyRule.FromAddressMatchesPatterns + DocumentContainsWords = $PolicyRule.DocumentContainsWords + ContentIsNotLabeled = $PolicyRule.ContentIsNotLabeled + SetHeader = $PolicyRule.SetHeader + AnyOfRecipientAddressContainsWords = $AnyOfRecipientAddressContainsWords + AnyOfRecipientAddressMatchesPatterns = $AnyOfRecipientAddressMatchesPatterns + ContentExtensionMatchesWords = $ContentExtensionMatchesWords + ExceptIfContentExtensionMatchesWords = $ExceptIfContentExtensionMatchesWords + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens + } + + $paramsToRemove = @() + foreach ($paramName in $result.Keys) + { + if ($null -eq $result[$paramName] -or '' -eq $result[$paramName] -or @() -eq $result[$paramName]) { - $result.Remove($paramName) + $paramsToRemove += $paramName } + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + foreach ($paramName in $paramsToRemove) + { + $result.Remove($paramName) } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -1477,6 +1475,7 @@ function Export-TargetResource Write-Host " |---[$i/$($rules.Length)] $($rule.Name)" -NoNewline + $Script:exportedInstance = $rule $Results = Get-TargetResource @PSBoundParameters ` -Name $rule.name ` -Policy $rule.ParentPolicyName diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConditionalAccessPolicy/MSFT_SCDeviceConditionalAccessPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConditionalAccessPolicy/MSFT_SCDeviceConditionalAccessPolicy.psm1 index 22a8b59815..35e85c6136 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConditionalAccessPolicy/MSFT_SCDeviceConditionalAccessPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConditionalAccessPolicy/MSFT_SCDeviceConditionalAccessPolicy.psm1 @@ -50,65 +50,60 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Device Conditional Access Policy for $Name" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of Device Conditional Access Policy for $Name" - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - $PolicyObject = Get-DeviceConditionalAccessPolicy -Identity $Name ` - -ErrorAction SilentlyContinue + $PolicyObject = Get-DeviceConditionalAccessPolicy -Identity $Name ` + -ErrorAction SilentlyContinue - if ($null -eq $PolicyObject) - { - Write-Verbose -Message "Device Conditional Access Policy $($Name) does not exist." - return $nullReturn + if ($null -eq $PolicyObject) + { + Write-Verbose -Message "Device Conditional Access Policy $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing Device Conditional Access Policy $($Name)" - $result = @{ - Ensure = 'Present' - Name = $PolicyObject.Name - Comment = $PolicyObject.Comment - Enabled = $PolicyObject.Enabled - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } + $PolicyObject = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing Device Conditional Access Policy $($Name)" + $result = @{ + Ensure = 'Present' + Name = $PolicyObject.Name + Comment = $PolicyObject.Comment + Enabled = $PolicyObject.Enabled + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -394,6 +389,7 @@ function Export-TargetResource Write-Host " |---[$i/$($policies.Length)] $($policy.Name)" -NoNewline + $Script:exportedInstance = $policy $Results = Get-TargetResource @PSBoundParameters -Name $policy.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConditionalAccessRule/MSFT_SCDeviceConditionalAccessRule.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConditionalAccessRule/MSFT_SCDeviceConditionalAccessRule.psm1 index b1932e3bef..dc887d1bf9 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConditionalAccessRule/MSFT_SCDeviceConditionalAccessRule.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConditionalAccessRule/MSFT_SCDeviceConditionalAccessRule.psm1 @@ -238,44 +238,45 @@ function Get-TargetResource $AccessTokens ) - New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters | Out-Null + try + { + if (-not $Script:exportedInstance) + { + New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters | Out-Null - New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters | Out-Null + New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters | Out-Null - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullResult = $PSBoundParameters - $nullResult.Ensure = 'Absent' - try - { - $policyObj = Get-DeviceConditionalAccessPolicy | Where-Object -FilterScript { $_.Name -eq $Policy } - if ($null -ne $policyObj) - { - Write-Verbose -Message "Found policy object {$Policy}" - if ($null -ne $Script:exportedInstances -and $Script:ExportMode -and $null) + $nullResult = $PSBoundParameters + $nullResult.Ensure = 'Absent' + + $policyObj = Get-DeviceConditionalAccessPolicy | Where-Object -FilterScript { $_.Name -eq $Policy } + if ($null -ne $policyObj) { - $instance = $Script:exportedInstances | Where-Object -FilterScript { $_.Policy -eq $policyObj.ExchangeObjectId } + Write-Verbose -Message "Found policy object {$Policy}" + $instance = Get-DeviceConditionalAccessRule | Where-Object -FilterScript { $_.Policy -eq $policyObj.ExchangeObjectId } } - else + if ($null -eq $instance) { - $instance = Get-DeviceConditionalAccessRule | Where-Object -FilterScript { $_.Policy -eq $policyObj.ExchangeObjectId } + return $nullResult } } - if ($null -eq $instance) + else { - return $nullResult + $instance = $Script:exportedInstance } $groupNames = @() @@ -1039,6 +1040,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $config $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConfigurationPolicy/MSFT_SCDeviceConfigurationPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConfigurationPolicy/MSFT_SCDeviceConfigurationPolicy.psm1 index 716a316834..ed9e1de087 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConfigurationPolicy/MSFT_SCDeviceConfigurationPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCDeviceConfigurationPolicy/MSFT_SCDeviceConfigurationPolicy.psm1 @@ -50,65 +50,61 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Device Configuration Policy for $Name" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of Device Configuration Policy for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'ExchangeOnline' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - try - { - $PolicyObject = Get-DeviceConfigurationPolicy -Identity $Name ` - -ErrorAction SilentlyContinue + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - if ($null -eq $PolicyObject) - { - Write-Verbose -Message "Device Configuration Policy $($Name) does not exist." - return $nullReturn + $PolicyObject = Get-DeviceConfigurationPolicy -Identity $Name ` + -ErrorAction SilentlyContinue + + if ($null -eq $PolicyObject) + { + Write-Verbose -Message "Device Configuration Policy $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing Device Configuration Policy $($Name)" - $result = @{ - Ensure = 'Present' - Name = $PolicyObject.Name - Comment = $PolicyObject.Comment - Enabled = $PolicyObject.Enabled - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } + $PolicyObject = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing Device Configuration Policy $($Name)" + $result = @{ + Ensure = 'Present' + Name = $PolicyObject.Name + Comment = $PolicyObject.Comment + Enabled = $PolicyObject.Enabled + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -395,6 +391,7 @@ function Export-TargetResource Write-Host " |---[$i/$($policies.Length)] $($policy.Name)" -NoNewline + $Script:exportedInstance = $policy $Results = Get-TargetResource @PSBoundParameters -Name $policy.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyAuthority/MSFT_SCFilePlanPropertyAuthority.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyAuthority/MSFT_SCFilePlanPropertyAuthority.psm1 index 7a9429b79e..0b2b70ffa6 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyAuthority/MSFT_SCFilePlanPropertyAuthority.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyAuthority/MSFT_SCFilePlanPropertyAuthority.psm1 @@ -42,62 +42,59 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCFilePlanPropertyAuthority for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCFilePlanPropertyAuthority for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - try - { - $property = Get-FilePlanPropertyAuthority -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Name } + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - if ($null -eq $property) - { - Write-Verbose -Message "SCFilePlanPropertyAuthority $($Name) does not exist." - return $nullReturn + $property = Get-FilePlanPropertyAuthority -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Name } + + if ($null -eq $property) + { + Write-Verbose -Message "SCFilePlanPropertyAuthority $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCFilePlanPropertyAuthority $($Name)" - - $result = @{ - Name = $property.DisplayName - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $property = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCFilePlanPropertyAuthority $($Name)" + + $result = @{ + Name = $property.DisplayName + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -363,6 +360,7 @@ function Export-TargetResource Write-Host " |---[$i/$($Properties.Length)] $($Property.Name)" -NoNewline + $Script:exportedInstance = $Property $Results = Get-TargetResource @PSBoundParameters -Name $Property.DisplayName $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyCategory/MSFT_SCFilePlanPropertyCategory.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyCategory/MSFT_SCFilePlanPropertyCategory.psm1 index d70c4433f5..5dd84e82ba 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyCategory/MSFT_SCFilePlanPropertyCategory.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyCategory/MSFT_SCFilePlanPropertyCategory.psm1 @@ -42,61 +42,59 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCFilePlanPropertyCategory for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCFilePlanPropertyCategory for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $property = Get-FilePlanPropertyCategory -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Name } + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $property) - { - Write-Verbose -Message "SCFilePlanPropertyCategory $($Name) does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $property = Get-FilePlanPropertyCategory -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Name } + + if ($null -eq $property) + { + Write-Verbose -Message "SCFilePlanPropertyCategory $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCFilePlanPropertyCategory $($Name)" - - $result = @{ - Name = $property.DisplayName - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $property = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCFilePlanPropertyCategory $($Name)" + + $result = @{ + Name = $property.DisplayName + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -364,6 +362,7 @@ function Export-TargetResource Write-Host " |---[$i/$($Properties.Length)] $($Property.Name)" -NoNewline + $Script:exportedInstance = $Property $Results = Get-TargetResource @PSBoundParameters -Name $Property.DisplayName $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyCitation/MSFT_SCFilePlanPropertyCitation.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyCitation/MSFT_SCFilePlanPropertyCitation.psm1 index 5ca55e538b..5fb975d4dd 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyCitation/MSFT_SCFilePlanPropertyCitation.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyCitation/MSFT_SCFilePlanPropertyCitation.psm1 @@ -50,65 +50,61 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCFilePlanPropertyCitation for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCFilePlanPropertyCitation for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - $property = Get-FilePlanPropertyCitation -ErrorAction Stop | Where-Object -FilterScript { $_.Name -eq $Name } + $property = Get-FilePlanPropertyCitation -ErrorAction Stop | Where-Object -FilterScript { $_.Name -eq $Name } - if ($null -eq $property) - { - Write-Verbose -Message "SCFilePlanPropertyCitation $($Name) does not exist." - return $nullReturn + if ($null -eq $property) + { + Write-Verbose -Message "SCFilePlanPropertyCitation $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCFilePlanPropertyCitation $($Name)" - - $result = @{ - Name = $property.Name - CitationUrl = $property.CitationUrl - CitationJurisdiction = $property.CitationJurisdiction - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $property = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCFilePlanPropertyCitation $($Name)" + + $result = @{ + Name = $property.Name + CitationUrl = $property.CitationUrl + CitationJurisdiction = $property.CitationJurisdiction + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -391,6 +387,7 @@ function Export-TargetResource Write-Host " |---[$i/$($Properties.Length)] $($Property.Name)" -NoNewline + $Script:exportedInstance = $Property $Results = Get-TargetResource @PSBoundParameters -Name $Property.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyDepartment/MSFT_SCFilePlanPropertyDepartment.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyDepartment/MSFT_SCFilePlanPropertyDepartment.psm1 index d1a851107c..5caf4b1160 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyDepartment/MSFT_SCFilePlanPropertyDepartment.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyDepartment/MSFT_SCFilePlanPropertyDepartment.psm1 @@ -42,62 +42,59 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCFilePlanPropertyDepartment for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCFilePlanPropertyDepartment for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $property = Get-FilePlanPropertyDepartment -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Name } + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - if ($null -eq $property) - { - Write-Verbose -Message "SCFilePlanPropertyDepartment $($Name) does not exist." - return $nullReturn + $property = Get-FilePlanPropertyDepartment -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Name } + + if ($null -eq $property) + { + Write-Verbose -Message "SCFilePlanPropertyDepartment $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCFilePlanPropertyDepartment $($Name)" - - $result = @{ - Name = $property.DisplayName - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $property = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCFilePlanPropertyDepartment $($Name)" + + $result = @{ + Name = $property.DisplayName + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -364,6 +361,7 @@ function Export-TargetResource Write-Host " |---[$i/$($Properties.Length)] $($Property.Name)" -NoNewline + $Script:exportedInstance = $Property $Results = Get-TargetResource @PSBoundParameters -Name $Property.DisplayName $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyReferenceId/MSFT_SCFilePlanPropertyReferenceId.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyReferenceId/MSFT_SCFilePlanPropertyReferenceId.psm1 index c1461d3661..422737c0d0 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyReferenceId/MSFT_SCFilePlanPropertyReferenceId.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertyReferenceId/MSFT_SCFilePlanPropertyReferenceId.psm1 @@ -42,62 +42,59 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCFilePlanPropertyReferenceId for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCFilePlanPropertyReferenceId for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - try - { - $property = Get-FilePlanPropertyReferenceId -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Name } + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - if ($null -eq $property) - { - Write-Verbose -Message "SCFilePlanPropertyReferenceId $($Name) does not exist." - return $nullReturn + $property = Get-FilePlanPropertyReferenceId -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Name } + + if ($null -eq $property) + { + Write-Verbose -Message "SCFilePlanPropertyReferenceId $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCFilePlanPropertyReferenceId $($Name)" - - $result = @{ - Name = $property.DisplayName - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $property = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCFilePlanPropertyReferenceId $($Name)" + + $result = @{ + Name = $property.DisplayName + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -364,6 +361,7 @@ function Export-TargetResource Write-Host " |---[$i/$($Properties.Length)] $($Property.Name)" -NoNewline + $Script:exportedInstance = $Property $Results = Get-TargetResource @PSBoundParameters -Name $Property.DisplayName $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertySubCategory/MSFT_SCFilePlanPropertySubCategory.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertySubCategory/MSFT_SCFilePlanPropertySubCategory.psm1 index 5302a4acc8..1c787d68db 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertySubCategory/MSFT_SCFilePlanPropertySubCategory.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCFilePlanPropertySubCategory/MSFT_SCFilePlanPropertySubCategory.psm1 @@ -46,73 +46,70 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCFilePlanPropertySubCategory for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCFilePlanPropertySubCategory for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $parent = Get-FilePlanPropertyCategory -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Category } + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - if ($null -eq $parent) - { - Write-Warning "Invalid Parent Category {$Category} detected in the Get-TargetResource" - return $nullReturn - } + $parent = Get-FilePlanPropertyCategory -ErrorAction Stop | Where-Object -FilterScript { $_.DisplayName -eq $Category } - $parentId = $parent.Guid - $property = Get-FilePlanPropertySubCategory | Where-Object -FilterScript { $_.DisplayName -eq $Name -and ` - $_.ParentId -eq $parentId } + if ($null -eq $parent) + { + Write-Warning "Invalid Parent Category {$Category} detected in the Get-TargetResource" + return $nullReturn + } - if ($null -eq $property) - { - Write-Verbose -Message "SCFilePlanPropertySubCategory $($Name) does not exist." - return $nullReturn + $parentId = $parent.Guid + $property = Get-FilePlanPropertySubCategory | Where-Object -FilterScript { $_.DisplayName -eq $Name -and ` + $_.ParentId -eq $parentId } + + if ($null -eq $property) + { + Write-Verbose -Message "SCFilePlanPropertySubCategory $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCFilePlanPropertySubCategory $($Name)" - - $result = @{ - Name = $property.DisplayName - Category = $parent.DisplayName - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $property = $Script:exportedInstance + } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SCFilePlanPropertySubCategory $($Name)" + + $result = @{ + Name = $property.DisplayName + Category = $Category + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -391,6 +388,7 @@ function Export-TargetResource $parent = Get-FilePlanPropertyCategory | Where-Object -FilterScript { $_.Guid -like "*$($property.ParentId)*" } Write-Host " |---[$i/$($Properties.Length)] $($Property.Name)" -NoNewline + $Script:exportedInstance = $Property $Results = Get-TargetResource @PSBoundParameters ` -Name $Property.DisplayName ` -Category $parent.DisplayName diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCLabelPolicy/MSFT_SCLabelPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCLabelPolicy/MSFT_SCLabelPolicy.psm1 index e2d2bfefe0..ed9c5cd68e 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCLabelPolicy/MSFT_SCLabelPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCLabelPolicy/MSFT_SCLabelPolicy.psm1 @@ -110,96 +110,93 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Sensitivity Label Policy for $Name" - - if ($PSBoundParameters.ContainsKey('Labels') -and ` - ($PSBoundParameters.ContainsKey('AddLabels') -or $PSBoundParameters.ContainsKey('RemoveLabels'))) - { - throw 'You cannot use the Labels parameter and the AddLabels or RemoveLabels parameters at the same time.' - } - - if ($PSBoundParameters.ContainsKey('AddLabels') -and $PSBoundParameters.ContainsKey('RemoveLabels')) + try { - # Check if AddLabels and RemoveLabels contain the same labels - [array]$diff = Compare-Object -ReferenceObject $AddLabels -DifferenceObject $RemoveLabels -ExcludeDifferent -IncludeEqual - if ($diff.Count -gt 0) + if (-not $Script:exportedInstance) { - throw 'Parameters AddLabels and RemoveLabels cannot contain the same labels. Make sure labels are not present in both parameters.' - } - } + Write-Verbose -Message "Getting configuration of Sensitivity Label Policy for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if ($PSBoundParameters.ContainsKey('Labels') -and ` + ($PSBoundParameters.ContainsKey('AddLabels') -or $PSBoundParameters.ContainsKey('RemoveLabels'))) + { + throw 'You cannot use the Labels parameter and the AddLabels or RemoveLabels parameters at the same time.' + } - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + if ($PSBoundParameters.ContainsKey('AddLabels') -and $PSBoundParameters.ContainsKey('RemoveLabels')) + { + # Check if AddLabels and RemoveLabels contain the same labels + [array]$diff = Compare-Object -ReferenceObject $AddLabels -DifferenceObject $RemoveLabels -ExcludeDifferent -IncludeEqual + if ($diff.Count -gt 0) + { + throw 'Parameters AddLabels and RemoveLabels cannot contain the same labels. Make sure labels are not present in both parameters.' + } + } - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - try - { - $policy = Get-LabelPolicy -Identity $Name -ErrorAction SilentlyContinue -WarningAction Ignore + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + try + { + $policy = Get-LabelPolicy -Identity $Name -ErrorAction SilentlyContinue -WarningAction Ignore + } + catch + { + throw $_ + } + + if ($null -eq $policy) + { + Write-Verbose -Message "Sensitivity label policy $($Name) does not exist." + return $nullReturn + } } - catch + else { - throw $_ + $policy = $Script:exportedInstance } - if ($null -eq $policy) + if ($null -ne $policy.Settings) { - Write-Verbose -Message "Sensitivity label policy $($Name) does not exist." - return $nullReturn + $advancedSettingsValue = Convert-StringToAdvancedSettings -AdvancedSettings $policy.Settings } - else - { - if ($null -ne $policy.Settings) - { - $advancedSettingsValue = Convert-StringToAdvancedSettings -AdvancedSettings $policy.Settings - } - Write-Verbose "Found existing Sensitivity Label policy $($Name)" - $result = @{ - Name = $policy.Name - Comment = $policy.Comment - AdvancedSettings = $advancedSettingsValue - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - Labels = $policy.Labels - ExchangeLocation = Convert-ArrayList -CurrentProperty $policy.ExchangeLocation - ExchangeLocationException = Convert-ArrayList -CurrentProperty $policy.ExchangeLocationException - ModernGroupLocation = Convert-ArrayList -CurrentProperty $policy.ModernGroupLocation - ModernGroupLocationException = Convert-ArrayList -CurrentProperty $policy.ModernGroupLocationException - AccessTokens = $AccessTokens - } - - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing Sensitivity Label policy $($Name)" + $result = @{ + Name = $policy.Name + Comment = $policy.Comment + AdvancedSettings = $advancedSettingsValue + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + Labels = $policy.Labels + ExchangeLocation = Convert-ArrayList -CurrentProperty $policy.ExchangeLocation + ExchangeLocationException = Convert-ArrayList -CurrentProperty $policy.ExchangeLocationException + ModernGroupLocation = Convert-ArrayList -CurrentProperty $policy.ModernGroupLocation + ModernGroupLocationException = Convert-ArrayList -CurrentProperty $policy.ModernGroupLocationException + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -854,6 +851,7 @@ function Export-TargetResource Write-Host " |---[$i/$($policies.Count)] $($policy.Name)" -NoNewline + $Script:exportedInstance = $policy $Results = Get-TargetResource @PSBoundParameters -Name $policy.Name if ($null -ne $Results.AdvancedSettings) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCProtectionAlert/MSFT_SCProtectionAlert.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCProtectionAlert/MSFT_SCProtectionAlert.psm1 index 92f7516c3c..29e58bf67b 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCProtectionAlert/MSFT_SCProtectionAlert.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCProtectionAlert/MSFT_SCProtectionAlert.psm1 @@ -139,83 +139,80 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SCProtectionAlert for $Name" - - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SCProtectionAlert for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $AlertObject = Get-ProtectionAlert -Identity $Name -ErrorAction SilentlyContinue + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $AlertObject) - { - Write-Verbose -Message "SCProtectionAlert $Name does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $AlertObject = Get-ProtectionAlert -Identity $Name -ErrorAction SilentlyContinue + + if ($null -eq $AlertObject) + { + Write-Verbose -Message "SCProtectionAlert $Name does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SCProtectionAlert $($Name)" - $result = @{ - Ensure = 'Present' - AlertBy = $AlertObject.AlertBy - AlertFor = $AlertObject.AlertFor - AggregationType = $AlertObject.AggregationType - Category = $AlertObject.Category - Comment = $AlertObject.Comment - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Disabled = $AlertObject.Disabled - Filter = $AlertObject.Filter - Name = $AlertObject.Name - NotificationCulture = $AlertObject.NotificationCulture - NotificationEnabled = $AlertObject.NotificationEnabled - NotifyUserOnFilterMatch = $AlertObject.NotifyUserOnFilterMatch - NotifyUserSuppressionExpiryDate = $AlertObject.NotifyUserSuppressionExpiryDate - NotifyUserThrottleThreshold = $AlertObject.NotifyUserThrottleThreshold - NotifyUserThrottleWindow = $AlertObject.NotifyUserThrottleWindow - NotifyUser = $AlertObject.NotifyUser - Operation = $AlertObject.Operation - PrivacyManagementScopedSensitiveInformationTypes = $AlertObject.PrivacyManagementScopedSensitiveInformationTypes - PrivacyManagementScopedSensitiveInformationTypesForCounting = $AlertObject.PrivacyManagementScopedSensitiveInformationTypesForCounting - PrivacyManagementScopedSensitiveInformationTypesThreshold = $AlertObject.PrivacyManagementScopedSensitiveInformationTypesThreshold - Severity = $AlertObject.Severity - ThreatType = $AlertObject.ThreatType - Threshold = $AlertObject.Threshold - TimeWindow = $AlertObject.TimeWindow - VolumeThreshold = $AlertObject.VolumeThreshold - AccessTokens = $AccessTokens - } - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + $AlertObject = $Script:exportedInstance + } + + Write-Verbose "Found existing SCProtectionAlert $($Name)" + $result = @{ + Ensure = 'Present' + AlertBy = $AlertObject.AlertBy + AlertFor = $AlertObject.AlertFor + AggregationType = $AlertObject.AggregationType + Category = $AlertObject.Category + Comment = $AlertObject.Comment + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Disabled = $AlertObject.Disabled + Filter = $AlertObject.Filter + Name = $AlertObject.Name + NotificationCulture = $AlertObject.NotificationCulture + NotificationEnabled = $AlertObject.NotificationEnabled + NotifyUserOnFilterMatch = $AlertObject.NotifyUserOnFilterMatch + NotifyUserSuppressionExpiryDate = $AlertObject.NotifyUserSuppressionExpiryDate + NotifyUserThrottleThreshold = $AlertObject.NotifyUserThrottleThreshold + NotifyUserThrottleWindow = $AlertObject.NotifyUserThrottleWindow + NotifyUser = $AlertObject.NotifyUser + Operation = $AlertObject.Operation + PrivacyManagementScopedSensitiveInformationTypes = $AlertObject.PrivacyManagementScopedSensitiveInformationTypes + PrivacyManagementScopedSensitiveInformationTypesForCounting = $AlertObject.PrivacyManagementScopedSensitiveInformationTypesForCounting + PrivacyManagementScopedSensitiveInformationTypesThreshold = $AlertObject.PrivacyManagementScopedSensitiveInformationTypesThreshold + Severity = $AlertObject.Severity + ThreatType = $AlertObject.ThreatType + Threshold = $AlertObject.Threshold + TimeWindow = $AlertObject.TimeWindow + VolumeThreshold = $AlertObject.VolumeThreshold + AccessTokens = $AccessTokens } + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -673,6 +670,7 @@ function Export-TargetResource } Write-Host " |---[$i/$($totalAlerts)] $($alert.Name)" -NoNewline + $Script:exportedInstance = $alert $Results = Get-TargetResource @PSBoundParameters -Name $Alert.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionCompliancePolicy/MSFT_SCRetentionCompliancePolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionCompliancePolicy/MSFT_SCRetentionCompliancePolicy.psm1 index f8626b0ad5..c972c13b56 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionCompliancePolicy/MSFT_SCRetentionCompliancePolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionCompliancePolicy/MSFT_SCRetentionCompliancePolicy.psm1 @@ -118,167 +118,165 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of RetentionCompliancePolicy for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of RetentionCompliancePolicy for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $PolicyObject = Get-RetentionCompliancePolicy $Name -DistributionDetail -ErrorAction SilentlyContinue + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $PolicyObject) - { - Write-Verbose -Message "RetentionCompliancePolicy $($Name) does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $PolicyObject = Get-RetentionCompliancePolicy $Name -DistributionDetail -ErrorAction SilentlyContinue + + if ($null -eq $PolicyObject) + { + Write-Verbose -Message "RetentionCompliancePolicy $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing RetentionCompliancePolicy $($Name)" + $PolicyObject = $Script:exportedInstance + } - if ($PolicyObject.TeamsPolicy) - { - $result = @{ - Ensure = 'Present' - Name = $PolicyObject.Name - Comment = $PolicyObject.Comment - Enabled = $PolicyObject.Enabled - RestrictiveRetention = $PolicyObject.RestrictiveRetention - TeamsChannelLocation = @() - TeamsChannelLocationException = @() - TeamsChatLocation = @() - TeamsChatLocationException = @() - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } + Write-Verbose "Found existing RetentionCompliancePolicy $($Name)" - if ($PolicyObject.TeamsChannelLocation.Count -gt 0) - { - $result.TeamsChannelLocation = [array]$PolicyObject.TeamsChannelLocation.Name - } - if ($PolicyObject.TeamsChatLocation.Count -gt 0) - { - $result.TeamsChatLocation = [array]$PolicyObject.TeamsChatLocation.Name - } - if ($PolicyObject.TeamsChannelLocationException.Count -gt 0) - { - $result.TeamsChannelLocationException = [array]$PolicyObject.TeamsChannelLocationException.Name - } - if ($PolicyObject.TeamsChatLocationException.Count -gt 0) - { - $result.TeamsChatLocationException = $PolicyObject.TeamsChatLocationException.Name - } + if ($PolicyObject.TeamsPolicy) + { + $result = @{ + Ensure = 'Present' + Name = $PolicyObject.Name + Comment = $PolicyObject.Comment + Enabled = $PolicyObject.Enabled + RestrictiveRetention = $PolicyObject.RestrictiveRetention + TeamsChannelLocation = @() + TeamsChannelLocationException = @() + TeamsChatLocation = @() + TeamsChatLocationException = @() + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens } - else - { - $result = @{ - Ensure = 'Present' - Name = $PolicyObject.Name - Comment = $PolicyObject.Comment - DynamicScopeLocation = @() - Enabled = $PolicyObject.Enabled - ExchangeLocation = @() - ExchangeLocationException = @() - ModernGroupLocation = @() - ModernGroupLocationException = @() - OneDriveLocation = @() - OneDriveLocationException = @() - PublicFolderLocation = @() - RestrictiveRetention = $PolicyObject.RestrictiveRetention - SharePointLocation = @() - SharePointLocationException = @() - SkypeLocation = @() - SkypeLocationException = @() - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } - if ($PolicyObject.DynamicScopeLocation.Count -gt 0) - { - $result.DynamicScopeLocation = [array]$PolicyObject.DynamicScopeLocation.Name - } - if ($PolicyObject.ExchangeLocation.Count -gt 0) - { - $result.ExchangeLocation = [array]$PolicyObject.ExchangeLocation.Name - } - if ($PolicyObject.ModernGroupLocation.Count -gt 0) - { - $result.ModernGroupLocation = [array]$PolicyObject.ModernGroupLocation.Name - } - if ($PolicyObject.OneDriveLocation.Count -gt 0) - { - $result.OneDriveLocation = [array]$PolicyObject.OneDriveLocation.Name - } - if ($PolicyObject.PublicFolderLocation.Count -gt 0) - { - $result.PublicFolderLocation = [array]$PolicyObject.PublicFolderLocation.Name - } - if ($PolicyObject.SharePointLocation.Count -gt 0) - { - $result.SharePointLocation = [array]$PolicyObject.SharePointLocation.Name - } - if ($PolicyObject.SkypeLocation.Count -gt 0) - { - $result.SkypeLocation = [array]$PolicyObject.SkypeLocation.Name - } - if ($PolicyObject.ExchangeLocationException.Count -gt 0) - { - $result.ExchangeLocationException = [array]$PolicyObject.ExchangeLocationException.Name - } - if ($PolicyObject.ModernGroupLocationException.Count -gt 0) - { - $result.ModernGroupLocationException = [array]$PolicyObject.ModernGroupLocationException.Name - } - if ($PolicyObject.OneDriveLocationException.Count -gt 0) - { - $result.OneDriveLocationException = [array]$PolicyObject.OneDriveLocationException.Name - } - if ($PolicyObject.SharePointLocationException.Count -gt 0) - { - $result.SharePointLocationException = [array]$PolicyObject.SharePointLocationException.Name - } - if ($PolicyObject.SkypeLocationException.Count -gt 0) - { - $result.SkypeLocationException = [array]$PolicyObject.SkypeLocationException.Name - } + if ($PolicyObject.TeamsChannelLocation.Count -gt 0) + { + $result.TeamsChannelLocation = [array]$PolicyObject.TeamsChannelLocation.Name + } + if ($PolicyObject.TeamsChatLocation.Count -gt 0) + { + $result.TeamsChatLocation = [array]$PolicyObject.TeamsChatLocation.Name + } + if ($PolicyObject.TeamsChannelLocationException.Count -gt 0) + { + $result.TeamsChannelLocationException = [array]$PolicyObject.TeamsChannelLocationException.Name + } + if ($PolicyObject.TeamsChatLocationException.Count -gt 0) + { + $result.TeamsChatLocationException = $PolicyObject.TeamsChatLocationException.Name + } + } + else + { + $result = @{ + Ensure = 'Present' + Name = $PolicyObject.Name + Comment = $PolicyObject.Comment + DynamicScopeLocation = @() + Enabled = $PolicyObject.Enabled + ExchangeLocation = @() + ExchangeLocationException = @() + ModernGroupLocation = @() + ModernGroupLocationException = @() + OneDriveLocation = @() + OneDriveLocationException = @() + PublicFolderLocation = @() + RestrictiveRetention = $PolicyObject.RestrictiveRetention + SharePointLocation = @() + SharePointLocationException = @() + SkypeLocation = @() + SkypeLocationException = @() + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens } - Write-Verbose -Message "Found RetentionCompliancePolicy $($Name)" - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + if ($PolicyObject.DynamicScopeLocation.Count -gt 0) + { + $result.DynamicScopeLocation = [array]$PolicyObject.DynamicScopeLocation.Name + } + if ($PolicyObject.ExchangeLocation.Count -gt 0) + { + $result.ExchangeLocation = [array]$PolicyObject.ExchangeLocation.Name + } + if ($PolicyObject.ModernGroupLocation.Count -gt 0) + { + $result.ModernGroupLocation = [array]$PolicyObject.ModernGroupLocation.Name + } + if ($PolicyObject.OneDriveLocation.Count -gt 0) + { + $result.OneDriveLocation = [array]$PolicyObject.OneDriveLocation.Name + } + if ($PolicyObject.PublicFolderLocation.Count -gt 0) + { + $result.PublicFolderLocation = [array]$PolicyObject.PublicFolderLocation.Name + } + if ($PolicyObject.SharePointLocation.Count -gt 0) + { + $result.SharePointLocation = [array]$PolicyObject.SharePointLocation.Name + } + if ($PolicyObject.SkypeLocation.Count -gt 0) + { + $result.SkypeLocation = [array]$PolicyObject.SkypeLocation.Name + } + if ($PolicyObject.ExchangeLocationException.Count -gt 0) + { + $result.ExchangeLocationException = [array]$PolicyObject.ExchangeLocationException.Name + } + if ($PolicyObject.ModernGroupLocationException.Count -gt 0) + { + $result.ModernGroupLocationException = [array]$PolicyObject.ModernGroupLocationException.Name + } + if ($PolicyObject.OneDriveLocationException.Count -gt 0) + { + $result.OneDriveLocationException = [array]$PolicyObject.OneDriveLocationException.Name + } + if ($PolicyObject.SharePointLocationException.Count -gt 0) + { + $result.SharePointLocationException = [array]$PolicyObject.SharePointLocationException.Name + } + if ($PolicyObject.SkypeLocationException.Count -gt 0) + { + $result.SkypeLocationException = [array]$PolicyObject.SkypeLocationException.Name + } } + + Write-Verbose -Message "Found RetentionCompliancePolicy $($Name)" + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -1071,7 +1069,7 @@ function Export-TargetResource try { - [array]$policies = Get-RetentionCompliancePolicy -ErrorAction Stop + [array]$policies = Get-RetentionCompliancePolicy -DistributionDetail -ErrorAction Stop $i = 1 if ($policies.Length -eq 0) @@ -1092,6 +1090,7 @@ function Export-TargetResource Write-Host " |---[$i/$($policies.Length)] $($policy.Name)" -NoNewline + $Script:exportedInstance = $policy $Results = Get-TargetResource @PSBoundParameters -Name $policy.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionComplianceRule/MSFT_SCRetentionComplianceRule.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionComplianceRule/MSFT_SCRetentionComplianceRule.psm1 index b38cc365f2..6ac1ecce7a 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionComplianceRule/MSFT_SCRetentionComplianceRule.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionComplianceRule/MSFT_SCRetentionComplianceRule.psm1 @@ -77,80 +77,78 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of RetentionComplianceRule for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of RetentionComplianceRule for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $RuleObject = Get-RetentionComplianceRule -Identity $Name ` - -ErrorAction SilentlyContinue - if ($null -eq $RuleObject) - { - Write-Verbose -Message "RetentionComplianceRule $($Name) does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $RuleObject = Get-RetentionComplianceRule -Identity $Name ` + -ErrorAction SilentlyContinue + + if ($null -eq $RuleObject) + { + Write-Verbose -Message "RetentionComplianceRule $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing RetentionComplianceRule $($Name)" - $AssociatedPolicy = Get-RetentionCompliancePolicy $RuleObject.Policy - $RetentionComplianceActionValue = $null - if (-not [System.String]::IsNullOrEmpty($ruleObject.RetentionComplianceAction)) - { - $RetentionComplianceActionValue = $RuleObject.RetentionComplianceAction - } - $result = @{ - Name = $RuleObject.Name - Comment = $RuleObject.Comment - Policy = $AssociatedPolicy.Name - RetentionDuration = $RuleObject.RetentionDuration - RetentionComplianceAction = $RetentionComplianceActionValue - RetentionDurationDisplayHint = $RuleObject.RetentionDurationDisplayHint - ExpirationDateOption = $RuleObject.ExpirationDateOption - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } - if (-not $associatedPolicy.TeamsPolicy) - { - $result.Add('ExcludedItemClasses', $RuleObject.ExcludedItemClasses) - $result.Add('ContentMatchQuery', $RuleObject.ContentMatchQuery) - } + $RuleObject = $Script:exportedInstance + } - Write-Verbose -Message "Found RetentionComplianceRule $($Name)" - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing RetentionComplianceRule $($Name)" + $AssociatedPolicy = Get-RetentionCompliancePolicy $RuleObject.Policy + $RetentionComplianceActionValue = $null + if (-not [System.String]::IsNullOrEmpty($ruleObject.RetentionComplianceAction)) + { + $RetentionComplianceActionValue = $RuleObject.RetentionComplianceAction } + $result = @{ + Name = $RuleObject.Name + Comment = $RuleObject.Comment + Policy = $AssociatedPolicy.Name + RetentionDuration = $RuleObject.RetentionDuration + RetentionComplianceAction = $RetentionComplianceActionValue + RetentionDurationDisplayHint = $RuleObject.RetentionDurationDisplayHint + ExpirationDateOption = $RuleObject.ExpirationDateOption + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens + } + if (-not $associatedPolicy.TeamsPolicy) + { + $result.Add('ExcludedItemClasses', $RuleObject.ExcludedItemClasses) + $result.Add('ContentMatchQuery', $RuleObject.ContentMatchQuery) + } + + Write-Verbose -Message "Found RetentionComplianceRule $($Name)" + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -596,6 +594,7 @@ function Export-TargetResource Write-Host " |---[$i/$($rules.Length)] $($rule.Name)" -NoNewline + $Script:exportedInstance = $rule $Results = Get-TargetResource @PSBoundParameters ` -Name $rule.Name ` -Policy $rule.Policy diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionEventType/MSFT_SCRetentionEventType.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionEventType/MSFT_SCRetentionEventType.psm1 index 847519cbfa..f74a1393ea 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionEventType/MSFT_SCRetentionEventType.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRetentionEventType/MSFT_SCRetentionEventType.psm1 @@ -46,64 +46,62 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Retention Event Type for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of Retention Event Type for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $EventTypeObject = Get-ComplianceRetentionEventType -Identity $Name ` - -ErrorAction SilentlyContinue - if ($null -eq $EventTypeObject) - { - Write-Verbose -Message "RetentionComplianceEventType $($Name) does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $EventTypeObject = Get-ComplianceRetentionEventType -Identity $Name ` + -ErrorAction SilentlyContinue + + if ($null -eq $EventTypeObject) + { + Write-Verbose -Message "RetentionComplianceEventType $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing RetentionComplianceEventType $($Name)" - $result = @{ - Name = $EventTypeObject.Name - Comment = $EventTypeObject.Comment - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - AccessTokens = $AccessTokens - } + $EventTypeObject = $Script:exportedInstance + } - Write-Verbose -Message "Found RetentionComplianceEventType $($Name)" - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing RetentionComplianceEventType $($Name)" + $result = @{ + Name = $EventTypeObject.Name + Comment = $EventTypeObject.Comment + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found RetentionComplianceEventType $($Name)" + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -380,6 +378,7 @@ function Export-TargetResource Write-Host " |---[$i/$($EventTypes.Length)] $($eventType.Name)" -NoNewline + $Script:exportedInstance = $eventType $Results = Get-TargetResource @PSBoundParameters -Name $eventType.Name $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRoleGroup/MSFT_SCRoleGroup.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRoleGroup/MSFT_SCRoleGroup.psm1 index acc49ae62f..517628bec6 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRoleGroup/MSFT_SCRoleGroup.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRoleGroup/MSFT_SCRoleGroup.psm1 @@ -60,63 +60,61 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Role Group configuration for $Name" - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters + try + { + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Role Group configuration for $Name" + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $RoleGroup = $Script:exportedInstances | Where-Object -FilterScript { $_.Name -eq $Name } - } - else - { $AllRoleGroups = Get-RoleGroup -ErrorAction Stop $RoleGroup = $AllRoleGroups | Where-Object -FilterScript { $_.Name -eq $Name } - } - if ($null -eq $RoleGroup) - { - Write-Verbose -Message "Role Group $($Name) does not exist." - return $nullReturn + if ($null -eq $RoleGroup) + { + Write-Verbose -Message "Role Group $($Name) does not exist." + return $nullReturn + } } else { - $result = @{ - Name = $RoleGroup.Name - DisplayName = $RoleGroup.DisplayName - Description = $RoleGroup.Description - Roles = $RoleGroup.Roles -replace '^.*\/(?=[^\/]*$)' - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Managedidentity = $ManagedIdentity.IsPresent - TenantId = $TenantId - AccessTokens = $AccessTokens - } + $RoleGroup = $Script:exportedInstance + } - Write-Verbose -Message "Found Role Group $($Name)" - return $result + $result = @{ + Name = $RoleGroup.Name + DisplayName = $RoleGroup.DisplayName + Description = $RoleGroup.Description + Roles = $RoleGroup.Roles -replace '^.*\/(?=[^\/]*$)' + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Managedidentity = $ManagedIdentity.IsPresent + TenantId = $TenantId + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found Role Group $($Name)" + return $result } catch { @@ -431,6 +429,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $RoleGroup $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRoleGroupMember/MSFT_SCRoleGroupMember.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRoleGroupMember/MSFT_SCRoleGroupMember.psm1 index fbd769032c..64e0ac78e1 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCRoleGroupMember/MSFT_SCRoleGroupMember.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCRoleGroupMember/MSFT_SCRoleGroupMember.psm1 @@ -51,73 +51,63 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting Role Group configuration for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting Role Group configuration for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - if ($null -ne $Script:exportedInstances -and $Script:ExportMode) - { - $RoleGroup = $Script:exportedInstances | Where-Object -FilterScript { $_.Name -eq $Name } - } - else - { $AllRoleGroups = Get-RoleGroup -ErrorAction Stop $RoleGroup = $AllRoleGroups | Where-Object -FilterScript { $_.Name -eq $Name } - } - if ($null -eq $RoleGroup) - { - Write-Verbose -Message "Role Group $($Name) does not exist." - return $nullReturn + if ($null -eq $RoleGroup) + { + Write-Verbose -Message "Role Group $($Name) does not exist." + return $nullReturn + } } else { - # Get RoleGroup Members if RoleGroup exists. - $roleGroupMember = Get-RoleGroupMember -Identity $Name | Select-Object Name - - $result = @{ - Name = $RoleGroup.Name - Description = $RoleGroup.Description - Members = $roleGroupMember.Name - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - TenantId = $TenantId - AccessTokens = $AccessTokens - } + $RoleGroup = $Script:exportedInstance + } - Write-Verbose -Message "Found Role Group $($Name)" - return $result + # Get RoleGroup Members if RoleGroup exists. + $roleGroupMember = Get-RoleGroupMember -Identity $Name | Select-Object Name + + $result = @{ + Name = $RoleGroup.Name + Description = $RoleGroup.Description + Members = $roleGroupMember.Name + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + TenantId = $TenantId + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found Role Group $($Name)" + return $result } catch { @@ -389,12 +379,10 @@ function Export-TargetResource } Write-Host " |---[$i/$($Script:exportedInstances.Count)] $($RoleGroup.Name)" -NoNewline - $roleGroupMember = Get-RoleGroupMember -Identity $RoleGroup.Name | Select-Object Name $Params = @{ Name = $RoleGroup.Name Description = $RoleGroup.Description - Members = $roleGroupMember.Name Credential = $Credential ApplicationId = $ApplicationId TenantId = $TenantId @@ -403,6 +391,7 @@ function Export-TargetResource CertificatePath = $CertificatePath AccessTokens = $AccessTokens } + $Script:exportedInstance = $RoleGroup $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCSensitivityLabel/MSFT_SCSensitivityLabel.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCSensitivityLabel/MSFT_SCSensitivityLabel.psm1 index c09fdbd22c..7a1f174e2c 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCSensitivityLabel/MSFT_SCSensitivityLabel.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCSensitivityLabel/MSFT_SCSensitivityLabel.psm1 @@ -301,390 +301,387 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of Sensitivity Label for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of Sensitivity Label for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - try - { - try + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + try + { + $label = Get-Label -Identity $Name -ErrorAction SilentlyContinue ` + -IncludeDetailedLabelActions + } + catch + { + throw $_ + } + + if ($null -eq $label) + { + Write-Verbose -Message "Sensitivity label $($Name) does not exist." + return $nullReturn + } + } + else { - $label = Get-Label -Identity $Name -ErrorAction SilentlyContinue ` - -IncludeDetailedLabelActions + $label = $Script:exportedInstance } - catch + + $parentLabelID = $null + if ($null -ne $label.ParentId) { - throw $_ + $parentLabel = Get-Label -Identity $label.ParentId -IncludeDetailedLabelActions -ErrorAction 'SilentlyContinue' + $parentLabelID = $parentLabel.Name } + if ($null -ne $label.LocaleSettings) + { + $localeSettingsValue = Convert-JSONToLocaleSettings -JSONLocalSettings $label.LocaleSettings + } + if ($null -ne $label.Settings) + { + $advancedSettingsValue = Convert-StringToAdvancedSettings -AdvancedSettings $label.Settings + } + Write-Verbose "Found existing Sensitivity Label $($Name)" - if ($null -eq $label) + [Array]$labelActions = $label.LabelActions + $actions = @() + foreach ($labelAction in $labelActions) { - Write-Verbose -Message "Sensitivity label $($Name) does not exist." - return $nullReturn + $action = ConvertFrom-Json ($labelAction | Out-String) + $actions += $action } - else + + $encryption = ($actions | Where-Object -FilterScript { $_.Type -eq 'encrypt' }).Settings + $header = ($actions | Where-Object -FilterScript { $_.Type -eq 'applycontentmarking' -and $_.Subtype -eq 'header' }).Settings + $footer = ($actions | Where-Object -FilterScript { $_.Type -eq 'applycontentmarking' -and $_.Subtype -eq 'footer' }).Settings + $watermark = ($actions | Where-Object -FilterScript { $_.Type -eq 'applywatermarking' }).Settings + $protectgroup = ($actions | Where-Object -FilterScript { $_.Type -eq 'protectgroup' }).Settings + $protectsite = ($actions | Where-Object -FilterScript { $_.Type -eq 'protectsite' }).Settings + + $ApplyContentMarkingFooterTextValue = $null + $footerText = ($footer | Where-Object -FilterScript { $_.Key -eq 'text' }).Value + if ([System.String]::IsNullOrEmpty($footerText) -eq $false) { - $parentLabelID = $null - if ($null -ne $label.ParentId) + $ApplyContentMarkingFooterTextValue = $footerText.Replace('$', '`$') + } + + $ApplyContentMarkingHeaderTextValue = $null + $headerText = ($header | Where-Object -FilterScript { $_.Key -eq 'text' }).Value + if ([System.String]::IsNullOrEmpty($headerText) -eq $false) + { + $ApplyContentMarkingHeaderTextValue = $headerText.Replace('$', '`$') + } + + $ApplyWaterMarkingTextValue = $null + $watermarkText = ($watermark | Where-Object -FilterScript { $_.Key -eq 'text' }).Value + if ([System.String]::IsNullOrEmpty($watermarkText) -eq $false) + { + $ApplyWaterMarkingTextValue = $watermarkText.Replace('$', '`$') + } + + $currentContentType = @() + switch -Regex ($label.ContentType) + { + 'File, Email' { - $parentLabel = Get-Label -Identity $label.ParentId -IncludeDetailedLabelActions -ErrorAction 'SilentlyContinue' - $parentLabelID = $parentLabel.Name + $currentContentType += 'File, Email' } - if ($null -ne $label.LocaleSettings) + 'Site, UnifiedGroup' { - $localeSettingsValue = Convert-JSONToLocaleSettings -JSONLocalSettings $label.LocaleSettings + $currentContentType += 'Site, UnifiedGroup' } - if ($null -ne $label.Settings) + 'PurviewAssets' { - $advancedSettingsValue = Convert-StringToAdvancedSettings -AdvancedSettings $label.Settings + $currentContentType += 'PurviewAssets' } - Write-Verbose "Found existing Sensitivity Label $($Name)" - - [Array]$labelActions = $label.LabelActions - $actions = @() - foreach ($labelAction in $labelActions) + 'Teamwork' { - $action = ConvertFrom-Json ($labelAction | Out-String) - $actions += $action + $currentContentType += 'Teamwork' } - - $encryption = ($actions | Where-Object -FilterScript { $_.Type -eq 'encrypt' }).Settings - $header = ($actions | Where-Object -FilterScript { $_.Type -eq 'applycontentmarking' -and $_.Subtype -eq 'header' }).Settings - $footer = ($actions | Where-Object -FilterScript { $_.Type -eq 'applycontentmarking' -and $_.Subtype -eq 'footer' }).Settings - $watermark = ($actions | Where-Object -FilterScript { $_.Type -eq 'applywatermarking' }).Settings - $protectgroup = ($actions | Where-Object -FilterScript { $_.Type -eq 'protectgroup' }).Settings - $protectsite = ($actions | Where-Object -FilterScript { $_.Type -eq 'protectsite' }).Settings - - $ApplyContentMarkingFooterTextValue = $null - $footerText = ($footer | Where-Object -FilterScript { $_.Key -eq 'text' }).Value - if ([System.String]::IsNullOrEmpty($footerText) -eq $false) + 'SchematizedData' { - $ApplyContentMarkingFooterTextValue = $footerText.Replace('$', '`$') + $currentContentType += 'SchematizedData' } + } - $ApplyContentMarkingHeaderTextValue = $null - $headerText = ($header | Where-Object -FilterScript { $_.Key -eq 'text' }).Value - if ([System.String]::IsNullOrEmpty($headerText) -eq $false) - { - $ApplyContentMarkingHeaderTextValue = $headerText.Replace('$', '`$') - } + # Encryption + $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'disabled' } + if ($null -ne $entry) + { + $encryptionEnabledValue = -not [Boolean]::Parse($entry.Value) + } - $ApplyWaterMarkingTextValue = $null - $watermarkText = ($watermark | Where-Object -FilterScript { $_.Key -eq 'text' }).Value - if ([System.String]::IsNullOrEmpty($watermarkText) -eq $false) - { - $ApplyWaterMarkingTextValue = $watermarkText.Replace('$', '`$') - } + $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'contentexpiredondateindaysornever' } + if ($null -ne $entry) + { + $contentExpiredOnDateValue = $entry.Value + } - $currentContentType = @() - switch -Regex ($label.ContentType) - { - 'File, Email' - { - $currentContentType += 'File, Email' - } - 'Site, UnifiedGroup' - { - $currentContentType += 'Site, UnifiedGroup' - } - 'PurviewAssets' - { - $currentContentType += 'PurviewAssets' - } - 'Teamwork' - { - $currentContentType += 'Teamwork' - } - 'SchematizedData' - { - $currentContentType += 'SchematizedData' - } - } + $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'protectiontype' } + if ($null -ne $entry) + { + $protectionTypeValue = $entry.Value + } - # Encryption - $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'disabled' } - if ($null -ne $entry) - { - $encryptionEnabledValue = -not [Boolean]::Parse($entry.Value) - } + $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'offlineaccessdays' } + if ($null -ne $entry) + { + $offlineAccessDaysValue = $entry.Value + } - $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'contentexpiredondateindaysornever' } - if ($null -ne $entry) - { - $contentExpiredOnDateValue = $entry.Value - } + $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'rightsdefinitions' } + if ($null -ne $entry) + { + $EncryptionRightsDefinitionsValue = Convert-EncryptionRightDefinition -RightsDefinition $entry.Value + } - $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'protectiontype' } - if ($null -ne $entry) - { - $protectionTypeValue = $entry.Value - } + $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'donotforward' } + if ($null -ne $entry) + { + $encryptionDoNotForwardValue = [Boolean]::Parse($entry.Value) + } - $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'offlineaccessdays' } - if ($null -ne $entry) - { - $offlineAccessDaysValue = $entry.Value - } + $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'encryptonly' } + if ($null -ne $entry) + { + $encryptionEncryptOnlyValue = [Boolean]::Parse($entry.Value) + } - $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'rightsdefinitions' } - if ($null -ne $entry) - { - $EncryptionRightsDefinitionsValue = Convert-EncryptionRightDefinition -RightsDefinition $entry.Value - } + $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'promptuser' } + if ($null -ne $entry) + { + $encryptionPromptUserValue = [Boolean]::Parse($entry.Value) + } - $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'donotforward' } - if ($null -ne $entry) - { - $encryptionDoNotForwardValue = [Boolean]::Parse($entry.Value) - } + # Watermark + $entry = $watermark | Where-Object -FilterScript { $_.Key -eq 'disabled' } + if ($null -ne $entry) + { + $watermarkEnabledValue = -not [Boolean]::Parse($entry.Value) + } - $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'encryptonly' } - if ($null -ne $entry) - { - $encryptionEncryptOnlyValue = [Boolean]::Parse($entry.Value) - } + # Watermark Footer + $entry = $footer | Where-Object -FilterScript { $_.Key -eq 'disabled' } + if ($null -ne $entry) + { + $footerEnabledValue = -not [Boolean]::Parse($entry.Value) + } - $entry = $encryption | Where-Object -FilterScript { $_.Key -eq 'promptuser' } - if ($null -ne $entry) - { - $encryptionPromptUserValue = [Boolean]::Parse($entry.Value) - } + # Watermark Header + $entry = $header | Where-Object -FilterScript { $_.Key -eq 'disabled' } + if ($null -ne $entry) + { + $headerEnabledValue = -not [Boolean]::Parse($entry.Value) + } - # Watermark - $entry = $watermark | Where-Object -FilterScript { $_.Key -eq 'disabled' } - if ($null -ne $entry) - { - $watermarkEnabledValue = -not [Boolean]::Parse($entry.Value) - } + # Site and Group + $entry = $protectgroup | Where-Object -FilterScript { $_.Key -eq 'disabled' } + if ($null -ne $entry) + { + $siteAndGroupEnabledValue = -not [Boolean]::Parse($entry.Value) + } - # Watermark Footer - $entry = $footer | Where-Object -FilterScript { $_.Key -eq 'disabled' } - if ($null -ne $entry) - { - $footerEnabledValue = -not [Boolean]::Parse($entry.Value) - } + $entry = $protectgroup | Where-Object -FilterScript { $_.Key -eq 'allowaccesstoguestusers' } + if ($null -ne $entry) + { + $siteAndGroupAccessToGuestUsersValue = [Boolean]::Parse($entry.Value) + } - # Watermark Header - $entry = $header | Where-Object -FilterScript { $_.Key -eq 'disabled' } - if ($null -ne $entry) - { - $headerEnabledValue = -not [Boolean]::Parse($entry.Value) - } + $entry = $protectgroup | Where-Object -FilterScript { $_.Key -eq 'allowemailfromguestusers' } + if ($null -ne $entry) + { + $siteAndGroupAllowEmailFromGuestUsers = [Boolean]::Parse($entry.Value) + } - # Site and Group - $entry = $protectgroup | Where-Object -FilterScript { $_.Key -eq 'disabled' } - if ($null -ne $entry) - { - $siteAndGroupEnabledValue = -not [Boolean]::Parse($entry.Value) - } + $entry = $protectsite | Where-Object -FilterScript { $_.Key -eq 'allowfullaccess' } + if ($null -ne $entry) + { + $siteAndGroupAllowFullAccess = [Boolean]::Parse($entry.Value) + } - $entry = $protectgroup | Where-Object -FilterScript { $_.Key -eq 'allowaccesstoguestusers' } - if ($null -ne $entry) - { - $siteAndGroupAccessToGuestUsersValue = [Boolean]::Parse($entry.Value) - } + $entry = $protectsite | Where-Object -FilterScript { $_.Key -eq 'allowlimitedaccess' } + if ($null -ne $entry) + { + $siteAndGroupAllowLimitedAccess = [Boolean]::Parse($entry.Value) + } - $entry = $protectgroup | Where-Object -FilterScript { $_.Key -eq 'allowemailfromguestusers' } - if ($null -ne $entry) - { - $siteAndGroupAllowEmailFromGuestUsers = [Boolean]::Parse($entry.Value) - } + $entry = $protectsite | Where-Object -FilterScript { $_.Key -eq 'blockaccess' } + if ($null -ne $entry) + { + $siteAndGroupBlockAccess = [Boolean]::Parse($entry.Value) + } - $entry = $protectsite | Where-Object -FilterScript { $_.Key -eq 'allowfullaccess' } - if ($null -ne $entry) - { - $siteAndGroupAllowFullAccess = [Boolean]::Parse($entry.Value) - } + # Auto Labelling Conditions + $getConditions = $null + if ([System.String]::IsNullOrEmpty($label.Conditions) -eq $false) + { + $currConditions = $label.Conditions | ConvertFrom-Json - $entry = $protectsite | Where-Object -FilterScript { $_.Key -eq 'allowlimitedaccess' } - if ($null -ne $entry) - { - $siteAndGroupAllowLimitedAccess = [Boolean]::Parse($entry.Value) + $getConditions = @{ + Groups = @() + Operator = '' } - $entry = $protectsite | Where-Object -FilterScript { $_.Key -eq 'blockaccess' } - if ($null -ne $entry) - { - $siteAndGroupBlockAccess = [Boolean]::Parse($entry.Value) - } + $operator = $currConditions.PSObject.Properties.Name + $getConditions.Operator = $operator - # Auto Labelling Conditions - $getConditions = $null - if ([System.String]::IsNullOrEmpty($label.Conditions) -eq $false) + $autoApplyType = '' + $policyTip = '' + $groups = foreach ($group in $currConditions.$($operator)) { - $currConditions = $label.Conditions | ConvertFrom-Json - - $getConditions = @{ - Groups = @() + $grpObject = @{ + Name = '' Operator = '' } - $operator = $currConditions.PSObject.Properties.Name - $getConditions.Operator = $operator + $grpOperator = $group.PSObject.Properties.Name + $grpObject.Operator = $grpOperator - $autoApplyType = '' - $policyTip = '' - $groups = foreach ($group in $currConditions.$($operator)) + $grpName = '' + [array]$sensitiveInformationTypes = foreach ($item in $group.$grpOperator | Where-Object { $_.Key -eq 'CCSI' }) { - $grpObject = @{ - Name = '' - Operator = '' + if ([String]::IsNullOrEmpty($grpName)) + { + $grpName = ($item.Settings | Where-Object { $_.Key -eq 'groupname' }).Value } - $grpOperator = $group.PSObject.Properties.Name - $grpObject.Operator = $grpOperator - - $grpName = '' - [array]$sensitiveInformationTypes = foreach ($item in $group.$grpOperator | Where-Object { $_.Key -eq 'CCSI' }) + if ([String]::IsNullOrEmpty($policyTip)) { - if ([String]::IsNullOrEmpty($grpName)) - { - $grpName = ($item.Settings | Where-Object { $_.Key -eq 'groupname' }).Value - } - - if ([String]::IsNullOrEmpty($policyTip)) - { - $policyTip = ($item.Settings | Where-Object { $_.Key -eq 'policytip' }).Value - } - - if ([String]::IsNullOrEmpty($autoApplyType)) - { - $autoApplyType = ($item.Settings | Where-Object { $_.Key -eq 'autoapplytype' }).Value - } - - $settingsObject = @{ - name = ($item.Settings | Where-Object { $_.Key -eq 'name' }).Value - confidencelevel = ($item.Settings | Where-Object { $_.Key -eq 'confidencelevel' }).Value - mincount = ($item.Settings | Where-Object { $_.Key -eq 'mincount' }).Value - maxcount = ($item.Settings | Where-Object { $_.Key -eq 'maxcount' }).Value - } - - if ($null -ne ($item.Settings | Where-Object { $_.Key -eq 'classifiertype' })) - { - $settingsObject.classifiertype = ($item.Settings | Where-Object { $_.Key -eq 'classifiertype' }).Value - } - - # return the settings object as output to the sensitiveInformationTypes array - $settingsObject + $policyTip = ($item.Settings | Where-Object { $_.Key -eq 'policytip' }).Value } - [array]$trainableClassifiers = foreach ($item in $group.$grpOperator | Where-Object { $_.Key -eq 'ContentMatchesModule' }) + if ([String]::IsNullOrEmpty($autoApplyType)) { - if ([String]::IsNullOrEmpty($grpName)) - { - $grpName = ($item.Settings | Where-Object { $_.Key -eq 'groupname' }).Value - } - - @{ - name = ($item.Settings | Where-Object { $_.Key -eq 'name' }).Value - id = $item.Value - } + $autoApplyType = ($item.Settings | Where-Object { $_.Key -eq 'autoapplytype' }).Value } - $grpObject.Name = $grpName - $grpObject.SensitiveInformationType = $sensitiveInformationTypes - $grpObject.TrainableClassifier = $trainableClassifiers + $settingsObject = @{ + name = ($item.Settings | Where-Object { $_.Key -eq 'name' }).Value + confidencelevel = ($item.Settings | Where-Object { $_.Key -eq 'confidencelevel' }).Value + mincount = ($item.Settings | Where-Object { $_.Key -eq 'mincount' }).Value + maxcount = ($item.Settings | Where-Object { $_.Key -eq 'maxcount' }).Value + } - # return the group object as output to the groups array - $grpObject - } - $getConditions.Groups = $groups - if ([System.String]::IsNullOrEmpty($policyTip) -eq $false) - { - $getConditions.PolicyTip = $policyTip - } - if ([System.String]::IsNullOrEmpty($autoApplyType) -eq $false) - { - $getConditions.AutoApplyType = $autoApplyType + if ($null -ne ($item.Settings | Where-Object { $_.Key -eq 'classifiertype' })) + { + $settingsObject.classifiertype = ($item.Settings | Where-Object { $_.Key -eq 'classifiertype' }).Value + } + + # return the settings object as output to the sensitiveInformationTypes array + $settingsObject } - else + + [array]$trainableClassifiers = foreach ($item in $group.$grpOperator | Where-Object { $_.Key -eq 'ContentMatchesModule' }) { - $getConditions.AutoApplyType = 'Automatic' + if ([String]::IsNullOrEmpty($grpName)) + { + $grpName = ($item.Settings | Where-Object { $_.Key -eq 'groupname' }).Value + } + + @{ + name = ($item.Settings | Where-Object { $_.Key -eq 'name' }).Value + id = $item.Value + } } - } - $result = @{ - Name = $label.Name - Comment = $label.Comment - ParentId = $parentLabelID - AdvancedSettings = $advancedSettingsValue - DisplayName = $label.DisplayName - LocaleSettings = $localeSettingsValue - Priority = $label.Priority - Tooltip = $label.Tooltip - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - Ensure = 'Present' - ApplyContentMarkingFooterAlignment = ($footer | Where-Object { $_.Key -eq 'alignment' }).Value - ApplyContentMarkingFooterEnabled = $footerEnabledValue - ApplyContentMarkingFooterFontColor = ($footer | Where-Object { $_.Key -eq 'fontcolor' }).Value - ApplyContentMarkingFooterFontSize = ($footer | Where-Object { $_.Key -eq 'fontsize' }).Value - ApplyContentMarkingFooterMargin = ($footer | Where-Object { $_.Key -eq 'margin' }).Value - ApplyContentMarkingFooterText = $ApplyContentMarkingFooterTextValue - ApplyContentMarkingHeaderAlignment = ($header | Where-Object { $_.Key -eq 'alignment' }).Value - ApplyContentMarkingHeaderEnabled = $headerEnabledValue - ApplyContentMarkingHeaderFontColor = ($header | Where-Object { $_.Key -eq 'fontcolor' }).Value - ApplyContentMarkingHeaderFontSize = ($header | Where-Object { $_.Key -eq 'fontsize' }).Value - ApplyContentMarkingHeaderMargin = ($header | Where-Object { $_.Key -eq 'margin' }).Value - #TODO ADD HEADER PLACEMENT? - ApplyContentMarkingHeaderText = $ApplyContentMarkingHeaderTextValue - ApplyWaterMarkingEnabled = $watermarkEnabledValue - ApplyWaterMarkingFontColor = ($watermark | Where-Object { $_.Key -eq 'fontcolor' }).Value - ApplyWaterMarkingFontSize = ($watermark | Where-Object { $_.Key -eq 'fontsize' }).Value - ApplyWaterMarkingLayout = ($watermark | Where-Object { $_.Key -eq 'layout' }).Value - ApplyWaterMarkingText = $ApplyWaterMarkingTextValue - ContentType = $currentContentType - EncryptionContentExpiredOnDateInDaysOrNever = $contentExpiredOnDateValue - EncryptionDoNotForward = $encryptionDoNotForwardValue - EncryptionEncryptOnly = $encryptionEncryptOnlyValue - EncryptionEnabled = $encryptionEnabledValue - EncryptionOfflineAccessDays = $offlineAccessDaysValue - EncryptionPromptUser = $encryptionPromptUserValue - EncryptionProtectionType = $protectionTypeValue - EncryptionRightsDefinitions = $EncryptionRightsDefinitionsValue - EncryptionRightsUrl = ($encryption | Where-Object { $_.Key -eq 'doublekeyencryptionurl' }).Value - SiteAndGroupProtectionAllowAccessToGuestUsers = $siteAndGroupAccessToGuestUsersValue - SiteAndGroupProtectionAllowEmailFromGuestUsers = $siteAndGroupAllowEmailFromGuestUsers - SiteAndGroupProtectionPrivacy = ($protectgroup | Where-Object { $_.Key -eq 'privacy' }).Value - SiteAndGroupProtectionAllowFullAccess = $siteAndGroupAllowFullAccess - SiteAndGroupProtectionAllowLimitedAccess = $siteAndGroupAllowLimitedAccess - SiteAndGroupProtectionBlockAccess = $siteAndGroupBlockAccess - SiteAndGroupProtectionEnabled = $siteAndGroupEnabledValue - SiteAndGroupExternalSharingControlType = ($protectsite | Where-Object { $_.Key -eq 'externalsharingcontroltype' }).Value - AccessTokens = $AccessTokens - AutoLabelingSettings = $getConditions + $grpObject.Name = $grpName + $grpObject.SensitiveInformationType = $sensitiveInformationTypes + $grpObject.TrainableClassifier = $trainableClassifiers + + # return the group object as output to the groups array + $grpObject } + $getConditions.Groups = $groups + if ([System.String]::IsNullOrEmpty($policyTip) -eq $false) + { + $getConditions.PolicyTip = $policyTip + } + if ([System.String]::IsNullOrEmpty($autoApplyType) -eq $false) + { + $getConditions.AutoApplyType = $autoApplyType + } + else + { + $getConditions.AutoApplyType = 'Automatic' + } + } - return $result + $result = @{ + Name = $label.Name + Comment = $label.Comment + ParentId = $parentLabelID + AdvancedSettings = $advancedSettingsValue + DisplayName = $label.DisplayName + LocaleSettings = $localeSettingsValue + Priority = $label.Priority + Tooltip = $label.Tooltip + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + Ensure = 'Present' + ApplyContentMarkingFooterAlignment = ($footer | Where-Object { $_.Key -eq 'alignment' }).Value + ApplyContentMarkingFooterEnabled = $footerEnabledValue + ApplyContentMarkingFooterFontColor = ($footer | Where-Object { $_.Key -eq 'fontcolor' }).Value + ApplyContentMarkingFooterFontSize = ($footer | Where-Object { $_.Key -eq 'fontsize' }).Value + ApplyContentMarkingFooterMargin = ($footer | Where-Object { $_.Key -eq 'margin' }).Value + ApplyContentMarkingFooterText = $ApplyContentMarkingFooterTextValue + ApplyContentMarkingHeaderAlignment = ($header | Where-Object { $_.Key -eq 'alignment' }).Value + ApplyContentMarkingHeaderEnabled = $headerEnabledValue + ApplyContentMarkingHeaderFontColor = ($header | Where-Object { $_.Key -eq 'fontcolor' }).Value + ApplyContentMarkingHeaderFontSize = ($header | Where-Object { $_.Key -eq 'fontsize' }).Value + ApplyContentMarkingHeaderMargin = ($header | Where-Object { $_.Key -eq 'margin' }).Value + #TODO ADD HEADER PLACEMENT? + ApplyContentMarkingHeaderText = $ApplyContentMarkingHeaderTextValue + ApplyWaterMarkingEnabled = $watermarkEnabledValue + ApplyWaterMarkingFontColor = ($watermark | Where-Object { $_.Key -eq 'fontcolor' }).Value + ApplyWaterMarkingFontSize = ($watermark | Where-Object { $_.Key -eq 'fontsize' }).Value + ApplyWaterMarkingLayout = ($watermark | Where-Object { $_.Key -eq 'layout' }).Value + ApplyWaterMarkingText = $ApplyWaterMarkingTextValue + ContentType = $currentContentType + EncryptionContentExpiredOnDateInDaysOrNever = $contentExpiredOnDateValue + EncryptionDoNotForward = $encryptionDoNotForwardValue + EncryptionEncryptOnly = $encryptionEncryptOnlyValue + EncryptionEnabled = $encryptionEnabledValue + EncryptionOfflineAccessDays = $offlineAccessDaysValue + EncryptionPromptUser = $encryptionPromptUserValue + EncryptionProtectionType = $protectionTypeValue + EncryptionRightsDefinitions = $EncryptionRightsDefinitionsValue + EncryptionRightsUrl = ($encryption | Where-Object { $_.Key -eq 'doublekeyencryptionurl' }).Value + SiteAndGroupProtectionAllowAccessToGuestUsers = $siteAndGroupAccessToGuestUsersValue + SiteAndGroupProtectionAllowEmailFromGuestUsers = $siteAndGroupAllowEmailFromGuestUsers + SiteAndGroupProtectionPrivacy = ($protectgroup | Where-Object { $_.Key -eq 'privacy' }).Value + SiteAndGroupProtectionAllowFullAccess = $siteAndGroupAllowFullAccess + SiteAndGroupProtectionAllowLimitedAccess = $siteAndGroupAllowLimitedAccess + SiteAndGroupProtectionBlockAccess = $siteAndGroupBlockAccess + SiteAndGroupProtectionEnabled = $siteAndGroupEnabledValue + SiteAndGroupExternalSharingControlType = ($protectsite | Where-Object { $_.Key -eq 'externalsharingcontroltype' }).Value + AccessTokens = $AccessTokens + AutoLabelingSettings = $getConditions } + + return $result } catch { @@ -1596,6 +1593,7 @@ function Export-TargetResource Write-Host " |---[$i/$($labels.Count)] $($label.Name)" -NoNewline + $Script:exportedInstance = $label $Results = Get-TargetResource @PSBoundParameters -Name $label.Name if ($null -ne $Results.AdvancedSettings) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCSupervisoryReviewPolicy/MSFT_SCSupervisoryReviewPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCSupervisoryReviewPolicy/MSFT_SCSupervisoryReviewPolicy.psm1 index 33c183c554..8811df299b 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCSupervisoryReviewPolicy/MSFT_SCSupervisoryReviewPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCSupervisoryReviewPolicy/MSFT_SCSupervisoryReviewPolicy.psm1 @@ -52,34 +52,31 @@ function Get-TargetResource ) Write-Verbose -Message "Getting configuration of SupervisoryReviewPolicy for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + if (-not $Global:CurrentModeIsExport) { $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` -InboundParameters $PSBoundParameters - } - - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies - - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + } $nullReturn = $PSBoundParameters $nullReturn.Ensure = 'Absent' try { + <# + Note: 'exportedInstance(s)' approach does not work for this resource; + command does not return Reviewers unless the policy name is specified + #> $PolicyObject = Get-SupervisoryReviewPolicyV2 $Name -ErrorAction SilentlyContinue if ($null -eq $PolicyObject) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SCSupervisoryReviewRule/MSFT_SCSupervisoryReviewRule.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SCSupervisoryReviewRule/MSFT_SCSupervisoryReviewRule.psm1 index d5c4a93186..ad755078a8 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SCSupervisoryReviewRule/MSFT_SCSupervisoryReviewRule.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SCSupervisoryReviewRule/MSFT_SCSupervisoryReviewRule.psm1 @@ -56,66 +56,64 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration of SupervisoryReviewRule for $Name" - if ($Global:CurrentModeIsExport) - { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters ` - -SkipModuleReload $true - } - else + try { - $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` - -InboundParameters $PSBoundParameters - } + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration of SupervisoryReviewRule for $Name" - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + $ConnectionMode = New-M365DSCConnection -Workload 'SecurityComplianceCenter' ` + -InboundParameters $PSBoundParameters - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' - try - { - $RuleObject = Get-SupervisoryReviewRule -Identity $Name -ErrorAction SilentlyContinue + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - if ($null -eq $RuleObject) - { - Write-Verbose -Message "SupervisoryReviewRule $($Name) does not exist." - return $nullReturn + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' + + $RuleObject = Get-SupervisoryReviewRule -Identity $Name -ErrorAction SilentlyContinue + + if ($null -eq $RuleObject) + { + Write-Verbose -Message "SupervisoryReviewRule $($Name) does not exist." + return $nullReturn + } } else { - Write-Verbose "Found existing SupervisoryReviewRule $($Name)" - $PolicyName = (Get-SupervisoryReviewPolicyV2 -Identity $RuleObject.Policy).Name - - $result = @{ - Name = $RuleObject.Name - Policy = $PolicyName - Condition = $RuleObject.Condition - SamplingRate = $RuleObject.SamplingRate - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - CertificateThumbprint = $CertificateThumbprint - CertificatePath = $CertificatePath - CertificatePassword = $CertificatePassword - AccessTokens = $AccessTokens - } + $RuleObject = $Script:exportedInstance + } - Write-Verbose -Message "Found SupervisoryReviewRule $($Name)" - Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" - return $result + Write-Verbose "Found existing SupervisoryReviewRule $($Name)" + $PolicyName = (Get-SupervisoryReviewPolicyV2 -Identity $RuleObject.Policy).Name + + $result = @{ + Name = $RuleObject.Name + Policy = $PolicyName + Condition = $RuleObject.Condition + SamplingRate = $RuleObject.SamplingRate + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + CertificatePath = $CertificatePath + CertificatePassword = $CertificatePassword + AccessTokens = $AccessTokens } + + Write-Verbose -Message "Found SupervisoryReviewRule $($Name)" + Write-Verbose -Message "Get-TargetResource Result: `n $(Convert-M365DscHashtableToString -Hashtable $result)" + return $result } catch { @@ -393,6 +391,7 @@ function Export-TargetResource } Write-Host " |---[$i/$($rules.Length)] $($rule.Name)" -NoNewline + $Script:exportedInstance = $rule $Results = Get-TargetResource @PSBoundParameters ` -Name $rule.Name ` -Policy $rule.Policy diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SPOHubSite/MSFT_SPOHubSite.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SPOHubSite/MSFT_SPOHubSite.psm1 index 2a705aedbf..9ac76e9940 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SPOHubSite/MSFT_SPOHubSite.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SPOHubSite/MSFT_SPOHubSite.psm1 @@ -74,101 +74,106 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration for hub site collection $Url" + try + { + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration for hub site collection $Url" - $ConnectionModeGraph = New-M365DSCConnection -Workload 'MicrosoftGraph' ` - -InboundParameters $PSBoundParameters + $ConnectionModeGraph = New-M365DSCConnection -Workload 'MicrosoftGraph' ` + -InboundParameters $PSBoundParameters - $ConnectionMode = New-M365DSCConnection -Workload 'PnP' ` - -InboundParameters $PSBoundParameters + $ConnectionMode = New-M365DSCConnection -Workload 'PnP' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - Write-Verbose -Message "Getting hub site collection $Url" - $site = Get-PnPTenantSite -Identity $Url -ErrorAction SilentlyContinue - if ($null -eq $site) - { - Write-Verbose -Message "The specified Site Collection doesn't already exist." - return $nullReturn - } + Write-Verbose -Message "Getting hub site collection $Url" + $site = Get-PnPTenantSite -Identity $Url -ErrorAction SilentlyContinue + if ($null -eq $site) + { + Write-Verbose -Message "The specified Site Collection doesn't already exist." + return $nullReturn + } - if ($site.IsHubSite -eq $false) - { - Write-Verbose -Message "The specified Site Collection isn't a hub site." - return $nullReturn + if ($site.IsHubSite -eq $false) + { + Write-Verbose -Message "The specified Site Collection isn't a hub site." + return $nullReturn + } } else { - $hubSite = Get-PnPHubSite -Identity $Url - $principals = @() - foreach ($permission in $hubSite.Permissions.PrincipalName) + $hubSite = $Script:exportedInstance + } + + $hubSite = Get-PnPHubSite -Identity $Url + $principals = @() + foreach ($permission in $hubSite.Permissions.PrincipalName) + { + $result = $permission.Split('|') + if ($result[0].StartsWith('c') -eq $true) { - $result = $permission.Split('|') - if ($result[0].StartsWith('c') -eq $true) - { - # Group permissions - $group = Get-MgGroup -GroupId $result[2] + # Group permissions + $group = Get-MgGroup -GroupId $result[2] - if ($null -eq $group.EmailAddress) - { - $principal = $group.DisplayName - } - else - { - $principal = $group.EmailAddress - } - $principals += $principal + if ($null -eq $group.EmailAddress) + { + $principal = $group.DisplayName } else { - # User permissions - $principals += $result[2] + $principal = $group.EmailAddress } - } - - if ($LogoUrl.StartsWith('http')) - { - $configuredLogo = $hubSite.LogoUrl + $principals += $principal } else { - $configuredLogo = ([System.Uri]$hubSite.LogoUrl).AbsolutePath + # User permissions + $principals += $result[2] } + } - $result = @{ - Url = $Url - Title = $hubSite.Title - Description = $hubSite.Description - LogoUrl = $configuredLogo - RequiresJoinApproval = $hubSite.RequiresJoinApproval - AllowedToJoin = $principals - SiteDesignId = $hubSite.SiteDesignId - Ensure = 'Present' - Credential = $Credential - ApplicationId = $ApplicationId - TenantId = $TenantId - ApplicationSecret = $ApplicationSecret - CertificateThumbprint = $CertificateThumbprint - Managedidentity = $ManagedIdentity.IsPresent - AccessTokens = $AccessTokens - } - return $result + if ($LogoUrl.StartsWith('http')) + { + $configuredLogo = $hubSite.LogoUrl + } + else + { + $configuredLogo = ([System.Uri]$hubSite.LogoUrl).AbsolutePath + } + + $result = @{ + Url = $Url + Title = $hubSite.Title + Description = $hubSite.Description + LogoUrl = $configuredLogo + RequiresJoinApproval = $hubSite.RequiresJoinApproval + AllowedToJoin = $principals + SiteDesignId = $hubSite.SiteDesignId + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + ApplicationSecret = $ApplicationSecret + CertificateThumbprint = $CertificateThumbprint + Managedidentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens } + return $result } catch { @@ -680,6 +685,7 @@ function Export-TargetResource AccessTokens = $AccessTokens } + $Script:exportedInstance = $hub $Results = Get-TargetResource @Params $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SPOSite/MSFT_SPOSite.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SPOSite/MSFT_SPOSite.psm1 index 9c398a741b..0e036b3634 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SPOSite/MSFT_SPOSite.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SPOSite/MSFT_SPOSite.psm1 @@ -157,35 +157,42 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting configuration for site collection $Url" + try + { + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting configuration for site collection $Url" - $ConnectionMode = New-M365DSCConnection -Workload 'PnP' ` - -InboundParameters $PSBoundParameters + $ConnectionMode = New-M365DSCConnection -Workload 'PnP' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - Write-Verbose -Message "Getting site collection $Url" + Write-Verbose -Message "Getting site collection $Url" - $site = Get-PnPTenantSite -Identity $Url -ErrorAction 'SilentlyContinue' - if ($null -eq $site) + $site = Get-PnPTenantSite -Identity $Url -ErrorAction 'SilentlyContinue' + if ($null -eq $site) + { + Write-Verbose -Message "The specified Site Collection {$Url} doesn't exist." + return $nullReturn + } + } + else { - Write-Verbose -Message "The specified Site Collection {$Url} doesn't exist." - return $nullReturn + $site = $Script:exportedInstance } $web = Get-PnPWeb -Includes RegionalSettings.TimeZone @@ -974,6 +981,7 @@ function Export-TargetResource try { + $Script:exportedInstance = $site $Results = Get-TargetResource @Params if ([System.String]::IsNullOrEmpty($Results.SharingDomainRestrictionMode)) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_SPOSiteGroup/MSFT_SPOSiteGroup.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_SPOSiteGroup/MSFT_SPOSiteGroup.psm1 index f1822fa249..9d3ff9c03f 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_SPOSiteGroup/MSFT_SPOSiteGroup.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_SPOSiteGroup/MSFT_SPOSiteGroup.psm1 @@ -61,61 +61,68 @@ function Get-TargetResource $AccessTokens ) - Write-Verbose -Message "Getting SPOSiteGroups for {$Url}" + try + { + if (-not $Script:exportedInstance) + { + Write-Verbose -Message "Getting SPOSiteGroups for {$Url}" - $ConnectionMode = New-M365DSCConnection -Workload 'PNP' ` - -InboundParameters $PSBoundParameters + $ConnectionMode = New-M365DSCConnection -Workload 'PNP' ` + -InboundParameters $PSBoundParameters - #Ensure the proper dependencies are installed in the current environment. - Confirm-M365DSCDependencies + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies - #region Telemetry - $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' - $CommandName = $MyInvocation.MyCommand - $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` - -CommandName $CommandName ` - -Parameters $PSBoundParameters - Add-M365DSCTelemetryEvent -Data $data - #endregion + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName -replace 'MSFT_', '' + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion - $nullReturn = $PSBoundParameters - $nullReturn.Ensure = 'Absent' + $nullReturn = $PSBoundParameters + $nullReturn.Ensure = 'Absent' - try - { - #checking if the site actually exists - try - { - $site = Get-PnPTenantSite $Url - } - catch - { - $Message = "The specified site collection doesn't exist." - New-M365DSCLogEntry -Message $Message ` - -Exception $_ ` - -Source $MyInvocation.MyCommand.ModuleName - throw $Message - return $nullReturn - } - try - { - $ConnectionMode = New-M365DSCConnection -Workload 'PNP' ` - -InboundParameters $PSBoundParameters ` - -Url $Url - $siteGroup = Get-PnPGroup -Identity $Identity ` - -ErrorAction Stop - } - catch - { - if ($Error[0].Exception.Message -eq 'Group cannot be found.') + #checking if the site actually exists + try + { + $site = Get-PnPTenantSite $Url + } + catch + { + $Message = "The specified site collection doesn't exist." + New-M365DSCLogEntry -Message $Message ` + -Exception $_ ` + -Source $MyInvocation.MyCommand.ModuleName + throw $Message + return $nullReturn + } + try { - Write-Verbose -Message "Site group $($Identity) could not be found on site $($Url)" + $ConnectionMode = New-M365DSCConnection -Workload 'PNP' ` + -InboundParameters $PSBoundParameters ` + -Url $Url + $siteGroup = Get-PnPGroup -Identity $Identity ` + -ErrorAction Stop + } + catch + { + if ($Error[0].Exception.Message -eq 'Group cannot be found.') + { + Write-Verbose -Message "Site group $($Identity) could not be found on site $($Url)" + } + } + if ($null -eq $siteGroup) + { + return $nullReturn } } - if ($null -eq $siteGroup) + else { - return $nullReturn + $siteGroup = $Script:exportedInstance } try @@ -548,15 +555,6 @@ function Export-TargetResource foreach ($siteGroup in $siteGroups) { Write-Host " |---[$j/$($siteGroups.Length)] $($siteGroup.Title)" -NoNewline - try - { - [array]$sitePerm = Get-PnPGroupPermissions -Identity $siteGroup.Title -ErrorAction Stop - } - catch - { - Write-Warning -Message "The specified account does not have access to the permissions list for {$($siteGroup.Title)}" - break - } $Params = @{ Url = $site.Url Identity = $siteGroup.Title @@ -572,6 +570,7 @@ function Export-TargetResource } try { + $Script:exportedInstance = $siteGroup $Results = Get-TargetResource @Params if ($Results.Ensure -eq 'Present') { diff --git a/Tests/Unit/Microsoft365DSC/Microsoft365DSC.EXOGlobalAddressList.Tests.ps1 b/Tests/Unit/Microsoft365DSC/Microsoft365DSC.EXOGlobalAddressList.Tests.ps1 index b6391269c9..5249126b83 100644 --- a/Tests/Unit/Microsoft365DSC/Microsoft365DSC.EXOGlobalAddressList.Tests.ps1 +++ b/Tests/Unit/Microsoft365DSC/Microsoft365DSC.EXOGlobalAddressList.Tests.ps1 @@ -58,13 +58,20 @@ Describe -Name $Global:DscHelper.DescribeHeader -Fixture { } Mock -CommandName Get-GlobalAddressList -MockWith { - return @{ + param($Identity) + $return = @{ Name = 'Contoso Different GAL' ConditionalCompany = 'Contoso' ConditionalDepartment = 'Finance' ConditionalStateOrProvince = 'DE' IncludedRecipients = 'AllRecipients' } + if ($Identity -eq $return.Name) { + return $return + } + else { + return $null + } } Mock -CommandName Set-GlobalAddressList -MockWith { diff --git a/Tests/Unit/Stubs/Generic.psm1 b/Tests/Unit/Stubs/Generic.psm1 index 7d18926ab1..24744131f2 100644 --- a/Tests/Unit/Stubs/Generic.psm1 +++ b/Tests/Unit/Stubs/Generic.psm1 @@ -207,6 +207,68 @@ function New-MGServicePrincipal ) } +function Get-MgServicePrincipalOwner +{ + [CmdletBinding()] + param( + [Parameter()] + [String] + $ServicePrincipalId, + + [Parameter()] + [String[]] + $ExpandProperty, + + [Parameter()] + [String] + $Filter, + + [Parameter()] + [String[]] + $Property, + + [Parameter()] + [String] + $Search, + + [Parameter()] + [Int32] + $Skip, + + [Parameter()] + [String[]] + $Sort, + + [Parameter()] + [Int32] + $Top, + + [Parameter()] + [String] + $ConsistencyLevel, + + [Parameter()] + [String] + $ResponseHeadersVariable, + + [Parameter()] + [hashtable] + $Headers, + + [Parameter()] + [Int32] + $PageSize, + + [Parameter()] + [switch] + $All, + + [Parameter()] + [String] + $CountVariable + ) +} + function New-MgBetaRoleManagementDirectoryRoleDefinition { [CmdletBinding()] @@ -737,7 +799,9 @@ function Get-GlobalAddressList [OutputType([System.Collections.Hashtable])] param ( - + [Parameter()] + [System.String] + $Identity ) } diff --git a/Tests/Unit/Stubs/Microsoft365.psm1 b/Tests/Unit/Stubs/Microsoft365.psm1 index fae2f3e556..fd4e223e19 100644 --- a/Tests/Unit/Stubs/Microsoft365.psm1 +++ b/Tests/Unit/Stubs/Microsoft365.psm1 @@ -50200,6 +50200,75 @@ function Get-MgUserLicenseDetail $HttpPipelineAppend ) } +function Get-MgUserMemberOfAsGroup +{ + [CmdletBinding()] + param( + [Parameter()] + [String] + $UserId, + + [Parameter()] + [String] + $DirectoryObjectId, + + [Parameter()] + [Object] + $InputObject, + + [Parameter()] + [String[]] + $ExpandProperty, + + [Parameter()] + [String[]] + $Property, + + [Parameter()] + [String] + $Filter, + + [Parameter()] + [String] + $Search, + + [Parameter()] + [Int32] + $Skip, + + [Parameter()] + [String[]] + $Sort, + + [Parameter()] + [Int32] + $Top, + + [Parameter()] + [String] + $ConsistencyLevel, + + [Parameter()] + [String] + $ResponseHeadersVariable, + + [Parameter()] + [hashtable] + $Headers, + + [Parameter()] + [Int32] + $PageSize, + + [Parameter()] + [switch] + $All, + + [Parameter()] + [String] + $CountVariable + ) +} function New-MgUser { [CmdletBinding()] @@ -105845,3 +105914,170 @@ function Update-MgPolicyRoleManagementPolicyRule } #endregion +#region Microsoft.Graph.Sites +function Get-MgAdminSharepointSetting +{ + [CmdletBinding()] + param + ( + [Parameter()] + [String[]] + $ExpandProperty, + + [Parameter()] + [String[]] + $Property, + + [Parameter()] + [String] + $ResponseHeadersVariable, + + [Parameter()] + [hashtable] + $Headers + ) +} +function Update-MgAdminSharepointSetting +{ + [CmdletBinding()] + param + ( + [Parameter()] + [Object] + $BodyParameter, + + [Parameter()] + [String] + $ResponseHeadersVariable, + + [Parameter()] + [Hashtable] + $AdditionalProperties, + + [Parameter()] + [String[]] + $AllowedDomainGuidsForSyncApp, + + [Parameter()] + [String[]] + $AvailableManagedPathsForSiteCreation, + + [Parameter()] + [Int32] + $DeletedUserPersonalSiteRetentionPeriodInDays, + + [Parameter()] + [String[]] + $ExcludedFileExtensionsForSyncApp, + + [Parameter()] + [String] + $Id, + + [Parameter()] + [Object] + $IdleSessionSignOut, + + [Parameter()] + [String] + $ImageTaggingOption, + + [Parameter()] + [switch] + $IsCommentingOnSitePagesEnabled, + + [Parameter()] + [switch] + $IsFileActivityNotificationEnabled, + + [Parameter()] + [switch] + $IsLegacyAuthProtocolsEnabled, + + [Parameter()] + [switch] + $IsLoopEnabled, + + [Parameter()] + [switch] + $IsMacSyncAppEnabled, + + [Parameter()] + [switch] + $IsRequireAcceptingUserToMatchInvitedUserEnabled, + + [Parameter()] + [switch] + $IsResharingByExternalUsersEnabled, + + [Parameter()] + [switch] + $IsSharePointMobileNotificationEnabled, + + [Parameter()] + [switch] + $IsSharePointNewsfeedEnabled, + + [Parameter()] + [switch] + $IsSiteCreationEnabled, + + [Parameter()] + [switch] + $IsSiteCreationUiEnabled, + + [Parameter()] + [switch] + $IsSitePagesCreationEnabled, + + [Parameter()] + [switch] + $IsSitesStorageLimitAutomatic, + + [Parameter()] + [switch] + $IsSyncButtonHiddenOnPersonalSite, + + [Parameter()] + [switch] + $IsUnmanagedSyncAppForTenantRestricted, + + [Parameter()] + [Int64] + $PersonalSiteDefaultStorageLimitInMb, + + [Parameter()] + [String[]] + $SharingAllowedDomainList, + + [Parameter()] + [String[]] + $SharingBlockedDomainList, + + [Parameter()] + [String] + $SharingCapability, + + [Parameter()] + [String] + $SharingDomainRestrictionMode, + + [Parameter()] + [String] + $SiteCreationDefaultManagedPath, + + [Parameter()] + [Int32] + $SiteCreationDefaultStorageLimitInMb, + + [Parameter()] + [String] + $TenantDefaultTimezone, + + [Parameter()] + [hashtable] + $Headers + ) +} + +#endregion