diff --git a/Modules/CIPPCore/CIPPCore.psm1 b/Modules/CIPPCore/CIPPCore.psm1 index f69a353414d9..12f13762d19c 100644 --- a/Modules/CIPPCore/CIPPCore.psm1 +++ b/Modules/CIPPCore/CIPPCore.psm1 @@ -4,8 +4,7 @@ $Functions = $Public + $Private foreach ($import in @($Functions)) { try { . $import.FullName - } - catch { + } catch { Write-Error -Message "Failed to import function $($import.FullName): $_" } } diff --git a/Modules/CIPPCore/Public/Add-CIPPApplicationPermission.ps1 b/Modules/CIPPCore/Public/Add-CIPPApplicationPermission.ps1 index 5ec28d3c2e7a..f41f2729a5c8 100644 --- a/Modules/CIPPCore/Public/Add-CIPPApplicationPermission.ps1 +++ b/Modules/CIPPCore/Public/Add-CIPPApplicationPermission.ps1 @@ -41,10 +41,11 @@ function Add-CIPPApplicationPermission { $counter = 0 foreach ($Grant in $Grants) { try { - $SettingsRequest = New-GraphPOSTRequest -body ($Grant | ConvertTo-Json) -uri "https://graph.microsoft.com/beta/servicePrincipals/$($ourSVCPrincipal.id)/appRoleAssignedTo" -tenantid $Tenantfilter -type POST -NoAuthCheck $true + $SettingsRequest = New-GraphPOSTRequest -body (ConvertTo-Json -InputObject $Grant -Depth 5) -uri "https://graph.microsoft.com/beta/servicePrincipals/$($ourSVCPrincipal.id)/appRoleAssignedTo" -tenantid $Tenantfilter -type POST -NoAuthCheck $true $counter++ } catch { - $Results.add("Failed to grant $($Grant.appRoleId) to $($Grant.resourceId): $($_.Exception.Message)") | Out-Null + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + $Results.add("Failed to grant $($Grant.appRoleId) to $($Grant.resourceId): $ErrorMessage") | Out-Null } } "Added $counter Application permissions to $($ourSVCPrincipal.displayName)" diff --git a/Modules/CIPPCore/Public/Add-CIPPAzDataTableEntity.ps1 b/Modules/CIPPCore/Public/Add-CIPPAzDataTableEntity.ps1 index 6e2e0dd618d5..38c7e2c8c1f6 100644 --- a/Modules/CIPPCore/Public/Add-CIPPAzDataTableEntity.ps1 +++ b/Modules/CIPPCore/Public/Add-CIPPAzDataTableEntity.ps1 @@ -134,7 +134,8 @@ function Add-CIPPAzDataTableEntity { } } catch { - throw "Error processing entity: $($_.Exception.Message) Linenumner: $($_.InvocationInfo.ScriptLineNumber)" + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + throw "Error processing entity: $ErrorMessage Linenumber: $($_.InvocationInfo.ScriptLineNumber)" } } else { Write-Information "THE ERROR IS $($_.Exception.ErrorCode). The size of the entity is $entitySize." diff --git a/Modules/CIPPCore/Public/Add-CIPPBPAField.ps1 b/Modules/CIPPCore/Public/Add-CIPPBPAField.ps1 index 1cc394c9fbf5..bed52e8cc786 100644 --- a/Modules/CIPPCore/Public/Add-CIPPBPAField.ps1 +++ b/Modules/CIPPCore/Public/Add-CIPPBPAField.ps1 @@ -30,7 +30,7 @@ function Add-CIPPBPAField { $Result["$fieldName"] = [bool]$FieldValue } 'JSON' { - if ($FieldValue -eq $null) { $JsonString = '{}' } else { $JsonString = (ConvertTo-Json -Depth 15 -InputObject $FieldValue -Compress) } + if ($null -eq $FieldValue) { $JsonString = '{}' } else { $JsonString = (ConvertTo-Json -Depth 15 -InputObject $FieldValue -Compress) } $Result[$fieldName] = [string]$JsonString } 'string' { @@ -38,4 +38,4 @@ function Add-CIPPBPAField { } } Add-CIPPAzDataTableEntity @Table -Entity $Result -Force -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1 b/Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1 index fdad4ca88b95..4b08eda522bb 100644 --- a/Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1 +++ b/Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1 @@ -72,7 +72,8 @@ function Add-CIPPScheduledTask { try { Add-CIPPAzDataTableEntity @Table -Entity $entity -Force } catch { - return "Could not add task: $($_.Exception.Message)" + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + return "Could not add task: $ErrorMessage" } return "Successfully added task: $($entity.Name)" } diff --git a/Modules/CIPPCore/Public/AdditionalPermissions.json b/Modules/CIPPCore/Public/AdditionalPermissions.json index 4983c6f5fd03..815fe9e59248 100644 --- a/Modules/CIPPCore/Public/AdditionalPermissions.json +++ b/Modules/CIPPCore/Public/AdditionalPermissions.json @@ -2,14 +2,5 @@ { "resourceAppId": "00000003-0000-0ff1-ce00-000000000000", "resourceAccess": [{ "id": "AllProfiles.Manage", "type": "Scope" }] - }, - { - "resourceAppId": "fb78d390-0c51-40cd-8e17-fdbfab77341b", - "resourceAccess": [ - { "id": "AdminApi.AccessAsUser.All", "type": "Scope" }, - { "id": "FfoPowerShell.AccessAsUser.All", "type": "Scope" }, - { "id": "RemotePowerShell.AccessAsUser.All", "type": "Scope" }, - { "id": "VivaFeatureAccessPolicy.Manage.All", "type": "Scope" } - ] } ] diff --git a/Modules/CIPPCore/Public/Assert-CippVersion.ps1 b/Modules/CIPPCore/Public/Assert-CippVersion.ps1 index 83f77f43edd0..621c1f6d4cac 100644 --- a/Modules/CIPPCore/Public/Assert-CippVersion.ps1 +++ b/Modules/CIPPCore/Public/Assert-CippVersion.ps1 @@ -24,4 +24,4 @@ function Assert-CippVersion { OutOfDateCIPP = ([version]$RemoteCIPPVersion -gt [version]$CIPPVersion) OutOfDateCIPPAPI = ([version]$RemoteAPIVersion -gt [version]$APIVersion) } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Clear-CippDurables.ps1 b/Modules/CIPPCore/Public/Clear-CippDurables.ps1 index eb1949a39078..089ca10282a7 100644 --- a/Modules/CIPPCore/Public/Clear-CippDurables.ps1 +++ b/Modules/CIPPCore/Public/Clear-CippDurables.ps1 @@ -59,4 +59,4 @@ function Clear-CippDurables { } $null = Get-CippTable -TableName ('{0}History' -f $FunctionName) Write-Information 'Durable Orchestrators and Queues have been cleared' -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecSetCIPPAutoBackup.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecSetCIPPAutoBackup.ps1 index 2d04df48933c..b705c1da9fc5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecSetCIPPAutoBackup.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Core/Invoke-ExecSetCIPPAutoBackup.ps1 @@ -19,14 +19,14 @@ Function Invoke-ExecSetCIPPAutoBackup { } Remove-AzDataTableEntity @Table -Entity $task | Out-Null - $TaskBody = @{ + $TaskBody = [pscustomobject]@{ TenantFilter = 'AllTenants' Name = 'Automated CIPP Backup' Command = @{ value = 'New-CIPPBackup' label = 'New-CIPPBackup' } - Parameters = @{ backupType = 'CIPP' } + Parameters = [pscustomobject]@{ backupType = 'CIPP' } ScheduledTime = $unixtime Recurrence = '1d' } diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-AddScheduledItem.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-AddScheduledItem.ps1 index f5885143a196..86a74a58a459 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-AddScheduledItem.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-AddScheduledItem.ps1 @@ -9,7 +9,7 @@ Function Invoke-AddScheduledItem { #> [CmdletBinding()] param($Request, $TriggerMetadata) - if ($Request.query.hidden -eq $null) { + if ($null -eq $Request.query.hidden) { $hidden = $false } else { $hidden = $true diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-RemoveScheduledItem.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-RemoveScheduledItem.ps1 index f21b1b88e275..2da498adaf36 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-RemoveScheduledItem.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Scheduler/Invoke-RemoveScheduledItem.ps1 @@ -10,6 +10,9 @@ Function Invoke-RemoveScheduledItem { [CmdletBinding()] param($Request, $TriggerMetadata) + $APIName = 'RemoveScheduledItem' + $User = $request.headers.'x-ms-client-principal' + $task = @{ RowKey = $Request.Query.ID PartitionKey = 'ScheduledTask' @@ -17,7 +20,7 @@ Function Invoke-RemoveScheduledItem { $Table = Get-CIPPTable -TableName 'ScheduledTasks' Remove-AzDataTableEntity @Table -Entity $task - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Task removed: $($task.Name)" -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Task removed: $($task.RowKey)" -Sev 'Info' Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAccessChecks.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAccessChecks.ps1 index f655b21c2a91..88a663ad990b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAccessChecks.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Settings/Invoke-ExecAccessChecks.ps1 @@ -21,7 +21,7 @@ Function Invoke-ExecAccessChecks { } if ($Request.Query.Tenants -eq 'true') { - $Results = Test-CIPPAccessTenant -TenantCSV $Request.Body.tenantid + $Results = Test-CIPPAccessTenant -TenantCSV $Request.Body.tenantid -ExecutingUser $Request.Headers.'x-ms-client-principal' } if ($Request.Query.GDAP -eq 'true') { $Results = Test-CIPPGDAPRelationships diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecJITAdmin.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecJITAdmin.ps1 index 6ec43458e29c..86558c5daa54 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecJITAdmin.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecJITAdmin.ps1 @@ -171,14 +171,14 @@ Function Invoke-ExecJITAdmin { Set-CIPPUserJITAdmin @Parameters } - $DisableTaskBody = @{ + $DisableTaskBody = [pscustomobject]@{ TenantFilter = $Request.Body.TenantFilter Name = "JIT Admin ($($Request.Body.ExpireAction)): $Username" Command = @{ value = 'Set-CIPPUserJITAdmin' label = 'Set-CIPPUserJITAdmin' } - Parameters = @{ + Parameters = [pscustomobject]@{ TenantFilter = $Request.Body.TenantFilter User = @{ 'UserPrincipalName' = $Username diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboardUser.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboardUser.ps1 index 0bf9feaf3dff..81707b1b22ef 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboardUser.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Identity/Administration/Users/Invoke-ExecOffboardUser.ps1 @@ -23,7 +23,7 @@ Function Invoke-ExecOffboardUser { Command = @{ value = 'Invoke-CIPPOffboardingJob' } - Parameters = @{ + Parameters = [pscustomobject]@{ Username = $Username APIName = 'Scheduled Offboarding' options = $request.body diff --git a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCAExclusion.ps1 b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCAExclusion.ps1 index 86d06bf95796..0ee8ffc437db 100644 --- a/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCAExclusion.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/HTTP Functions/Tenant/Conditional/Invoke-ExecCAExclusion.ps1 @@ -18,14 +18,14 @@ Function Invoke-ExecCAExclusion { } if ($Request.body.vacation -eq 'true') { $StartDate = $Request.body.StartDate - $TaskBody = @{ + $TaskBody = [pscustomobject]@{ TenantFilter = $Request.body.TenantFilter Name = "Add CA Exclusion Vacation Mode: $Username - $($Request.body.TenantFilter)" Command = @{ value = 'Set-CIPPCAExclusion' label = 'Set-CIPPCAExclusion' } - Parameters = @{ + Parameters = [pscustomobject]@{ ExclusionType = 'Add' UserID = $Request.body.UserID PolicyId = $Request.body.PolicyId diff --git a/Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1 b/Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1 index a80a5d3b002e..a72d598639a2 100644 --- a/Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1 @@ -14,9 +14,8 @@ function Get-CIPPBitlockerKey { } return $GraphRequest } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid)" -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) - return "Could not add out of office message for $($userid). Error: $($_.Exception.Message)" + return "Could not add out of office message for $($userid). Error: $ErrorMessage" } } - - diff --git a/Modules/CIPPCore/Public/Get-CIPPDomainAnalyser.ps1 b/Modules/CIPPCore/Public/Get-CIPPDomainAnalyser.ps1 index 0bc50c4acaad..1d3ba51f1dd8 100644 --- a/Modules/CIPPCore/Public/Get-CIPPDomainAnalyser.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPDomainAnalyser.ps1 @@ -36,4 +36,4 @@ function Get-CIPPDomainAnalyser { $Results = @() } return $Results -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1 b/Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1 index 06d74edae438..011ab9f4552a 100644 --- a/Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1 @@ -4,7 +4,7 @@ function Get-CIPPLapsPassword { param ( $device, $TenantFilter, - $APIName = "Get LAPS Password", + $APIName = 'Get LAPS Password', $ExecutingUser ) @@ -15,10 +15,10 @@ function Get-CIPPLapsPassword { "The password for $($_.AccountName) is $($PlainText) generated at $($date)" } if ($GraphRequest) { return $GraphRequest } else { return "No LAPS password found for $device" } - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid)" -Sev "Error" -tenant $TenantFilter - return "Could not add out of office message for $($userid). Error: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not add out of office message for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1 b/Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1 index 9668cd51b50e..84bab8d378cb 100644 --- a/Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1 @@ -7,7 +7,7 @@ function Get-CIPPLicenseOverview { $ExecutingUser ) - + $LicRequest = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/subscribedSkus' -tenantid $TenantFilter $SkuIDs = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/directory/subscriptions' -tenantid $TenantFilter @@ -25,7 +25,7 @@ function Get-CIPPLicenseOverview { if ($sku.skuId -in $ExcludedSkuList.GUID) { continue } $PrettyName = ($ConvertTable | Where-Object { $_.guid -eq $sku.skuid }).'Product_Display_Name' | Select-Object -Last 1 if (!$PrettyName) { $PrettyName = $sku.skuPartNumber } - + # Initialize $Term with the default value $TermInfo = foreach ($Subscription in $sku.subscriptionIds) { $SubInfo = $SkuIDs | Where-Object { $_.id -eq $Subscription } @@ -63,7 +63,7 @@ function Get-CIPPLicenseOverview { TermInfo = [string]($TermInfo | ConvertTo-Json -Depth 10 -Compress) 'PartitionKey' = 'License' 'RowKey' = "$($singlereq.Tenant) - $($sku.skuid)" - } + } } } return $GraphRequest diff --git a/Modules/CIPPCore/Public/Get-CIPPMFAState.ps1 b/Modules/CIPPCore/Public/Get-CIPPMFAState.ps1 index 28d526a9944d..0a6b0a4b3fba 100644 --- a/Modules/CIPPCore/Public/Get-CIPPMFAState.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPMFAState.ps1 @@ -47,7 +47,7 @@ function Get-CIPPMFAState { $Policy.conditions.users.excludeUsers.foreach({ $ExcludeAllUsers.Add($_) | Out-Null }) continue } - } + } } } catch { } @@ -76,7 +76,7 @@ function Get-CIPPMFAState { $PerUser = if ($PerUserMFAState -eq $null) { $null } else { ($PerUserMFAState | Where-Object -Property UserPrincipalName -EQ $_.UserPrincipalName).PerUserMFAState } $MFARegUser = if (($MFARegistration | Where-Object -Property UserPrincipalName -EQ $_.UserPrincipalName).IsMFARegistered -eq $null) { $false } else { ($MFARegistration | Where-Object -Property UserPrincipalName -EQ $_.UserPrincipalName) } - + [PSCustomObject]@{ Tenant = $TenantFilter ID = $_.ObjectId @@ -92,7 +92,7 @@ function Get-CIPPMFAState { RowKey = [string]($_.UserPrincipalName).replace('#', '') PartitionKey = 'users' } - + } return $GraphRequest } diff --git a/Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1 b/Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1 index 2cbc13b0a4f3..caca21766253 100644 --- a/Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1 @@ -3,22 +3,22 @@ function Get-CIPPOutOfOffice { param ( $userid, $TenantFilter, - $APIName = "Get Out of Office", + $APIName = 'Get Out of Office', $ExecutingUser ) try { - $OutOfOffice = New-ExoRequest -tenantid $TenantFilter -cmdlet "Get-MailboxAutoReplyConfiguration" -cmdParams @{Identity = $userid } -Anchor $userid + $OutOfOffice = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-MailboxAutoReplyConfiguration' -cmdParams @{Identity = $userid } -Anchor $userid $Results = @{ - AutoReplyState = $OutOfOffice.AutoReplyState - StartTime = $OutOfOffice.StartTime.ToString("yyyy-MM-dd HH:mm") - EndTime = $OutOfOffice.EndTime.ToString("yyyy-MM-dd HH:mm") + AutoReplyState = $OutOfOffice.AutoReplyState + StartTime = $OutOfOffice.StartTime.ToString('yyyy-MM-dd HH:mm') + EndTime = $OutOfOffice.EndTime.ToString('yyyy-MM-dd HH:mm') InternalMessage = $OutOfOffice.InternalMessage ExternalMessage = $OutOfOffice.ExternalMessage } | ConvertTo-Json return $Results - } - catch { - return "Could not retrieve out of office message for $($userid). Error: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + return "Could not retrieve out of office message for $($userid). Error: $ErrorMessage" } } diff --git a/Modules/CIPPCore/Public/Get-CIPPPartnerAzSubscriptions.ps1 b/Modules/CIPPCore/Public/Get-CIPPPartnerAzSubscriptions.ps1 index ea67ec1a3f9e..9c06f76edd0a 100644 --- a/Modules/CIPPCore/Public/Get-CIPPPartnerAzSubscriptions.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPPartnerAzSubscriptions.ps1 @@ -1,7 +1,7 @@ function Get-CIPPPartnerAzSubscriptions { param ( $TenantFilter, - $APIName = "Get-CIPPPartnerAzSubscriptions" + $APIName = 'Get-CIPPPartnerAzSubscriptions' ) try { @@ -15,38 +15,39 @@ function Get-CIPPPartnerAzSubscriptions { $subsCache = [system.collections.generic.list[hashtable]]::new() try { try { - $usageRecords = (New-GraphGETRequest -Uri "https://api.partnercenter.microsoft.com/v1/customers/$($TenantFilter)/subscriptions/usagerecords" -scope "https://api.partnercenter.microsoft.com/user_impersonation").items + $usageRecords = (New-GraphGETRequest -Uri "https://api.partnercenter.microsoft.com/v1/customers/$($TenantFilter)/subscriptions/usagerecords" -scope 'https://api.partnercenter.microsoft.com/user_impersonation').items } catch { - throw "Unable to retrieve usagerecord(s): $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + throw "Unable to retrieve usagerecord(s): $($ErrorMessage.NormalizedError)" } foreach ($usageRecord in $usageRecords) { # if condition probably needs more refining - if ($usageRecord.offerId -notlike "DZH318Z0BPS6*") { + if ($usageRecord.offerId -notlike 'DZH318Z0BPS6*') { # Legacy subscriptions are directly accessible $subDetails = @{ - tenantId = $tenantFilter + tenantId = $tenantFilter subscriptionId = ($usageRecord.id).ToLower() - isLegacy = $true - POR = "Legacy subscription" - status = $usageRecord.status + isLegacy = $true + POR = 'Legacy subscription' + status = $usageRecord.status } - + $subsCache.Add($subDetails) } else { # For modern subscriptions we need to dig a little deeper try { - $subid = (New-GraphGETRequest -Uri "https://api.partnercenter.microsoft.com/v1/customers/$($TenantFilter)/subscriptions/$($usageRecord.id)/azureEntitlements" -scope "https://api.partnercenter.microsoft.com/user_impersonation").items #| Where-Object { $_.status -eq "active" } - + $subid = (New-GraphGETRequest -Uri "https://api.partnercenter.microsoft.com/v1/customers/$($TenantFilter)/subscriptions/$($usageRecord.id)/azureEntitlements" -scope 'https://api.partnercenter.microsoft.com/user_impersonation').items #| Where-Object { $_.status -eq "active" } + foreach ($id in $subid) { $subDetails = @{ - tenantId = $tenantFilter + tenantId = $tenantFilter subscriptionId = ($id.id) - isLegacy = $false - POR = $id.partnerOnRecord - status = $id.status + isLegacy = $false + POR = $id.partnerOnRecord + status = $id.status } - + $subsCache.Add($subDetails) } } catch { @@ -59,6 +60,7 @@ function Get-CIPPPartnerAzSubscriptions { return $subsCache } catch { - Write-LogMessage -message "Unable to retrieve CSP Azure subscriptions for $($TenantFilter): $($_.Exception.Message)" -Sev 'ERROR' -API $APINAME + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -message "Unable to retrieve CSP Azure subscriptions for $($TenantFilter): $($ErrorMessage.NormalizedError)" -Sev 'ERROR' -API $APINAME -LogData $ErrorMessage } } diff --git a/Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1 b/Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1 index 5c525962009f..26a6033055ad 100644 --- a/Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1 @@ -29,6 +29,7 @@ function Get-CIPPPerUserMFA { } } } catch { - "Failed to get MFA State for $id : $_" + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + "Failed to get MFA State for $id : $ErrorMessage" } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Get-CIPPSPOTenant.ps1 b/Modules/CIPPCore/Public/Get-CIPPSPOTenant.ps1 index 80f6e83453aa..fec489bc729d 100644 --- a/Modules/CIPPCore/Public/Get-CIPPSPOTenant.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPSPOTenant.ps1 @@ -24,4 +24,4 @@ function Get-CIPPSPOTenant { $Results = New-GraphPostRequest -scope "$AdminURL/.default" -tenantid $TenantFilter -Uri "$AdminURL/_vti_bin/client.svc/ProcessQuery" -Type POST -Body $XML -ContentType 'text/xml' -AddedHeaders $AdditionalHeaders $Results | Select-Object -Last 1 *, @{n = 'SharepointPrefix'; e = { $tenantName } }, @{n = 'TenantFilter'; e = { $TenantFilter } } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Get-CIPPSchemaExtensions.ps1 b/Modules/CIPPCore/Public/Get-CIPPSchemaExtensions.ps1 index b85edb06af86..7b6df00aae24 100644 --- a/Modules/CIPPCore/Public/Get-CIPPSchemaExtensions.ps1 +++ b/Modules/CIPPCore/Public/Get-CIPPSchemaExtensions.ps1 @@ -81,4 +81,4 @@ function Get-CIPPSchemaExtensions { New-GraphPOSTRequest -type PATCH -Uri "https://graph.microsoft.com/v1.0/schemaExtensions/$($Schema.id)" -Body $PatchJson -AsApp $true -NoAuthCheck $true } } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Get-SlackAlertBlocks.ps1 b/Modules/CIPPCore/Public/Get-SlackAlertBlocks.ps1 index 60e42aee5ced..52a0fbb2a1f8 100644 --- a/Modules/CIPPCore/Public/Get-SlackAlertBlocks.ps1 +++ b/Modules/CIPPCore/Public/Get-SlackAlertBlocks.ps1 @@ -262,4 +262,4 @@ function Get-SlackAlertBlocks { blocks = $Blocks } } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/GraphHelper/New-ExoRequest.ps1 b/Modules/CIPPCore/Public/GraphHelper/New-ExoRequest.ps1 index 1217dc4886e6..8d5aa4e372dc 100644 --- a/Modules/CIPPCore/Public/GraphHelper/New-ExoRequest.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/New-ExoRequest.ps1 @@ -1,23 +1,61 @@ -function New-ExoRequest ($tenantid, $cmdlet, $cmdParams, $useSystemMailbox, $Anchor, $NoAuthCheck, $Select) { +function New-ExoRequest { <# .FUNCTIONALITY Internal #> + [CmdletBinding()] + Param( + [Parameter(Mandatory = $true)] + [string]$cmdlet, + + [Parameter(Mandatory = $false)] + $cmdParams, + + [Parameter(Mandatory = $false)] + [string]$Select, + + [Parameter(Mandatory = $false)] + [string]$Anchor, + + [Parameter(Mandatory = $false)] + [bool]$useSystemMailbox, + + [Parameter(Mandatory = $false)] + [string]$tenantid, + + [Parameter(Mandatory = $false)] + [bool]$NoAuthCheck, + + [switch]$Compliance, + [ValidateSet('v1.0', 'beta')] + [string]$ApiVersion = 'beta' + ) if ((Get-AuthorisedRequest -TenantID $tenantid) -or $NoAuthCheck -eq $True) { - $token = Get-ClassicAPIToken -resource 'https://outlook.office365.com' -Tenantid $tenantid - $Tenant = Get-Tenants -IncludeErrors | Where-Object { $_.defaultDomainName -eq $tenantid -or $_.customerId -eq $tenantid } + + if ($Compliance.IsPresent) { + $Resource = 'https://ps.compliance.protection.outlook.com' + $token = Get-GraphToken -tenantid $tenantid -scope "$Resource/.default" + $token = @{ 'access_token' = $token.Authorization -replace 'Bearer ' } + } else { + $Resource = 'https://outlook.office365.com' + $token = Get-ClassicAPIToken -resource $Resource -Tenantid $tenantid + } if ($cmdParams) { + #if cmdparams is a pscustomobject, convert to hashtable, otherwise leave as is $Params = $cmdParams } else { $Params = @{} } - $ExoBody = ConvertTo-Json -Depth 5 -InputObject @{ + $ExoBody = ConvertTo-Json -Depth 5 -Compress -InputObject @{ CmdletInput = @{ CmdletName = $cmdlet Parameters = $Params } } + + $Tenant = Get-Tenants -IncludeErrors | Where-Object { $_.defaultDomainName -eq $tenantid -or $_.customerId -eq $tenantid } + if (!$Anchor) { if ($cmdparams.Identity) { $Anchor = $cmdparams.Identity } if ($cmdparams.anr) { $Anchor = $cmdparams.anr } @@ -43,21 +81,40 @@ function New-ExoRequest ($tenantid, $cmdlet, $cmdParams, $useSystemMailbox, $Anc } } } - Write-Host "Using $Anchor" + + Write-Verbose "Using $Anchor" + $Headers = @{ - Authorization = "Bearer $($token.access_token)" - Prefer = 'odata.maxpagesize = 1000' - 'parameter-based-routing' = $true - 'X-AnchorMailbox' = $anchor + Authorization = "Bearer $($token.access_token)" + Prefer = 'odata.maxpagesize=1000' + 'X-AnchorMailbox' = $anchor + } + # Compliance API trickery. Capture Location headers on redirect, extract subdomain and prepend to compliance URL + if ($Compliance.IsPresent) { + $URL = "$Resource/adminapi/$ApiVersion/$($tenant.customerId)/EXOBanner('AutogenSession')?Version=3.4.0" + Invoke-RestMethod -ResponseHeadersVariable ComplianceHeaders -MaximumRedirection 0 -ErrorAction SilentlyContinue -Uri $URL -Headers $Headers -SkipHttpErrorCheck | Out-Null + $RedirectedHost = ([System.Uri]($ComplianceHeaders.Location | Select-Object -First 1)).Host + $RedirectedHostname = '{0}.ps.compliance.protection.outlook.com' -f ($RedirectedHost -split '\.' | Select-Object -First 1) + $Resource = "https://$($RedirectedHostname)" + Write-Verbose "Redirecting to $Resource" } + try { - if ($Select) { $Select = "`$select=$Select" } - $URL = "https://outlook.office365.com/adminapi/beta/$($tenant.customerId)/InvokeCommand?$Select" + if ($Select) { $Select = "?`$select=$Select" } + $URL = "$Resource/adminapi/$ApiVersion/$($tenant.customerId)/InvokeCommand$Select" + + Write-Verbose "POST [ $URL ]" + $ReturnedData = do { + $ExoRequestParams = @{ + Uri = $URL + Method = 'POST' + Body = $ExoBody + Headers = $Headers + ContentType = 'application/json' + } - $ReturnedData = - do { - $Return = Invoke-RestMethod $URL -Method POST -Body $ExoBody -Headers $Headers -ContentType 'application/json; charset=utf-8' + $Return = Invoke-RestMethod @ExoRequestParams $URL = $Return.'@odata.nextLink' $Return } until ($null -eq $URL) @@ -67,11 +124,14 @@ function New-ExoRequest ($tenantid, $cmdlet, $cmdParams, $useSystemMailbox, $Anc } } catch { $ErrorMess = $($_.Exception.Message) - $ReportedError = ($_.ErrorDetails | ConvertFrom-Json -ErrorAction SilentlyContinue) - $Message = if ($ReportedError.error.details.message) { - $ReportedError.error.details.message - } elseif ($ReportedError.error.message) { $ReportedError.error.message } - else { $ReportedError.error.innererror.internalException.message } + try { + $ReportedError = ($_.ErrorDetails.Message | ConvertFrom-Json -ErrorAction SilentlyContinue) + $Message = if ($ReportedError.error.details.message) { + $ReportedError.error.details.message + } elseif ($ReportedError.error.innererror) { + $ReportedError.error.innererror.internalException.message + } elseif ($ReportedError.error.message) { $ReportedError.error.message } + } catch { $Message = $_.ErrorDetails } if ($null -eq $Message) { $Message = $ErrorMess } throw $Message } diff --git a/Modules/CIPPCore/Public/GraphHelper/New-passwordString.ps1 b/Modules/CIPPCore/Public/GraphHelper/New-passwordString.ps1 index 5869c370108e..c8393455c326 100644 --- a/Modules/CIPPCore/Public/GraphHelper/New-passwordString.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/New-passwordString.ps1 @@ -23,7 +23,7 @@ function New-passwordString { $containsUppercase = $Password -cmatch '[A-Z]' $containsLowercase = $Password -cmatch '[a-z]' $containsDigit = $Password -cmatch '\d' - $containsSpecialChar = $Password -cmatch "[$%&*#]" + $containsSpecialChar = $Password -cmatch '[$%&*#]' $isComplex = $containsUppercase -and $containsLowercase -and $containsDigit -and $containsSpecialChar diff --git a/Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1 index 1c474b20a44f..db939b3ee098 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1 @@ -20,19 +20,20 @@ Function Invoke-RemoveAPDevice { $Deviceid = $Request.Query.ID try { - if ($TenantFilter -eq $null -or $TenantFilter -eq 'null') { - $GraphRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities/$Deviceid" -type DELETE + if ($null -eq $TenantFilter -or $TenantFilter -eq 'null') { + $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities/$Deviceid" -type DELETE } else { - $GraphRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities/$Deviceid" -tenantid $TenantFilter -type DELETE + $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeviceIdentities/$Deviceid" -tenantid $TenantFilter -type DELETE } Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $TenantFilter -API $APINAME -message "Deleted autopilot device $Deviceid" -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully deleted the autopilot device' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $TenantFilter -API $APINAME -message "Autopilot Delete API failed for $deviceid. The error is: $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to delete device: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $request.headers.'x-ms-client-principal' -tenant $TenantFilter -API $APINAME -message "Autopilot Delete API failed for $deviceid. The error is: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Failed to delete device: $($ErrorMessage.NormalizedError)" } } #force a sync, this can give "too many requests" if deleleting a bunch of devices though. - $GraphRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotSettings/sync' -tenantid $TenantFilter -type POST -body '{}' + $null = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotSettings/sync' -tenantid $TenantFilter -type POST -body '{}' # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ diff --git a/Modules/CIPPCore/Public/Invoke-RemoveApp.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveApp.ps1 index b154d77568eb..10430868b406 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveApp.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveApp.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveApp { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter @@ -19,12 +20,13 @@ Function Invoke-RemoveApp { if (!$policyId) { exit } try { #$unAssignRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies('$($policyId)')/assign" -type POST -Body '{"assignments":[]}' -tenant $TenantFilter - $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($policyId)" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Deleted $policyId" -Sev 'Info' -tenant $TenantFilter + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($policyId)" -type DELETE -tenant $TenantFilter + Write-LogMessage -user $User -API $APINAME -message "Deleted $policyId" -Sev 'Info' -tenant $TenantFilter $body = [pscustomobject]@{'Results' = 'Successfully deleted the application' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not delete app $policyId. $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter - $body = [pscustomobject]@{'Results' = "Could not delete this application: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Could not delete app $policyId. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Could not delete this application: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveBPATemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveBPATemplate.ps1 index b9ae2a8c13e1..6e247411b394 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveBPATemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveBPATemplate.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveBPATemplate { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.TemplateName try { @@ -20,11 +21,12 @@ Function Invoke-RemoveBPATemplate { $Filter = "PartitionKey eq 'BPATemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed BPA Template with ID $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed BPA Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed BPA Template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove BPA template $ID. $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to remove template: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove BPA template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveCAPolicy.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveCAPolicy.ps1 index da878e3dbba2..f84ed7466f45 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveCAPolicy.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveCAPolicy.ps1 @@ -11,20 +11,22 @@ Function Invoke-RemoveCAPolicy { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter $policyId = $Request.Query.GUID if (!$policyId) { exit } try { - $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/$($policyId)" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Deleted CA Policy $policyId" -Sev 'Info' -tenant $TenantFilter + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/$($policyId)" -type DELETE -tenant $TenantFilter + Write-LogMessage -user $User -API $APINAME -message "Deleted CA Policy $policyId" -Sev 'Info' -tenant $TenantFilter $body = [pscustomobject]@{'Results' = 'Successfully deleted the policy' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not delete CA policy $policyId. $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter - $body = [pscustomobject]@{'Results' = "Could not delete policy: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Could not delete CA policy $policyId. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Could not delete policy: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveCATemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveCATemplate.ps1 index 7ff2f2bf5df8..b3024895b3a5 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveCATemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveCATemplate.ps1 @@ -11,20 +11,22 @@ Function Invoke-RemoveCATemplate { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' - + $User = $request.headers.'x-ms-client-principal' $ID = $request.query.id + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' + try { $Table = Get-CippTable -tablename 'templates' $Filter = "PartitionKey eq 'CATemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed Conditional Access Template with ID $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed Conditional Access Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Conditional Access Template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove Conditional Access template $ID. $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to remove template: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove Conditional Access template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' + $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveContact.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveContact.ps1 index fc34c0073005..3635459a6f1b 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveContact.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveContact.ps1 @@ -11,8 +11,9 @@ Function Invoke-RemoveContact { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Params = @{ @@ -22,12 +23,13 @@ Function Invoke-RemoveContact { try { $Params = @{ Identity = $request.query.GUID } - $GraphRequest = New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Remove-MailContact' -cmdParams $params -UseSystemMailbox $true + $null = New-ExoRequest -tenantid $Tenantfilter -cmdlet 'Remove-MailContact' -cmdParams $params -UseSystemMailbox $true $Result = "Deleted $($Request.query.guid)" - Write-LogMessage -API 'TransportRules' -tenant $tenantfilter -message "Deleted contact $($Request.query.guid)" -sev Debug + Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Deleted contact $($Request.query.guid)" -sev Debug } catch { - $ErrorMessage = Get-NormalizedError -Message $_.Exception - $Result = $ErrorMessage + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Failed to delete contact $($Request.query.guid). $($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage + $Result = $ErrorMessage.NormalizedError } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ diff --git a/Modules/CIPPCore/Public/Invoke-RemoveExConnector.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveExConnector.ps1 index 79b201c068b4..84cdfc72e91c 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveExConnector.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveExConnector.ps1 @@ -11,19 +11,20 @@ Function Invoke-RemoveExConnector { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter try { $Params = @{ Identity = $request.query.GUID } - $GraphRequest = New-ExoRequest -tenantid $Tenantfilter -cmdlet "Remove-$($Request.query.Type)Connector" -cmdParams $params -useSystemMailbox $true + $null = New-ExoRequest -tenantid $Tenantfilter -cmdlet "Remove-$($Request.query.Type)Connector" -cmdParams $params -useSystemMailbox $true $Result = "Deleted $($Request.query.guid)" - Write-LogMessage -API 'TransportRules' -tenant $tenantfilter -message "Deleted transport rule $($Request.query.guid)" -sev Debug - } - catch { - $ErrorMessage = Get-NormalizedError -Message $_.Exception - $Result = $ErrorMessage + Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Deleted transport rule $($Request.query.guid)" -sev Debug + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Failed deleting transport rule $($Request.query.guid). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage + $Result = $ErrorMessage.NormalizedError } # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ diff --git a/Modules/CIPPCore/Public/Invoke-RemoveExConnectorTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveExConnectorTemplate.ps1 index b12df6a3d0aa..f603904daec4 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveExConnectorTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveExConnectorTemplate.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveExConnectorTemplate { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -19,11 +20,12 @@ Function Invoke-RemoveExConnectorTemplate { $Filter = "PartitionKey eq 'ExConnectorTemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed Exchange Connector Template with ID $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed Exchange Connector Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Exchange Connector Template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove Exchange Connector Template $ID. $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to remove template: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove Exchange Connector Template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveGroupTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveGroupTemplate.ps1 index 85e4346a2b81..51d5d9d03ce6 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveGroupTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveGroupTemplate.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveGroupTemplate { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -22,11 +23,12 @@ Function Invoke-RemoveGroupTemplate { Write-Host $Filter $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed Intune Template with ID $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed Intune Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove intune template $ID. $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to remove template: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove intune template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveIntuneTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveIntuneTemplate.ps1 index f1b2c51ca2bf..4c66d297fc66 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveIntuneTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveIntuneTemplate.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveIntuneTemplate { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -22,14 +23,14 @@ Function Invoke-RemoveIntuneTemplate { Write-Host $Filter $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed Intune Template with ID $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed Intune Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Intune Template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove intune template $ID. $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to remove template: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove intune template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } - # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Invoke-RemovePolicy.ps1 b/Modules/CIPPCore/Public/Invoke-RemovePolicy.ps1 index c7805fb46a48..aa94e6d3213c 100644 --- a/Modules/CIPPCore/Public/Invoke-RemovePolicy.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemovePolicy.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemovePolicy { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter @@ -20,13 +21,14 @@ Function Invoke-RemovePolicy { try { #$unAssignRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies('$($policyId)')/assign" -type POST -Body '{"assignments":[]}' -tenant $TenantFilter - $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$($Request.Query.URLName)('$($policyId)')" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Deleted $policyId" -Sev 'Info' -tenant $TenantFilter + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/deviceManagement/$($Request.Query.URLName)('$($policyId)')" -type DELETE -tenant $TenantFilter + Write-LogMessage -user $User -API $APINAME -message "Deleted $policyId" -Sev 'Info' -tenant $TenantFilter $body = [pscustomobject]@{'Results' = 'Successfully deleted the policy' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not delete policy $policyId. $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter - $body = [pscustomobject]@{'Results' = "Could not delete policy: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Could not delete policy $policyId. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Could not delete policy: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveQueuedApp.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveQueuedApp.ps1 index 1e1d3fd4de14..f1de92bdeab7 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveQueuedApp.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveQueuedApp.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveQueuedApp { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -19,14 +20,14 @@ Function Invoke-RemoveQueuedApp { $Filter = "PartitionKey eq 'apps' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed application queue for $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed application queue for $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed from queue.' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove application queue for $ID. $($_.Exception.Message)" -Sev 'Error' + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove application queue for $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage $body = [pscustomobject]@{'Results' = 'Failed to remove standard)' } } - # Associate values to output bindings by calling 'Push-OutputBinding'. Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK diff --git a/Modules/CIPPCore/Public/Invoke-RemoveSpamfilter.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveSpamfilter.ps1 index d1d0160aaa34..736b834d0d72 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveSpamfilter.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveSpamfilter.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveSpamfilter { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter $Params = @{ @@ -24,10 +25,10 @@ Function Invoke-RemoveSpamfilter { $cmdlet = 'Remove-HostedContentFilterPolicy' $null = New-ExoRequest -tenantid $Tenantfilter -cmdlet $cmdlet -cmdParams $params -useSystemmailbox $true $Result = "Deleted $($Request.query.name)" - Write-LogMessage -API 'TransportRules' -tenant $tenantfilter -message "Deleted transport rule $($Request.query.name)" -sev Debug + Write-LogMessage -user $User -API 'TransportRules' -tenant $tenantfilter -message "Deleted transport rule $($Request.query.name)" -sev Debug } catch { - $ErrorMessage = Get-NormalizedError -Message $_.Exception - Write-LogMessage -API 'TransportRules' -tenant $tenantfilter -message "Failed deleting transport rule $($Request.query.name). Error:$ErrorMessage" -Sev Error + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API 'TransportRules' -tenant $tenantfilter -message "Failed deleting transport rule $($Request.query.name). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $Result = $ErrorMessage } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Invoke-RemoveSpamfilterTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveSpamfilterTemplate.ps1 index eaa19ff08df6..8e4f8d870eed 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveSpamfilterTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveSpamfilterTemplate.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveSpamfilterTemplate { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -19,11 +20,12 @@ Function Invoke-RemoveSpamfilterTemplate { $Filter = "PartitionKey eq 'SpamfilterTemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed Transport Rule Template with ID $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed Transport Rule Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Transport Rule Template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove Transport Rule template $ID. $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to remove template: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove Transport Rule template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveStandard.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveStandard.ps1 index 88d7f21e3212..06f864c69222 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveStandard.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveStandard.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveStandard { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -19,12 +20,13 @@ Function Invoke-RemoveStandard { $Filter = "PartitionKey eq 'standards' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed standards for $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed standards for $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed standards deployment' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove standard for $ID. $($_.Exception.Message)" -Sev 'Error' + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove standard for $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' $body = [pscustomobject]@{'Results' = 'Failed to remove standard)' } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveStandardTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveStandardTemplate.ps1 index b7c11bd2d584..d00b4da7bffa 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveStandardTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveStandardTemplate.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveStandardTemplate { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.ID try { @@ -20,11 +21,12 @@ Function Invoke-RemoveStandardTemplate { $Filter = "PartitionKey eq 'StandardsTemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed Standards Template named $($ClearRow.name) and id $($id)" -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed Standards Template named $($ClearRow.name) and id $($id)" -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove Standards template $ID. $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to remove template: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove Standards template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveTransportRule.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveTransportRule.ps1 index aa358ad25202..8db570555836 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveTransportRule.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveTransportRule.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveTransportRule { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $Tenantfilter = $request.Query.tenantfilter @@ -23,9 +24,10 @@ Function Invoke-RemoveTransportRule { $cmdlet = 'Remove-TransportRule' $null = New-ExoRequest -tenantid $Tenantfilter -cmdlet $cmdlet -cmdParams $params -UseSystemMailbox $true $Result = "Deleted $($Request.query.guid)" - Write-LogMessage -API 'TransportRules' -tenant $tenantfilter -message "Deleted transport rule $($Request.query.guid)" -sev Debug + Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Deleted transport rule $($Request.query.guid)" -sev Debug } catch { $ErrorMessage = Get-NormalizedError -Message $_.Exception + Write-LogMessage -user $User -API $APIName -tenant $tenantfilter -message "Failed deleting transport rule $($Request.query.guid). Error:$($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage $Result = $ErrorMessage } # Associate values to output bindings by calling 'Push-OutputBinding'. diff --git a/Modules/CIPPCore/Public/Invoke-RemoveTransportRuleTemplate.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveTransportRuleTemplate.ps1 index 3510d02b34a2..f01c97da7adb 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveTransportRuleTemplate.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveTransportRuleTemplate.ps1 @@ -11,7 +11,8 @@ Function Invoke-RemoveTransportRuleTemplate { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' $ID = $request.query.id try { @@ -19,11 +20,12 @@ Function Invoke-RemoveTransportRuleTemplate { $Filter = "PartitionKey eq 'TransportTemplate' and RowKey eq '$id'" $ClearRow = Get-CIPPAzDataTableEntity @Table -Filter $Filter -Property PartitionKey, RowKey Remove-AzDataTableEntity @Table -Entity $clearRow - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Removed Transport Rule Template with ID $ID." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Removed Transport Rule Template with ID $ID." -Sev 'Info' $body = [pscustomobject]@{'Results' = 'Successfully removed Transport Rule Template' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove Transport Rule template $ID. $($_.Exception.Message)" -Sev 'Error' - $body = [pscustomobject]@{'Results' = "Failed to remove template: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Failed to remove Transport Rule template $ID. $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Failed to remove template: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Invoke-RemoveUser.ps1 b/Modules/CIPPCore/Public/Invoke-RemoveUser.ps1 index 040278ba9d80..a018e2ffd710 100644 --- a/Modules/CIPPCore/Public/Invoke-RemoveUser.ps1 +++ b/Modules/CIPPCore/Public/Invoke-RemoveUser.ps1 @@ -11,20 +11,22 @@ Function Invoke-RemoveUser { param($Request, $TriggerMetadata) $APIName = $TriggerMetadata.FunctionName - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug' + $User = $request.headers.'x-ms-client-principal' + Write-LogMessage -user $User -API $APINAME -message 'Accessed this API' -Sev 'Debug' # Interact with query parameters or the body of the request. $TenantFilter = $Request.Query.TenantFilter $userid = $Request.Query.ID if (!$userid) { exit } try { - $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Deleted $userid" -Sev 'Info' -tenant $TenantFilter + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)" -type DELETE -tenant $TenantFilter + Write-LogMessage -user $User -API $APINAME -message "Deleted $userid" -Sev 'Info' -tenant $TenantFilter $body = [pscustomobject]@{'Results' = 'Successfully deleted the user.' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not delete user $userid. $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter - $body = [pscustomobject]@{'Results' = "Could not delete user: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Could not delete user $userid. $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + $body = [pscustomobject]@{'Results' = "Could not delete user: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/New-CIPPAPIConfig.ps1 b/Modules/CIPPCore/Public/New-CIPPAPIConfig.ps1 index 47d111209e0f..873e264b11ec 100644 --- a/Modules/CIPPCore/Public/New-CIPPAPIConfig.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPAPIConfig.ps1 @@ -3,41 +3,39 @@ function New-CIPPAPIConfig { [CmdletBinding()] param ( - $APIName = "CIPP API Config", + $APIName = 'CIPP API Config', $ExecutingUser, $resetpassword ) $null = Connect-AzAccount -Identity - $currentapp = (Get-AzKeyVaultSecret -VaultName $ENV:WEBSITE_DEPLOYMENT_ID -Name "CIPPAPIAPP" -AsPlainText) + $currentapp = (Get-AzKeyVaultSecret -VaultName $ENV:WEBSITE_DEPLOYMENT_ID -Name 'CIPPAPIAPP' -AsPlainText) $subscription = $($ENV:WEBSITE_OWNER_NAME).Split('+')[0] try { if ($currentapp) { $APIApp = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/applications(appid='$($currentapp)')" -NoAuthCheck $true - } - else { + } else { $CreateBody = @" {"api":{"oauth2PermissionScopes":[{"adminConsentDescription":"Allow the application to access CIPP-API on behalf of the signed-in user.","adminConsentDisplayName":"Access CIPP-API","id":"ba7ffeff-96ea-4ac4-9822-1bcfee9adaa4","isEnabled":true,"type":"User","userConsentDescription":"Allow the application to access CIPP-API on your behalf.","userConsentDisplayName":"Access CIPP-API","value":"user_impersonation"}]},"displayName":"CIPP-API","requiredResourceAccess":[{"resourceAccess":[{"id":"e1fe6dd8-ba31-4d61-89e7-88639da4683d","type":"Scope"}],"resourceAppId":"00000003-0000-0000-c000-000000000000"}],"signInAudience":"AzureADMyOrg","web":{"homePageUrl":"https://cipp.app","implicitGrantSettings":{"enableAccessTokenIssuance":false,"enableIdTokenIssuance":true},"redirectUris":["https://$($ENV:Website_hostname)/.auth/login/aad/callback"]}} "@ - Write-Host "Creating app" - $APIApp = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications" -NoAuthCheck $true -type POST -body $CreateBody - Write-Host "Creating password" - $APIPassword = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/addPassword" -NoAuthCheck $true -type POST -body "{`"passwordCredential`":{`"displayName`":`"Generated by API Setup`"}}" - Write-Host "Adding App URL" - $APIIdUrl = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)" -NoAuthCheck $true -type PATCH -body "{`"identifierUris`":[`"api://$($APIApp.appId)`"]}" - Write-Host "Adding serviceprincipal" - $ServicePrincipal = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/serviceprincipals" -NoAuthCheck $true -type POST -body "{`"accountEnabled`":true,`"appId`":`"$($APIApp.appId)`",`"displayName`":`"CIPP-API`",`"tags`":[`"WindowsAzureActiveDirectoryIntegratedApp`",`"AppServiceIntegratedApp`"]}" + Write-Host 'Creating app' + $APIApp = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/v1.0/applications' -NoAuthCheck $true -type POST -body $CreateBody + Write-Host 'Creating password' + $APIPassword = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/addPassword" -NoAuthCheck $true -type POST -body "{`"passwordCredential`":{`"displayName`":`"Generated by API Setup`"}}" + Write-Host 'Adding App URL' + $APIIdUrl = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)" -NoAuthCheck $true -type PATCH -body "{`"identifierUris`":[`"api://$($APIApp.appId)`"]}" + Write-Host 'Adding serviceprincipal' + $ServicePrincipal = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/v1.0/serviceprincipals' -NoAuthCheck $true -type POST -body "{`"accountEnabled`":true,`"appId`":`"$($APIApp.appId)`",`"displayName`":`"CIPP-API`",`"tags`":[`"WindowsAzureActiveDirectoryIntegratedApp`",`"AppServiceIntegratedApp`"]}" } if ($resetpassword) { - Write-Host "Removing all old passwords" + Write-Host 'Removing all old passwords' $RemovePasswords = New-GraphPOSTRequest -type Patch -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/" -body '{"passwordCredentials":[]}' -NoAuthCheck $true - $passwordDate = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") - $APIPassword = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/addPassword" -NoAuthCheck $true -type POST -body "{`"passwordCredential`":{`"displayName`":`"Generated by API Setup`"}}" - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None '-message "Reset CIPP API Password." -Sev "info" - } - else { - $CurrentSettings = New-GraphGetRequest -uri "https://management.azure.com/subscriptions/$($subscription)/resourceGroups/$ENV:WEBSITE_RESOURCE_GROUP/providers/Microsoft.Web/sites/$ENV:WEBSITE_SITE_NAME/Config/authsettingsV2/list?api-version=2018-11-01" -NoAuthCheck $true -scope "https://management.azure.com/.default" - Write-Host "setting settings" + $passwordDate = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ') + $APIPassword = New-GraphPOSTRequest -uri "https://graph.microsoft.com/v1.0/applications/$($APIApp.id)/addPassword" -NoAuthCheck $true -type POST -body "{`"passwordCredential`":{`"displayName`":`"Generated by API Setup`"}}" + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None '-message 'Reset CIPP API Password.' -Sev 'info' + } else { + $CurrentSettings = New-GraphGetRequest -uri "https://management.azure.com/subscriptions/$($subscription)/resourceGroups/$ENV:WEBSITE_RESOURCE_GROUP/providers/Microsoft.Web/sites/$ENV:WEBSITE_SITE_NAME/Config/authsettingsV2/list?api-version=2018-11-01" -NoAuthCheck $true -scope 'https://management.azure.com/.default' + Write-Host 'setting settings' $currentSettings.properties.identityProviders.azureActiveDirectory = @{ registration = @{ clientId = $APIApp.appId @@ -48,10 +46,10 @@ function New-CIPPAPIConfig { } } $currentBody = ConvertTo-Json -Depth 15 -InputObject ($currentSettings | Select-Object Properties) - Write-Host "writing to Azure" - $SetAPIAuth = New-GraphPOSTRequest -type "PUT" -uri "https://management.azure.com/subscriptions/$($subscription)/resourceGroups/$ENV:WEBSITE_RESOURCE_GROUP/providers/Microsoft.Web/sites/$ENV:WEBSITE_SITE_NAME/Config/authsettingsV2?api-version=2018-11-01" -scope "https://management.azure.com/.default" -NoAuthCheck $true -body $currentBody + Write-Host 'writing to Azure' + $SetAPIAuth = New-GraphPOSTRequest -type 'PUT' -uri "https://management.azure.com/subscriptions/$($subscription)/resourceGroups/$ENV:WEBSITE_RESOURCE_GROUP/providers/Microsoft.Web/sites/$ENV:WEBSITE_SITE_NAME/Config/authsettingsV2?api-version=2018-11-01" -scope 'https://management.azure.com/.default' -NoAuthCheck $true -body $currentBody $null = Set-AzKeyVaultSecret -VaultName $ENV:WEBSITE_DEPLOYMENT_ID -Name 'CIPPAPIAPP' -SecretValue (ConvertTo-SecureString -String $APIApp.AppID -AsPlainText -Force) - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None '-message "Successfully setup CIPP-API Access." -Sev "info" + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None '-message 'Successfully setup CIPP-API Access.' -Sev 'info' } return @{ ApplicationID = $APIApp.AppId @@ -59,12 +57,12 @@ function New-CIPPAPIConfig { Results = "API Enabled. Your API URL is https://$($ENV:Website_hostname). Your Application ID is $($APIApp.AppId) and your Application Secret is $($APIPassword.secretText) - Copy these keys, they are only shown once." } - } - catch { - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None' -message "Failed to setup CIPP-API Access: $($_.Exception.Message) Linenumber: $($_.InvocationInfo.ScriptLineNumber)" -Sev "Error" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant 'None' -message "Failed to setup CIPP-API Access: $($ErrorMessage.NormalizedError) Linenumber: $($_.InvocationInfo.ScriptLineNumber)" -Sev 'Error' -LogData $ErrorMessage return @{ - Results = " but could not set API configuration: $($_.Exception.Message)" + Results = " but could not set API configuration: $($ErrorMessage.NormalizedError)" } } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/New-CIPPApplicationCopy.ps1 b/Modules/CIPPCore/Public/New-CIPPApplicationCopy.ps1 index da8b584954f8..1b20dea8eb81 100644 --- a/Modules/CIPPCore/Public/New-CIPPApplicationCopy.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPApplicationCopy.ps1 @@ -35,7 +35,7 @@ function New-CIPPApplicationCopy { $TenantInfo = New-GraphGetRequest -Uri 'https://graph.microsoft.com/beta/servicePrincipals?$top=999' -tenantid $Tenant -NoAuthCheck $true if ($App -Notin $TenantInfo.appId) { - $PostResults = New-GraphPostRequest 'https://graph.microsoft.com/beta/servicePrincipals' -type POST -tenantid $Tenant -body "{ `"appId`": `"$($App)`" }" + $null = New-GraphPostRequest 'https://graph.microsoft.com/beta/servicePrincipals' -type POST -tenantid $Tenant -body "{ `"appId`": `"$($App)`" }" Write-LogMessage -message "Added $App as a service principal" -tenant $tenant -API 'Application Copy' -sev Info } Add-CIPPApplicationPermission -RequiredResourceAccess $ApplicationResourceAccess -ApplicationId $App -Tenantfilter $Tenant diff --git a/Modules/CIPPCore/Public/New-CIPPBackup.ps1 b/Modules/CIPPCore/Public/New-CIPPBackup.ps1 index 722a1f09a18f..266c724ff39b 100644 --- a/Modules/CIPPCore/Public/New-CIPPBackup.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPBackup.ps1 @@ -40,13 +40,15 @@ function New-CIPPBackup { $Result = Add-CIPPAzDataTableEntity @Table -entity $entity -Force Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Created CIPP Backup' -Sev 'Debug' } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup for CIPP: $($_.Exception.Message)" -Sev 'Error' - [pscustomobject]@{'Results' = "Backup Creation failed: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup for CIPP: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + [pscustomobject]@{'Results' = "Backup Creation failed: $($ErrorMessage.NormalizedError)" } } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup: $($_.Exception.Message)" -Sev 'Error' - [pscustomobject]@{'Results' = "Backup Creation failed: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + [pscustomobject]@{'Results' = "Backup Creation failed: $($ErrorMessage.NormalizedError)" } } } @@ -73,8 +75,9 @@ function New-CIPPBackup { $Result } catch { $State = 'Failed to write backup to table storage' - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup for Conditional Access Policies: $($_.Exception.Message)" -Sev 'Error' - [pscustomobject]@{'Results' = "Backup Creation failed: $($_.Exception.Message)" } + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to create backup for Conditional Access Policies: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + [pscustomobject]@{'Results' = "Backup Creation failed: $($ErrorMessage.NormalizedError)" } } } diff --git a/Modules/CIPPCore/Public/New-CIPPBackupTask.ps1 b/Modules/CIPPCore/Public/New-CIPPBackupTask.ps1 index a82bd4d1ac3a..e1905ac3d49e 100644 --- a/Modules/CIPPCore/Public/New-CIPPBackupTask.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPBackupTask.ps1 @@ -11,7 +11,7 @@ function New-CIPPBackupTask { $Users = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/users?$top=999' -tenantid $TenantFilter | Select-Object * -ExcludeProperty mail, provisionedPlans, onPrem*, *passwordProfile*, *serviceProvisioningErrors*, isLicenseReconciliationNeeded, isManagementRestricted, isResourceAccount, *date*, *external*, identities, deletedDateTime, isSipEnabled, assignedPlans, cloudRealtimeCommunicationInfo, deviceKeys, provisionedPlan, securityIdentifier #remove the property if the value is $null $Users | ForEach-Object { - $_.psobject.properties | Where-Object { $_.Value -eq $null } | ForEach-Object { + $_.psobject.properties | Where-Object { $null -eq $_.Value } | ForEach-Object { $_.psobject.properties.Remove($_.Name) } } @@ -50,7 +50,8 @@ function New-CIPPBackupTask { try { New-CIPPIntuneTemplate -TenantFilter $TenantFilter -URLName $URLName -ID $Policy.ID } catch { - "Failed to create a template of the Intune Configuration Policy with ID: $($Policy.id). Error: $($_.Exception.Message)" + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + "Failed to create a template of the Intune Configuration Policy with ID: $($Policy.id). Error: $ErrorMessage" } } } catch { diff --git a/Modules/CIPPCore/Public/New-CIPPCAPolicy.ps1 b/Modules/CIPPCore/Public/New-CIPPCAPolicy.ps1 index 26f9046c4d21..e75847a094cf 100644 --- a/Modules/CIPPCore/Public/New-CIPPCAPolicy.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPCAPolicy.ps1 @@ -10,6 +10,9 @@ function New-CIPPCAPolicy { $APIName = 'Create CA Policy', $ExecutingUser ) + + $User = $request.headers.'x-ms-client-principal' + function Remove-EmptyArrays ($Object) { if ($Object -is [Array]) { foreach ($Item in $Object) { Remove-EmptyArrays $Item } @@ -23,7 +26,7 @@ function New-CIPPCAPolicy { foreach ($Name in @($Object.psobject.properties.Name)) { if ($Object.$Name -is [Array] -and $Object.$Name.get_Count() -eq 0) { $Object.PSObject.Properties.Remove($Name) - } elseif ($object.$name -eq $null) { + } elseif ($null -eq $object.$name) { $Object.PSObject.Properties.Remove($Name) } else { Remove-EmptyArrays $Object.$Name } } @@ -38,11 +41,11 @@ function New-CIPPCAPolicy { param($groupNames) return $groupNames | ForEach-Object { if (Test-IsGuid $_) { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Already GUID, no need to replace: $_" -Sev 'Debug' + Write-LogMessage -user $User -API $APINAME -message "Already GUID, no need to replace: $_" -Sev 'Debug' $_ # it's a GUID, so we keep it } else { $groupId = ($groups | Where-Object -Property displayName -EQ $_).id # it's a display name, so we get the group ID - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Replaced group name $_ with ID $groupId" -Sev 'Debug' + Write-LogMessage -user $User -API $APINAME -message "Replaced group name $_ with ID $groupId" -Sev 'Debug' $groupId } } @@ -75,7 +78,7 @@ function New-CIPPCAPolicy { $Body = ConvertTo-Json -InputObject $JSONObj.GrantControls.authenticationStrength $GraphRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/identity/conditionalAccess/authenticationStrength/policies' -body $body -Type POST -tenantid $tenantfilter $JSONObj.GrantControls.authenticationStrength = @{ id = $ExistingStrength.id } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created new Authentication Strength Policy: $($JSONObj.GrantControls.authenticationStrength.displayName)" -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Created new Authentication Strength Policy: $($JSONObj.GrantControls.authenticationStrength.displayName)" -Sev 'Info' } } @@ -90,13 +93,13 @@ function New-CIPPCAPolicy { id = ($CheckExististing | Where-Object -Property displayName -EQ $Location.displayName).id name = ($CheckExististing | Where-Object -Property displayName -EQ $Location.displayName).displayName } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Matched a CA policy with the existing Named Location: $($location.displayName)" -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Matched a CA policy with the existing Named Location: $($location.displayName)" -Sev 'Info' } else { if ($location.countriesAndRegions) { $location.countriesAndRegions = @($location.countriesAndRegions) } $Body = ConvertTo-Json -InputObject $Location $GraphRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/identity/conditionalAccess/namedLocations' -body $body -Type POST -tenantid $tenantfilter - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created new Named Location: $($location.displayName)" -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -message "Created new Named Location: $($location.displayName)" -Sev 'Info' [pscustomobject]@{ id = $GraphRequest.id name = $GraphRequest.displayName @@ -148,13 +151,14 @@ function New-CIPPCAPolicy { } } } catch { - throw "Failed to replace displayNames for conditional access rule $($JSONObj.displayName): $($_.exception.message)" - Write-LogMessage -API 'Standards' -tenant $tenant -message "Failed to replace displayNames for conditional access rule $($JSONObj.displayName)" -sev 'Error' + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -API 'Standards' -tenant $tenant -message "Failed to replace displayNames for conditional access rule $($JSONObj.displayName). Error: $($ErrorMessage.NormalizedError)" -sev 'Error' -LogData $ErrorMessage + throw "Failed to replace displayNames for conditional access rule $($JSONObj.displayName): $($ErrorMessage.NormalizedError)" } } } $JsonObj.PSObject.Properties.Remove('LocationInfo') - $RawJSON = $JSONObj | ConvertTo-Json -Depth 10 -Compress + $RawJSON = ConvertTo-Json -InputObject $JSONObj -Depth 10 -Compress Write-Host $RawJSON try { Write-Host 'Checking' @@ -166,17 +170,18 @@ function New-CIPPCAPolicy { } else { Write-Host "overwriting $($CheckExististing.id)" $PatchRequest = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/identity/conditionalAccess/policies/$($CheckExististing.id)" -tenantid $tenantfilter -type PATCH -body $RawJSON - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Updated Conditional Access Policy $($JSONObj.Displayname) to the template standard." -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -tenant $($Tenant) -message "Updated Conditional Access Policy $($JSONObj.Displayname) to the template standard." -Sev 'Info' return "Updated policy $displayname for $tenantfilter" } } else { Write-Host 'Creating' $CreateRequest = New-GraphPOSTRequest -uri 'https://graph.microsoft.com/beta/identity/conditionalAccess/policies' -tenantid $tenantfilter -type POST -body $RawJSON - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($Tenant) -message "Added Conditional Access Policy $($JSONObj.Displayname)" -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -tenant $($Tenant) -message "Added Conditional Access Policy $($JSONObj.Displayname)" -Sev 'Info' return "Created policy $displayname for $tenantfilter" } } catch { - throw "Failed to create or update conditional access rule $($JSONObj.displayName): $($_.exception.message)" - Write-LogMessage -API 'Standards' -tenant $tenant -message "Failed to create or update conditional access rule $($JSONObj.displayName): $($_.exception.message) " -sev 'Error' + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -API 'Standards' -tenant $tenant -message "Failed to create or update conditional access rule $($JSONObj.displayName): $($ErrorMessage.NormalizedError) " -sev 'Error' -LogData $ErrorMessage + throw "Failed to create or update conditional access rule $($JSONObj.displayName): $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/New-CIPPDeviceAction.ps1 b/Modules/CIPPCore/Public/New-CIPPDeviceAction.ps1 index 3e0312750dc8..8a1d2eaf5476 100644 --- a/Modules/CIPPCore/Public/New-CIPPDeviceAction.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPDeviceAction.ps1 @@ -8,13 +8,13 @@ function New-CIPPDeviceAction { $ExecutingUser, $APINAME ) - try { - $GraphRequest = New-Graphpostrequest -uri "https://graph.microsoft.com/beta/deviceManagement/managedDevices('$DeviceFilter')/$($Action)" -type POST -tenantid $TenantFilter -body $ActionBody - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message "Queued $Action on $DeviceFilter" -Sev "Info" + try { + $null = New-Graphpostrequest -uri "https://graph.microsoft.com/beta/deviceManagement/managedDevices('$DeviceFilter')/$($Action)" -type POST -tenantid $TenantFilter -body $ActionBody + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message "Queued $Action on $DeviceFilter" -Sev 'Info' return "Queued $Action on $DeviceFilter" - } - catch { - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message "Failed to queue action $Action on $DeviceFilter : $($_.Exception.Message)" -Sev "Error" - return "Failed to queue action $Action on $DeviceFilter $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $TenantFilter -message "Failed to queue action $Action on $DeviceFilter : $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + return "Failed to queue action $Action on $DeviceFilter $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/New-CIPPOneDriveShortCut.ps1 b/Modules/CIPPCore/Public/New-CIPPOneDriveShortCut.ps1 index e140b1e6052c..d270b17efde3 100644 --- a/Modules/CIPPCore/Public/New-CIPPOneDriveShortCut.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPOneDriveShortCut.ps1 @@ -6,33 +6,33 @@ function New-CIPPOneDriveShortCut { $userid, $URL, $TenantFilter, - $APIName = "Create OneDrive shortcut", + $APIName = 'Create OneDrive shortcut', $ExecutingUser ) Write-Host "Received $username and $userid. We're using $url and $TenantFilter" try { - $SiteInfo = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/sites/" -tenantid $TenantFilter -asapp $true | Where-Object -Property weburl -EQ $url + $SiteInfo = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/sites/' -tenantid $TenantFilter -asapp $true | Where-Object -Property weburl -EQ $url $ListItemUniqueId = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/sites/$($siteInfo.id)/drive?`$select=SharepointIds" -tenantid $TenantFilter -asapp $true).SharePointIds $body = [PSCustomObject]@{ name = "$($SiteInfo.displayName)" remoteItem = @{ sharepointIds = @{ listId = $($ListItemUniqueId.listid) - listItemUniqueId = "root" + listItemUniqueId = 'root' siteId = $($ListItemUniqueId.siteId) siteUrl = $($ListItemUniqueId.siteUrl) webId = $($ListItemUniqueId.webId) } } - '@microsoft.graph.conflictBehavior' = "rename" + '@microsoft.graph.conflictBehavior' = 'rename' } | ConvertTo-Json -Depth 10 New-GraphPOSTRequest -method POST "https://graph.microsoft.com/beta/users/$username/drive/root/children" -body $body -tenantid $TenantFilter -asapp $true - Write-LogMessage -message "Created OneDrive shortcut called $($SiteInfo.displayName) for $($username)" -Sev 'info' -API $APIName -user $ExecutingUser + Write-LogMessage -API $APIName -user $ExecutingUser -message "Created OneDrive shortcut called $($SiteInfo.displayName) for $($username)" -Sev 'info' return "Created OneDrive Shortcut for $username called $($SiteInfo.displayName) " - } - catch { - Write-LogMessage -message "Could not add Onedrive shortcut to $username : $($_.Exception.Message)" -Sev 'error' -API $APIName -user $ExecutingUser - return "Could not add Onedrive shortcut to $username : $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add Onedrive shortcut to $username : $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + return "Could not add Onedrive shortcut to $username : $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/New-CIPPRestoreTask.ps1 b/Modules/CIPPCore/Public/New-CIPPRestoreTask.ps1 index 8d48960d1899..afa3463b4fd0 100644 --- a/Modules/CIPPCore/Public/New-CIPPRestoreTask.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPRestoreTask.ps1 @@ -39,8 +39,9 @@ function New-CIPPRestoreTask { } } } catch { - "Could not restore user $($UPN): $($_.Exception.Message) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore user $($UPN): $($_.Exception.Message) " -Sev 'error' + $ErrorMessage = Get-CippException -Exception $_ + "Could not restore user $($UPN): $($ErrorMessage.NormalizedError) " + Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore user $($UPN): $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } } @@ -74,8 +75,9 @@ function New-CIPPRestoreTask { } } } catch { - "Could not restore group $DisplayName $($_.Exception.Message) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore group $DisplayName $($_.Exception.Message) " -Sev 'error' + $ErrorMessage = Get-CippException -Exception $_ + "Could not restore group $DisplayName : $($ErrorMessage.NormalizedError) " + Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore group $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } } @@ -87,8 +89,9 @@ function New-CIPPRestoreTask { try { New-CIPPCAPolicy -replacePattern 'displayName' -Overwrite $overwrite -TenantFilter $TenantFilter -state 'donotchange' -RawJSON $JSON -APIName 'CIPP Restore' -ErrorAction SilentlyContinue } catch { - "Could not restore Conditional Access Policy $DisplayName $($_.Exception.Message) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Conditional Access Policy $DisplayName $($_.Exception.Message) " -Sev 'error' + $ErrorMessage = Get-CippException -Exception $_ + "Could not restore Conditional Access Policy $DisplayName : $($ErrorMessage.NormalizedError) " + Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Conditional Access Policy $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } } @@ -98,8 +101,9 @@ function New-CIPPRestoreTask { try { Set-CIPPIntunePolicy -TemplateType $backup.Type -TenantFilter $TenantFilter -DisplayName $backup.DisplayName -Description $backup.Description -RawJSON ($backup.TemplateJson) -ErrorAction SilentlyContinue } catch { - "Could not restore Intune Configuration $DisplayName $($_.Exception.Message) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName $($_.Exception.Message) " -Sev 'error' + $ErrorMessage = Get-CippException -Exception $_ + "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " + Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } #Convert the manual method to a function @@ -110,8 +114,9 @@ function New-CIPPRestoreTask { try { Set-CIPPIntunePolicy -TemplateType $backup.Type -TenantFilter $TenantFilter -DisplayName $backup.DisplayName -Description $backup.Description -RawJSON ($backup.TemplateJson) -ErrorAction SilentlyContinue } catch { - "Could not restore Intune Compliance $DisplayName $($_.Exception.Message) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName $($_.Exception.Message) " -Sev 'error' + $ErrorMessage = Get-CippException -Exception $_ + "Could not restore Intune Compliance $DisplayName : $($ErrorMessage.NormalizedError) " + Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } @@ -123,8 +128,9 @@ function New-CIPPRestoreTask { try { Set-CIPPIntunePolicy -TemplateType $backup.Type -TenantFilter $TenantFilter -DisplayName $backup.DisplayName -Description $backup.Description -RawJSON ($backup.TemplateJson) -ErrorAction SilentlyContinue } catch { - "Could not restore Intune Protection $DisplayName $($_.Exception.Message) " - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName $($_.Exception.Message) " -Sev 'error' + $ErrorMessage = Get-CippException -Exception $_ + "Could not restore Intune Protection $DisplayName : $($ErrorMessage.NormalizedError) " + Write-LogMessage -user $ExecutingUser -API $APINAME -message "Could not restore Intune Configuration $DisplayName : $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } @@ -137,7 +143,8 @@ function New-CIPPRestoreTask { try { Add-CIPPAzDataTableEntity @WebhookTable -Entity $Backup -Force } catch { - "Could not restore Webhook Alerts $($_.Exception.Message)" + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + "Could not restore Webhook Alerts $ErrorMessage" } } 'CippScriptedAlerts' { @@ -147,7 +154,8 @@ function New-CIPPRestoreTask { try { Add-CIPPAzDataTableEntity @ScheduledTasks -Entity $Backup -Force } catch { - "Could not restore Scripted Alerts $($_.Exception.Message) " + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + "Could not restore Scripted Alerts $ErrorMessage " } } 'CippStandards' { @@ -157,7 +165,8 @@ function New-CIPPRestoreTask { try { Add-CIPPAzDataTableEntity @Table -Entity $StandardsBackup -Force } catch { - "Could not restore Standards $($_.Exception.Message) " + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + "Could not restore Standards $ErrorMessage " } } diff --git a/Modules/CIPPCore/Public/New-CIPPSharepointSite.ps1 b/Modules/CIPPCore/Public/New-CIPPSharepointSite.ps1 index ccf2e8b81b22..9959defd302e 100644 --- a/Modules/CIPPCore/Public/New-CIPPSharepointSite.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPSharepointSite.ps1 @@ -128,7 +128,7 @@ function New-CIPPSharepointSite { $Request.Classification = $Classification } - Write-Verbose ($Request | ConvertTo-Json -Compress -Depth 10) + Write-Verbose (ConvertTo-Json -InputObject $Request -Compress -Depth 10) $body = @{ request = $Request diff --git a/Modules/CIPPCore/Public/New-CIPPTAP.ps1 b/Modules/CIPPCore/Public/New-CIPPTAP.ps1 index 7b0427a5cf20..c997c6d62daf 100644 --- a/Modules/CIPPCore/Public/New-CIPPTAP.ps1 +++ b/Modules/CIPPCore/Public/New-CIPPTAP.ps1 @@ -3,20 +3,19 @@ function New-CIPPTAP { param ( $userid, $TenantFilter, - $APIName = "Create TAP", + $APIName = 'Create TAP', $ExecutingUser ) try { - $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)/authentication/temporaryAccessPassMethods" -tenantid $TenantFilter -type POST -body "{}" -verbose - $GraphRequest - Write-LogMessage -user $ExecutingUser -API $APIName -message "Created Temporary Access Password (TAP) for $userid" -Sev "Info" -tenant $TenantFilter + $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)/authentication/temporaryAccessPassMethods" -tenantid $TenantFilter -type POST -body '{}' -verbose + Write-LogMessage -user $ExecutingUser -API $APIName -message "Created Temporary Access Password (TAP) for $userid" -Sev 'Info' -tenant $TenantFilter return "The TAP for this user is $($GraphRequest.temporaryAccessPass) - This TAP is usable for the next $($GraphRequest.LifetimeInMinutes) minutes" - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to created TAP for $($userid): $($_.Exception.Message)" -Sev "Error" -tenant $TenantFilter - Return "Failed to create TAP: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to created TAP for $($userid): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + Return "Failed to create TAP: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPCalendarInvites.ps1 b/Modules/CIPPCore/Public/Remove-CIPPCalendarInvites.ps1 index 22e57c2acff8..3c0d9c326024 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPCalendarInvites.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPCalendarInvites.ps1 @@ -9,13 +9,14 @@ function Remove-CIPPCalendarInvites { ) try { - - New-ExoRequest -tenantid $tenantFilter -cmdlet 'Remove-CalendarEvents' -Anchor $username -cmdParams @{Identity = $username; QueryWindowInDays = 730 ; CancelOrganizedMeetings = $true ; Confirm = $false} + + New-ExoRequest -tenantid $tenantFilter -cmdlet 'Remove-CalendarEvents' -Anchor $username -cmdParams @{Identity = $username; QueryWindowInDays = 730 ; CancelOrganizedMeetings = $true ; Confirm = $false } Write-LogMessage -user $ExecutingUser -API $APIName -message "Cancelled all calendar invites for $($username)" -Sev 'Info' -tenant $tenantFilter - "Cancelled all calendar invites for $($username)" + "Cancelled all calendar invites for $($username)" } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not cancel calendar invites for $($username): $($_.Exception.Message)" -Sev 'Error' -tenant $tenantFilter - return "Could not cancel calendar invites for $($username). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not cancel calendar invites for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $tenantFilter -LogData $ErrorMessage + return "Could not cancel calendar invites for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPGroup.ps1 b/Modules/CIPPCore/Public/Remove-CIPPGroup.ps1 index a99750cda781..4dcd10d02988 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPGroup.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPGroup.ps1 @@ -5,26 +5,26 @@ function Remove-CIPPGroup { $GroupType, $ID, $DisplayName, - $APIName = "Remove Group", + $APIName = 'Remove Group', $TenantFilter ) try { - if ($GroupType -eq "Distribution List" -or $GroupType -eq "Mail-Enabled Security") { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Remove-DistributionGroup" -cmdParams @{Identity = $id; BypassSecurityGroupManagerCheck = $true } -useSystemMailbox $true - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "$($DisplayName) Deleted" -Sev "Info" + if ($GroupType -eq 'Distribution List' -or $GroupType -eq 'Mail-Enabled Security') { + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Remove-DistributionGroup' -cmdParams @{Identity = $id; BypassSecurityGroupManagerCheck = $true } -useSystemMailbox $true + Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "$($DisplayName) Deleted" -Sev 'Info' return "Successfully Deleted $($GroupType) group $($DisplayName)" - } - elseif ($GroupType -eq "Microsoft 365" -or $GroupType -eq "Security") { - $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/groups/$($ID)" -tenantid $TenantFilter -type Delete -verbose - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "$($DisplayName) Deleted" -Sev "Info" + + } elseif ($GroupType -eq 'Microsoft 365' -or $GroupType -eq 'Security') { + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/groups/$($ID)" -tenantid $TenantFilter -type Delete -verbose + Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "$($DisplayName) Deleted" -Sev 'Info' return "Successfully Deleted $($GroupType) group $($DisplayName)" } - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete $DisplayName" -Sev "Error" -tenant $TenantFilter - return "Could not delete $DisplayName. Error: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete $DisplayName. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not delete $DisplayName. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPGroupMember.ps1 b/Modules/CIPPCore/Public/Remove-CIPPGroupMember.ps1 index 54c6a33e1a9d..c434625a3537 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPGroupMember.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPGroupMember.ps1 @@ -1,28 +1,29 @@ function Remove-CIPPGroupMember( [string]$ExecutingUser, - [string]$GroupType, + [string]$GroupType, [string]$GroupId, - [string]$Member, + [string]$Member, [string]$TenantFilter, [string]$APIName = 'Remove Group Member' ) { try { if ($member -like '*#EXT#*') { $member = [System.Web.HttpUtility]::UrlEncode($member) } - $MemberIDs = 'https://graph.microsoft.com/v1.0/directoryObjects/' + (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($member)" -tenantid $TenantFilter).id - $addmemberbody = "{ `"members@odata.bind`": $(ConvertTo-Json @($MemberIDs)) }" + # $MemberIDs = 'https://graph.microsoft.com/v1.0/directoryObjects/' + (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/users/$($member)" -tenantid $TenantFilter).id + # $addmemberbody = "{ `"members@odata.bind`": $(ConvertTo-Json @($MemberIDs)) }" if ($GroupType -eq 'Distribution list' -or $GroupType -eq 'Mail-Enabled Security') { $Params = @{ Identity = $GroupId; Member = $member; BypassSecurityGroupManagerCheck = $true } - New-ExoRequest -tenantid $TenantFilter -cmdlet 'Remove-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Remove-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true } else { New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$($GroupId)/members/$($Member)/`$ref" -tenantid $TenantFilter -type DELETE -body '{}' -Verbose } $Message = "Successfully removed user $($Member) from $($GroupId)." Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message $Message -Sev 'Info' return $message + } catch { - $message = "Failed to remove user $($Member) from $($GroupId): $($_.Exception.Message)" - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message $message -Sev 'error' - return $message + $ErrorMessage = Get-CippException -Exception $_ + $message = "Failed to remove user $($Member) from $($GroupId): $($ErrorMessage.NormalizedError)" + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message $message -Sev 'error' -LogData $ErrorMessage + return $message } - } diff --git a/Modules/CIPPCore/Public/Remove-CIPPGroups.ps1 b/Modules/CIPPCore/Public/Remove-CIPPGroups.ps1 index e37df34f2bf0..e9cb0b078b23 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPGroups.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPGroups.ps1 @@ -17,16 +17,16 @@ function Remove-CIPPGroups { Import-Module '.\Modules\AzBobbyTables' Import-Module '.\Modules\CIPPCore' $group = $_ - - try { + + try { $Groupname = ($using:AllGroups | Where-Object -Property id -EQ $group).displayName $IsMailEnabled = ($using:AllGroups | Where-Object -Property id -EQ $group).mailEnabled - $IsM365Group = ($using:AllGroups | Where-Object { $_.id -eq $group -and $_.groupTypes -contains 'Unified' }) -ne $null + $IsM365Group = $null -ne ($using:AllGroups | Where-Object { $_.id -eq $group -and $_.groupTypes -contains 'Unified' }) if ($IsM365Group) { - $RemoveRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$_/members/$($using:userid)/`$ref" -tenantid $using:tenantFilter -type DELETE -body '' -Verbose + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$_/members/$($using:userid)/`$ref" -tenantid $using:tenantFilter -type DELETE -body '' -Verbose } elseif (-not $IsMailEnabled) { - $RemoveRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$_/members/$($using:userid)/`$ref" -tenantid $using:tenantFilter -type DELETE -body '' -Verbose + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/groups/$_/members/$($using:userid)/`$ref" -tenantid $using:tenantFilter -type DELETE -body '' -Verbose } elseif ($IsMailEnabled) { $Params = @{ Identity = $Groupname; Member = $using:userid ; BypassSecurityGroupManagerCheck = $true } New-ExoRequest -tenantid $using:tenantFilter -cmdlet 'Remove-DistributionGroupMember' -cmdParams $params -UseSystemMailbox $true @@ -35,13 +35,14 @@ function Remove-CIPPGroups { Write-LogMessage -user $using:ExecutingUser -API $($using:APIName) -message "Removed $($using:Username) from $groupname" -Sev 'Info' -tenant $using:TenantFilter "Successfully removed $($using:Username) from group $Groupname" } catch { - Write-LogMessage -user $using:ExecutingUser -API $($using:APIName) -message "Could not remove $($using:Username) from group $groupname" -Sev 'Error' -tenant $using:TenantFilter - "Could not remove $($using:Username) from group $($Groupname): $($_.Exception.Message). This is likely because its a Dynamic Group or synched with active directory" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $using:ExecutingUser -API $($using:APIName) -message "Could not remove $($using:Username) from group $groupname : $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $using:TenantFilter -LogData $ErrorMessage + "Could not remove $($using:Username) from group $($Groupname): $($ErrorMessage.NormalizedError). This is likely because its a Dynamic Group or synched with active directory" } } if (!$Returnval) { $Returnval = "$($Username) is not a member of any groups." Write-LogMessage -user $ExecutingUser -API $APIName -message "$($Username) is not a member of any groups" -Sev 'Info' -tenant $TenantFilter - } + } return $Returnval } diff --git a/Modules/CIPPCore/Public/Remove-CIPPLicense.ps1 b/Modules/CIPPCore/Public/Remove-CIPPLicense.ps1 index 68c037b495fc..390b276efa20 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPLicense.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPLicense.ps1 @@ -29,7 +29,8 @@ function Remove-CIPPLicense { return "No licenses to remove for $username" } } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not remove license for $username" -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) - return "Could not remove license for $($username). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not remove license for $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not remove license for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPMailboxPermissions.ps1 b/Modules/CIPPCore/Public/Remove-CIPPMailboxPermissions.ps1 index 7035a083ff0f..1e039e8bb8e5 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPMailboxPermissions.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPMailboxPermissions.ps1 @@ -25,7 +25,7 @@ function Remove-CIPPMailboxPermissions { $MailboxPerms = New-ExoRequest -Anchor $UserId -tenantid $Tenantfilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $userid; GrantSendonBehalfTo = @{'@odata.type' = '#Exchange.GenericHashTable'; remove = $AccessUser }; } if ($MailboxPerms -notlike '*completed successfully but no settings of*') { Write-LogMessage -user $ExecutingUser -API $APIName -message "Removed SendOnBehalf permissions for $($AccessUser) from $($userid)'s mailbox." -Sev 'Info' -tenant $TenantFilter - "Removed SendOnBehalf permissions for $($AccessUser) from $($userid)'s mailbox." + "Removed SendOnBehalf permissions for $($AccessUser) from $($userid)'s mailbox." } } 'SendAS' { @@ -47,7 +47,8 @@ function Remove-CIPPMailboxPermissions { } return $Results } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not remove mailbox permissions for $($userid). Error: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter - return "Could not remove mailbox permissions for $($userid). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not remove mailbox permissions for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not remove mailbox permissions for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPMobileDevice.ps1 b/Modules/CIPPCore/Public/Remove-CIPPMobileDevice.ps1 index e5ae407bf35e..54706e3e97f3 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPMobileDevice.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPMobileDevice.ps1 @@ -17,11 +17,12 @@ function Remove-CIPPMobileDevice { "Could not remove device: $($_.FriendlyName)" } } - if (!$Devices) { $Devices ='No mobile devices have been removed as we could not find any' } + if (!$Devices) { $Devices = 'No mobile devices have been removed as we could not find any' } Write-LogMessage -user $ExecutingUser -API $APIName -message "Deleted mobile devices for $($username)" -Sev 'Info' -tenant $tenantFilter return $devices } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete mobile devices for $($username): $($_.Exception.Message)" -Sev 'Error' -tenant $tenantFilter - return "Could not delete mobile devices for $($username). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete mobile devices for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $tenantFilter -LogData $ErrorMessage + return "Could not delete mobile devices for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPRules.ps1 b/Modules/CIPPCore/Public/Remove-CIPPRules.ps1 index c7e481bd0943..67a87f053ab8 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPRules.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPRules.ps1 @@ -4,28 +4,27 @@ function Remove-CIPPRules { $userid, $username, $TenantFilter, - $APIName = "Rules Removal", + $APIName = 'Rules Removal', $ExecutingUser ) try { Write-Host "Checking rules for $username" - $rules = New-ExoRequest -tenantid $TenantFilter -cmdlet "Get-InboxRule" -cmdParams @{mailbox = $username } + $rules = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Get-InboxRule' -cmdParams @{mailbox = $username } Write-Host "$($rules.count) rules found" - if ($rules -eq $null) { - Write-LogMessage -user $ExecutingUser -API $APIName -message "No Rules for $($username) to delete" -Sev "Info" -tenant $TenantFilter + if ($null -eq $rules) { + Write-LogMessage -user $ExecutingUser -API $APIName -message "No Rules for $($username) to delete" -Sev 'Info' -tenant $TenantFilter return "No rules for $($username) to delete" - } - else { + } else { ForEach ($rule in $rules) { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Remove-InboxRule" -Anchor $username -cmdParams @{Identity = $rule.Identity } + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Remove-InboxRule' -Anchor $username -cmdParams @{Identity = $rule.Identity } } - Write-LogMessage -user $ExecutingUser -API $APIName -message "Deleted Rules for $($username)" -Sev "Info" -tenant $TenantFilter + Write-LogMessage -user $ExecutingUser -API $APIName -message "Deleted Rules for $($username)" -Sev 'Info' -tenant $TenantFilter return "Deleted Rules for $($username)" } - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete rules for $($username): $($_.Exception.Message)" -Sev "Error" -tenant $TenantFilter - return "Could not delete rules for $($username). Error: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not delete rules for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not delete rules for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Remove-CIPPUser.ps1 b/Modules/CIPPCore/Public/Remove-CIPPUser.ps1 index 788a4e3332d3..f144b7f1213f 100644 --- a/Modules/CIPPCore/Public/Remove-CIPPUser.ps1 +++ b/Modules/CIPPCore/Public/Remove-CIPPUser.ps1 @@ -4,19 +4,19 @@ function Remove-CIPPUser { $ExecutingUser, $userid, $username, - $APIName = "Remove User", + $APIName = 'Remove User', $TenantFilter ) try { - $DeleteRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)" -type DELETE -tenant $TenantFilter - Write-LogMessage -user $ExecutingUser, -API $APIName -message "Deleted account $username" -Sev "Info" -tenant $TenantFilter + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)" -type DELETE -tenant $TenantFilter + Write-LogMessage -user $ExecutingUser, -API $APIName -message "Deleted account $username" -Sev 'Info' -tenant $TenantFilter return "Deleted the user account $username" - } - catch { - Write-LogMessage -user $ExecutingUser, -API $APIName -message "Could not delete $username" -Sev "Error" -tenant $TenantFilter - return "Could not delete $username. Error: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser, -API $APIName -message "Could not delete $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not delete $username. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Request-CIPPSPOPersonalSite.ps1 b/Modules/CIPPCore/Public/Request-CIPPSPOPersonalSite.ps1 index 44f1764b674c..1cfaec1e75ef 100644 --- a/Modules/CIPPCore/Public/Request-CIPPSPOPersonalSite.ps1 +++ b/Modules/CIPPCore/Public/Request-CIPPSPOPersonalSite.ps1 @@ -45,7 +45,8 @@ function Request-CIPPSPOPersonalSite { Write-LogMessage -user $ExecutingUser -API $APIName -message "Requested personal site for $($Users -join ', ')" -Sev 'Info' -tenant $TenantFilter return "Requested personal site for $($Users -join ', ')" } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not request personal site for $($Users -join ', ')" -Sev 'Error' -tenant $TenantFilter - return "Could not request personal site for $($Users -join ', '). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not request personal site for $($Users -join ', '). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not request personal site for $($Users -join ', '). Error: $($ErrorMessage.NormalizedError)" } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Revoke-CIPPSessions.ps1 b/Modules/CIPPCore/Public/Revoke-CIPPSessions.ps1 index a43996e3fe68..a20a0df59c8e 100644 --- a/Modules/CIPPCore/Public/Revoke-CIPPSessions.ps1 +++ b/Modules/CIPPCore/Public/Revoke-CIPPSessions.ps1 @@ -4,18 +4,18 @@ function Revoke-CIPPSessions { $ExecutingUser, $userid, $username, - $APIName = "Revoke Sessions", + $APIName = 'Revoke Sessions', $TenantFilter ) try { - $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)/invalidateAllRefreshTokens" -tenantid $TenantFilter -type POST -body '{}' -verbose - Write-LogMessage -user $ExecutingUser -API $APIName -message "Revoked sessions for $($username)" -Sev "Info" -tenant $TenantFilter + $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/users/$($userid)/invalidateAllRefreshTokens" -tenantid $TenantFilter -type POST -body '{}' -verbose + Write-LogMessage -user $ExecutingUser -API $APIName -message "Revoked sessions for $($username)" -Sev 'Info' -tenant $TenantFilter return "Success. All sessions by $username have been revoked" - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to revoke sessions for $($username): $($_.Exception.Message)" -Sev "Error" -tenant $TenantFilter - return "Revoke Session Failed: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to revoke sessions for $($username): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Revoke Session Failed: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 b/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 index 89bd2ade79d2..380431faa98f 100644 --- a/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 +++ b/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 @@ -39,8 +39,9 @@ function Send-CIPPAlert { Write-LogMessage -API 'Webhook Alerts' -message "Sent a webhook alert to email: $Title" -tenant $TenantFilter -sev info } catch { - Write-Information "Could not send webhook alert to email: $($_.Exception.message)" - Write-LogMessage -API 'Webhook Alerts' -message "Could not send webhook alerts to email. $($_.Exception.message)" -tenant $TenantFilter -sev info + $ErrorMessage = Get-CippException -Exception $_ + Write-Information "Could not send webhook alert to email: $($ErrorMessage.NormalizedError)" + Write-LogMessage -API 'Webhook Alerts' -message "Could not send webhook alerts to email. $($ErrorMessage.NormalizedError)" -tenant $TenantFilter -sev Error -LogData $ErrorMessage } } @@ -78,8 +79,9 @@ function Send-CIPPAlert { Write-LogMessage -API 'Webhook Alerts' -message "Sent Webhook alert $title to External webhook" -tenant $TenantFilter -sev info } catch { - Write-Information "Could not send alerts to webhook: $($_.Exception.message)" - Write-LogMessage -API 'Webhook Alerts' -message "Could not send alerts to webhook: $($_.Exception.message)" -tenant $TenantFilter -sev error -LogData (Get-CippException -Exception $_) + $ErrorMessage = Get-CippException -Exception $_ + Write-Information "Could not send alerts to webhook: $($ErrorMessage.NormalizedError)" + Write-LogMessage -API 'Webhook Alerts' -message "Could not send alerts to webhook: $($ErrorMessage.NormalizedError)" -tenant $TenantFilter -sev error -LogData $ErrorMessage } } Write-Information 'Trying to send to PSA' @@ -97,8 +99,9 @@ function Send-CIPPAlert { Write-LogMessage -API 'Webhook Alerts' -tenant $TenantFilter -message "Sent PSA alert $title" -sev info } catch { - Write-Information "Could not send alerts to ticketing system: $($_.Exception.message)" - Write-LogMessage -API 'Webhook Alerts' -tenant $TenantFilter -message "Could not send alerts to ticketing system: $($_.Exception.message)" -sev info + $ErrorMessage = Get-CippException -Exception $_ + Write-Information "Could not send alerts to ticketing system: $($ErrorMessage.NormalizedError)" + Write-LogMessage -API 'Webhook Alerts' -tenant $TenantFilter -message "Could not send alerts to ticketing system: $($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage } } } diff --git a/Modules/CIPPCore/Public/Set-CIPPAssignedApplication.ps1 b/Modules/CIPPCore/Public/Set-CIPPAssignedApplication.ps1 index 1938c35fabb8..bdd1ec2da682 100644 --- a/Modules/CIPPCore/Public/Set-CIPPAssignedApplication.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPAssignedApplication.ps1 @@ -114,7 +114,8 @@ function Set-CIPPAssignedApplication { } return "Assigned Application to $($GroupName)" } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not assign application to $GroupName" -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) - return "Could not assign application to $GroupName. Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not assign application to $GroupName. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not assign application to $GroupName. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPAssignedPolicy.ps1 b/Modules/CIPPCore/Public/Set-CIPPAssignedPolicy.ps1 index 2999f0705b17..e3e7c0b11ce4 100644 --- a/Modules/CIPPCore/Public/Set-CIPPAssignedPolicy.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPAssignedPolicy.ps1 @@ -70,14 +70,15 @@ function Set-CIPPAssignedPolicy { assignments = @($assignmentsObject) } if ($PSCmdlet.ShouldProcess($GroupName, "Assigning policy $PolicyId")) { - Write-Host "https://graph.microsoft.com/beta/$($PlatformType)/$Type('$($PolicyId)')/assign" + Write-Host "https://graph.microsoft.com/beta/$($PlatformType)/$Type('$($PolicyId)')/assign" $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/$($PlatformType)/$Type('$($PolicyId)')/assign" -tenantid $tenantFilter -type POST -body ($assignmentsObject | ConvertTo-Json -Depth 10) Write-LogMessage -user $ExecutingUser -API $APIName -message "Assigned Policy to $($GroupName)" -Sev 'Info' -tenant $TenantFilter } return "Assigned policy to $($GroupName) Policy ID is $($PolicyId)." } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to assign Policy to $GroupName. Policy ID is $($PolicyId)." -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) - return "Could not assign policy to $GroupName. Policy ID is $($PolicyId). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to assign Policy to $GroupName. Policy ID is $($PolicyId)." -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not assign policy to $GroupName. Policy ID is $($PolicyId). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPAuthenticationPolicy.ps1 b/Modules/CIPPCore/Public/Set-CIPPAuthenticationPolicy.ps1 index 380e7b2a4b30..77cdabfa6374 100644 --- a/Modules/CIPPCore/Public/Set-CIPPAuthenticationPolicy.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPAuthenticationPolicy.ps1 @@ -21,9 +21,9 @@ function Set-CIPPAuthenticationPolicy { $CurrentInfo = New-GraphGetRequest -Uri "https://graph.microsoft.com/beta/policies/authenticationmethodspolicy/authenticationMethodConfigurations/$AuthenticationMethodId" -tenantid $Tenant $CurrentInfo.state = $State } catch { - $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Could not get CurrentInfo for $AuthenticationMethodId. Error:$ErrorMessage" -sev Error - Return "Could not get CurrentInfo for $AuthenticationMethodId. Error:$($_.exception.message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Could not get CurrentInfo for $AuthenticationMethodId. Error:$($ErrorMessage.NormalizedError)" -sev Error -LogData $ErrorMessage + Return "Could not get CurrentInfo for $AuthenticationMethodId. Error:$($ErrorMessage.NormalizedError)" } switch ($AuthenticationMethodId) { @@ -118,8 +118,8 @@ function Set-CIPPAuthenticationPolicy { return "Set $AuthenticationMethodId state to $State $OptionalLogMessage" } catch { - Get-NormalizedError -Message $_.Exception.Message - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Failed to $State $AuthenticationMethodId Support: $ErrorMessage" -sev Error -LogData (Get-CippException -Exception $_) - return "Failed to $State $AuthenticationMethodId Support: $ErrorMessage" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $Tenant -message "Failed to $State $AuthenticationMethodId Support: $ErrorMessage" -sev Error -LogData $ErrorMessage + return "Failed to $State $AuthenticationMethodId Support. Error: $($ErrorMessage.NormalizedError)" } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Set-CIPPCPVConsent.ps1 b/Modules/CIPPCore/Public/Set-CIPPCPVConsent.ps1 index 5d530312d6f0..382b78d90e48 100644 --- a/Modules/CIPPCore/Public/Set-CIPPCPVConsent.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPCPVConsent.ps1 @@ -9,6 +9,7 @@ function Set-CIPPCPVConsent { $Results = [System.Collections.Generic.List[string]]::new() $Tenant = Get-Tenants -IncludeAll | Where-Object -Property customerId -EQ $TenantFilter | Select-Object -First 1 $TenantName = $Tenant.displayName + $User = $request.headers.'x-ms-client-principal' if ($TenantFilter -eq $env:TenantID) { return @('Cannot modify CPV consent on partner tenant') @@ -24,7 +25,8 @@ function Set-CIPPCPVConsent { } $Results.add("Deleted Service Principal from $TenantName") } catch { - $Results.add("Error deleting SP - $($_.Exception.Message)") + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + $Results.add("Error deleting SP - $($ErrorMessage)") } } @@ -57,10 +59,10 @@ function Set-CIPPCPVConsent { Add-CIPPAzDataTableEntity @Table -Entity $GraphRequest -Force } $Results.add("Successfully added CPV Application to tenant $($TenantName)") | Out-Null - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Added our Service Principal to $($TenantName)" -Sev 'Info' -tenant $Tenant.defaultDomainName -tenantId $TenantFilter + Write-LogMessage -user $User -API $APINAME -message "Added our Service Principal to $($TenantName)" -Sev 'Info' -tenant $Tenant.defaultDomainName -tenantId $TenantFilter } catch { - $ErrorMessage = Get-NormalizedError -message $_.Exception.Message - if ($ErrorMessage -like '*Permission entry already exists*') { + $ErrorMessage = Get-CippException -Exception $_ + if ($ErrorMessage.NormalizedError -like '*Permission entry already exists*') { $Table = Get-CIPPTable -TableName cpvtenants $unixtime = [int64](([datetime]::UtcNow) - (Get-Date '1/1/1970')).TotalSeconds $GraphRequest = @{ @@ -73,8 +75,8 @@ function Set-CIPPCPVConsent { Add-CIPPAzDataTableEntity @Table -Entity $GraphRequest -Force return @("We've already added our Service Principal to $($TenantName)") } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Could not add our Service Principal to the client tenant $($TenantName): $($_.Exception.message)" -Sev 'Error' -tenant $Tenant.defaultDomainName -tenantId $TenantFilter -LogData (Get-CippException -Exception $_) - return @("Could not add our Service Principal to the client tenant $($TenantName): $ErrorMessage") + Write-LogMessage -user $User -API $APINAME -message "Could not add our Service Principal to the client tenant $($TenantName): $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $Tenant.defaultDomainName -tenantId $TenantFilter -LogData $ErrorMessage + return @("Could not add our Service Principal to the client tenant $($TenantName). Error: $($ErrorMessage.NormalizedError)") } return $Results } diff --git a/Modules/CIPPCore/Public/Set-CIPPCopyGroupMembers.ps1 b/Modules/CIPPCore/Public/Set-CIPPCopyGroupMembers.ps1 index 0d437374b69e..41d60a70b521 100644 --- a/Modules/CIPPCore/Public/Set-CIPPCopyGroupMembers.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPCopyGroupMembers.ps1 @@ -26,9 +26,9 @@ function Set-CIPPCopyGroupMembers { Write-LogMessage -user $ExecutingUser -API $APIName -message "Added $UserId to group $($_.displayName)" -Sev 'Info' -tenant $TenantFilter $Success.Add("Added group: $($MailGroup.displayName)") | Out-Null } catch { - $NormalizedError = Get-NormalizedError -message $($_.Exception.Message) - $Errors.Add("We've failed to add the group $($MailGroup.displayName): $NormalizedError") | Out-Null - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Group adding failed for group $($_.displayName): $($_.Exception.Message)" -Sev 'Error' -LogData (Get-CippException -Exception $_) + $ErrorMessage = Get-CippException -Exception $_ + $Errors.Add("We've failed to add the group $($MailGroup.displayName): $($ErrorMessage.NormalizedError)") | Out-Null + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Group adding failed for group $($_.displayName): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage } } diff --git a/Modules/CIPPCore/Public/Set-CIPPDefaultAPDeploymentProfile.ps1 b/Modules/CIPPCore/Public/Set-CIPPDefaultAPDeploymentProfile.ps1 index e685491b262d..1b56d3816aa9 100644 --- a/Modules/CIPPCore/Public/Set-CIPPDefaultAPDeploymentProfile.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPDefaultAPDeploymentProfile.ps1 @@ -18,6 +18,9 @@ function Set-CIPPDefaultAPDeploymentProfile { $Language = 'os-default', $APIName = 'Add Default Enrollment Status Page' ) + + $User = $request.headers.'x-ms-client-principal-name' + try { $ObjBody = [pscustomobject]@{ '@odata.type' = '#microsoft.graph.azureADWindowsAutopilotDeploymentProfile' @@ -47,7 +50,7 @@ function Set-CIPPDefaultAPDeploymentProfile { if ($_.id -ne $Profiles[0].id) { if ($PSCmdlet.ShouldProcess($_.displayName, 'Delete duplicate Autopilot profile')) { $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeploymentProfiles/$($_.id)" -tenantid $tenantfilter -type DELETE - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($tenantfilter) -message "Deleted duplicate Autopilot profile $($displayname)" -Sev 'Info' + Write-LogMessage -user $User -API $APIName -tenant $($tenantfilter) -message "Deleted duplicate Autopilot profile $($displayname)" -Sev 'Info' } } } @@ -56,7 +59,7 @@ function Set-CIPPDefaultAPDeploymentProfile { if (!$Profiles) { if ($PSCmdlet.ShouldProcess($displayName, 'Add Autopilot profile')) { $GraphRequest = New-GraphPostRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeploymentProfiles' -body $body -tenantid $tenantfilter - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($tenantfilter) -message "Added Autopilot profile $($displayname)" -Sev 'Info' + Write-LogMessage -user $User -API $APIName -tenant $($tenantfilter) -message "Added Autopilot profile $($displayname)" -Sev 'Info' } } else { #patch the profile @@ -68,12 +71,13 @@ function Set-CIPPDefaultAPDeploymentProfile { $AssignBody = '{"target":{"@odata.type":"#microsoft.graph.allDevicesAssignmentTarget"}}' if ($PSCmdlet.ShouldProcess($AssignTo, "Assign Autopilot profile $displayname")) { $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/windowsAutopilotDeploymentProfiles/$($GraphRequest.id)/assignments" -tenantid $tenantfilter -type POST -body $AssignBody - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($tenantfilter) -message "Assigned autopilot profile $($Displayname) to $AssignTo" -Sev 'Info' + Write-LogMessage -user $User -API $APIName -tenant $($tenantfilter) -message "Assigned autopilot profile $($Displayname) to $AssignTo" -Sev 'Info' } } "Successfully added profile for $($tenantfilter)" } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APIName -tenant $($tenantfilter) -message "Failed adding Autopilot Profile $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' -LogData (Get-CippException -Exception $_) - throw "Failed to add profile for $($tenantfilter): $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APIName -tenant $($tenantfilter) -message "Failed adding Autopilot Profile $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + throw "Failed to add profile for $($tenantfilter): $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPDefaultAPEnrollment.ps1 b/Modules/CIPPCore/Public/Set-CIPPDefaultAPEnrollment.ps1 index 798dfdb71553..d0533c020201 100644 --- a/Modules/CIPPCore/Public/Set-CIPPDefaultAPEnrollment.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPDefaultAPEnrollment.ps1 @@ -13,6 +13,9 @@ function Set-CIPPDefaultAPEnrollment { $ExecutingUser, $APIName = 'Add Default Enrollment Status Page' ) + + $User = $request.headers.'x-ms-client-principal-name' + try { $ObjBody = [pscustomobject]@{ '@odata.type' = '#microsoft.graph.windows10EnrollmentCompletionPageConfiguration' @@ -37,10 +40,11 @@ function Set-CIPPDefaultAPEnrollment { if ($PSCmdlet.ShouldProcess($ExistingStatusPage.ID, 'Set Default Enrollment Status Page')) { $null = New-GraphPOSTRequest -uri "https://graph.microsoft.com/beta/deviceManagement/deviceEnrollmentConfigurations/$($ExistingStatusPage.ID)" -body $body -Type PATCH -tenantid $($TenantFilter) "Successfully changed default enrollment status page for $($($TenantFilter))" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message "Added Autopilot Enrollment Status Page $($Displayname)" -Sev 'Info' + Write-LogMessage -user $User -API $APINAME -tenant $($TenantFilter) -message "Added Autopilot Enrollment Status Page $($Displayname)" -Sev 'Info' } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($TenantFilter) -message "Failed adding Autopilot Enrollment Status Page $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' - throw "Failed to change default enrollment status page for $($($TenantFilter)): $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -tenant $($TenantFilter) -message "Failed adding Autopilot Enrollment Status Page $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + throw "Failed to change default enrollment status page for $($($TenantFilter)): $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPForwarding.ps1 b/Modules/CIPPCore/Public/Set-CIPPForwarding.ps1 index d8ebfe422845..23bce649ca3e 100644 --- a/Modules/CIPPCore/Public/Set-CIPPForwarding.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPForwarding.ps1 @@ -66,7 +66,8 @@ function Set-CIPPForwarding { Write-LogMessage -user $ExecutingUser -API $APIName -message $Message -Sev 'Info' -tenant $TenantFilter return $Message } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add forwarding for $($username)" -Sev 'Error' -tenant $TenantFilter - return "Could not add forwarding for $($username). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add forwarding for $($username). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not add forwarding for $($username). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPGDAPInviteGroups.ps1 b/Modules/CIPPCore/Public/Set-CIPPGDAPInviteGroups.ps1 index c648d1300446..bfba35fa1103 100644 --- a/Modules/CIPPCore/Public/Set-CIPPGDAPInviteGroups.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPGDAPInviteGroups.ps1 @@ -28,7 +28,8 @@ function Set-CIPPGDAPInviteGroups { Start-Sleep -Milliseconds 100 } } catch { - Write-LogMessage -API $APINAME -message "GDAP Group mapping failed for $($Relationship.customer.displayName) - Group: $($role.GroupId) - Exception: $($_.Exception.Message)" -Sev Error -LogData (Get-CippException -Exception $_) + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -API $APINAME -message "GDAP Group mapping failed for $($Relationship.customer.displayName) - Group: $($role.GroupId) - Exception: $($ErrorMessage.NormalizedError)" -Sev Error -LogData $ErrorMessage return $false } } @@ -57,7 +58,7 @@ function Set-CIPPGDAPInviteGroups { SkipLog = $true } #Write-Information ($InputObject | ConvertTo-Json) - $InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject ($InputObject | ConvertTo-Json -Depth 5 -Compress) + $InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject (ConvertTo-Json -InputObject $InputObject -Depth 5 -Compress) Write-Information "Started GDAP Invite orchestration with ID = '$InstanceId'" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPGraphSubscription.ps1 b/Modules/CIPPCore/Public/Set-CIPPGraphSubscription.ps1 index 1efd17294e93..c5cd14a1a7aa 100644 --- a/Modules/CIPPCore/Public/Set-CIPPGraphSubscription.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPGraphSubscription.ps1 @@ -5,16 +5,16 @@ function Set-CIPPGraphSubscription { $RenewSubscriptions, $Resource, $EventType, - $APIName = "Set Graph Webhook", + $APIName = 'Set Graph Webhook', $ExecutingUser ) if ($RenewSubscriptions) { - $RenewalDate = (Get-Date).AddDays(1).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + $RenewalDate = (Get-Date).AddDays(1).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ') $body = @{ - "expirationDateTime" = "$RenewalDate" + 'expirationDateTime' = "$RenewalDate" } | ConvertTo-Json - $ExistingSub = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/subscriptions" -tenantid $TenantFilter) | ForEach-Object { + $null = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/subscriptions' -tenantid $TenantFilter) | ForEach-Object { try { $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/subscriptions/$($_.id)" -tenantid $TenantFilter -type PATCH -body $body -Verbose $WebhookTable = Get-CIPPTable -TableName webhookTable @@ -22,13 +22,13 @@ function Set-CIPPGraphSubscription { $WebhookRow = Get-CIPPAzDataTableEntity @WebhookTable | Where-Object { $_.WebhookNotificationUrl -eq $GraphRequest.notificationUrl } $WebhookRow.Expiration = $RenewalDate $null = Add-CIPPAzDataTableEntity @WebhookTable -Entity $WebhookRow -Force - return "Renewed $($GraphRequest.notificationUrl)" + return "Renewed $($GraphRequest.notificationUrl)" - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to renew Webhook Subscription: $($_.Exception.Message)" -Sev "Error" -tenant $TenantFilter - return "Failed to renew Webhook Subscription $($WebhookRow.RowKey): $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Failed to renew Webhook Subscription: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Failed to renew Webhook Subscription $($WebhookRow.RowKey): $($ErrorMessage.NormalizedError)" } } } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Set-CIPPGroupAuthentication.ps1 b/Modules/CIPPCore/Public/Set-CIPPGroupAuthentication.ps1 index 13b224a70efa..e8d65c89fb5a 100644 --- a/Modules/CIPPCore/Public/Set-CIPPGroupAuthentication.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPGroupAuthentication.ps1 @@ -1,31 +1,29 @@ function Set-CIPPGroupAuthentication( [string]$ExecutingUser, - [string]$GroupType, - [string]$Id, - [string]$OnlyAllowInternalString, + [string]$GroupType, + [string]$Id, + [string]$OnlyAllowInternalString, [string]$TenantFilter, - [string]$APIName = "Group Sender Authentication" + [string]$APIName = 'Group Sender Authentication' ) { try { - $OnlyAllowInternal = if ($OnlyAllowInternalString -eq 'true') { "true" } else { "false" } - $messageSuffix = if ($OnlyAllowInternal -eq 'true') { "inside the organisation." } else { "inside and outside the organisation." } + $OnlyAllowInternal = if ($OnlyAllowInternalString -eq 'true') { 'true' } else { 'false' } + $messageSuffix = if ($OnlyAllowInternal -eq 'true') { 'inside the organisation.' } else { 'inside and outside the organisation.' } - if ($GroupType -eq "Distribution List" -or $GroupType -eq "Mail-Enabled Security") { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-DistributionGroup" -cmdParams @{Identity = $Id; RequireSenderAuthenticationEnabled = $OnlyAllowInternal } - } - elseif ($GroupType -eq "Microsoft 365") { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-UnifiedGroup" -cmdParams @{Identity = $Id; RequireSenderAuthenticationEnabled = $OnlyAllowInternal } - } - elseif ($GroupType -eq "Security") { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "This setting cannot be set on a security group." -Sev "Error" + if ($GroupType -eq 'Distribution List' -or $GroupType -eq 'Mail-Enabled Security') { + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-DistributionGroup' -cmdParams @{Identity = $Id; RequireSenderAuthenticationEnabled = $OnlyAllowInternal } + } elseif ($GroupType -eq 'Microsoft 365') { + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-UnifiedGroup' -cmdParams @{Identity = $Id; RequireSenderAuthenticationEnabled = $OnlyAllowInternal } + } elseif ($GroupType -eq 'Security') { + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message 'This setting cannot be set on a security group.' -Sev 'Error' return "$GroupType's group cannot have this setting changed" } - - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "$Id set to allow messages from people $messageSuffix" -Sev "Info" + + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "$Id set to allow messages from people $messageSuffix" -Sev 'Info' return "Set $GroupType group $Id to allow messages from people $messageSuffix" - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Delivery Management failed: $($_.Exception.Message)" -Sev "Error" - return "Failed. $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Delivery Management failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + return "Failed. $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPGroupGAL.ps1 b/Modules/CIPPCore/Public/Set-CIPPGroupGAL.ps1 index aec510dfe806..0da6ddf798a6 100644 --- a/Modules/CIPPCore/Public/Set-CIPPGroupGAL.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPGroupGAL.ps1 @@ -1,25 +1,29 @@ function Set-CIPPGroupGAL( [string]$ExecutingUser, - [string]$GroupType, - [string]$Id, - [string]$HiddenString, + [string]$GroupType, + [string]$Id, + [string]$HiddenString, [string]$TenantFilter, - [string]$APIName = "Group GAL Status" + [string]$APIName = 'Group GAL Status' ) { - $Hidden = if ($HiddenString -eq 'true') { "true" } else { "false" } - $messageSuffix = if ($Hidden -eq 'true') { "hidden" } else { "unhidden" } + $Hidden = if ($HiddenString -eq 'true') { 'true' } else { 'false' } + $messageSuffix = if ($Hidden -eq 'true') { 'hidden' } else { 'unhidden' } - if ($GroupType -eq "Distribution List" -or $GroupType -eq "Mail-Enabled Security") { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-DistributionGroup" -cmdParams @{Identity = $Id; HiddenFromAddressListsEnabled = $Hidden } - } - elseif ($GroupType -eq "Microsoft 365") { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-UnifiedGroup" -cmdParams @{Identity = $Id; HiddenFromAddressListsEnabled = $Hidden } - } - elseif ($GroupType -eq "Security") { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "This setting cannot be set on a security group." -Sev "Error" - return "$GroupType's group cannot have this setting changed" + try { + if ($GroupType -eq 'Distribution List' -or $GroupType -eq 'Mail-Enabled Security') { + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-DistributionGroup' -cmdParams @{Identity = $Id; HiddenFromAddressListsEnabled = $Hidden } + } elseif ($GroupType -eq 'Microsoft 365') { + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-UnifiedGroup' -cmdParams @{Identity = $Id; HiddenFromAddressListsEnabled = $Hidden } + } elseif ($GroupType -eq 'Security') { + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message 'This setting cannot be set on a security group.' -Sev 'Error' + return "$GroupType's group cannot have this setting changed" + } + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "$Id $messageSuffix from GAL failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + return "Failed. $($ErrorMessage.NormalizedError)" } - - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "$Id $messageSuffix from GAL" -Sev "Info" + + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "$Id $messageSuffix from GAL" -Sev 'Info' return "Successfully $messageSuffix $GroupType group $Id from GAL." } diff --git a/Modules/CIPPCore/Public/Set-CIPPHideFromGAL.ps1 b/Modules/CIPPCore/Public/Set-CIPPHideFromGAL.ps1 index 31daa7020fd4..13c70a474602 100644 --- a/Modules/CIPPCore/Public/Set-CIPPHideFromGAL.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPHideFromGAL.ps1 @@ -3,18 +3,18 @@ function Set-CIPPHideFromGAL { param ( $userid, $tenantFilter, - $APIName = "Hide From Address List", + $APIName = 'Hide From Address List', [bool]$HideFromGAL, $ExecutingUser ) - $Text = if ($HideFromGAL) { "hidden" } else { "unhidden" } + $Text = if ($HideFromGAL) { 'hidden' } else { 'unhidden' } try { - $Request = New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-mailbox" -cmdParams @{Identity = $userid ; HiddenFromAddressListsEnabled = $HideFromGAL } - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantfilter) -message "$($userid) $Text from GAL" -Sev "Info" + $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-mailbox' -cmdParams @{Identity = $userid ; HiddenFromAddressListsEnabled = $HideFromGAL } + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantfilter) -message "$($userid) $Text from GAL" -Sev 'Info' return "Successfully $Text $($userid) from GAL." - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not hide $($userid) from address list" -Sev "Error" -tenant $TenantFilter - return "Could not hide $($userid) from address list. Error: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not hide $($userid) from address list. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not hide $($userid) from address list. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPIntunePolicy.ps1 b/Modules/CIPPCore/Public/Set-CIPPIntunePolicy.ps1 index 45ffd9fad2e1..cb05c24df99f 100644 --- a/Modules/CIPPCore/Public/Set-CIPPIntunePolicy.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPIntunePolicy.ps1 @@ -121,8 +121,9 @@ function Set-CIPPIntunePolicy { } "Successfully $($PostType) policy for $($tenantFilter) with display name $($Displayname)" } catch { - "Failed to add or set policy for $($tenantFilter) with display name $($Displayname): $($_.Exception.Message)" - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantFilter) -message "Failed $($PostType) policy $($Displayname). Error: $($_.Exception.Message)" -Sev 'Error' + $ErrorMessage = Get-CippException -Exception $_ + "Failed to add or set policy for $($tenantFilter) with display name $($Displayname): $($ErrorMessage.NormalizedError)" + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantFilter) -message "Failed $($PostType) policy $($Displayname). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage continue } diff --git a/Modules/CIPPCore/Public/Set-CIPPIntuneTemplate.ps1 b/Modules/CIPPCore/Public/Set-CIPPIntuneTemplate.ps1 index 65f40a06449d..b216c5b56672 100644 --- a/Modules/CIPPCore/Public/Set-CIPPIntuneTemplate.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPIntuneTemplate.ps1 @@ -8,8 +8,8 @@ function Set-CIPPIntuneTemplate { $templateType ) - if (!$DisplayName) { throw "You must enter a displayname" } - if ($null -eq ($RawJSON | ConvertFrom-Json)) { throw "the JSON is invalid" } + if (!$DisplayName) { throw 'You must enter a displayname' } + if ($null -eq ($RawJSON | ConvertFrom-Json)) { throw 'the JSON is invalid' } $object = [PSCustomObject]@{ Displayname = $DisplayName @@ -24,9 +24,9 @@ function Set-CIPPIntuneTemplate { JSON = "$object" RowKey = "$GUID" GUID = "$GUID" - PartitionKey = "IntuneTemplate" + PartitionKey = 'IntuneTemplate' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created intune policy template named $($Request.body.displayname) with GUID $GUID" -Sev "Debug" + Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Created intune policy template named $($Request.body.displayname) with GUID $GUID" -Sev 'Debug' - return "Successfully added template" + return 'Successfully added template' } diff --git a/Modules/CIPPCore/Public/Set-CIPPMailboxAccess.ps1 b/Modules/CIPPCore/Public/Set-CIPPMailboxAccess.ps1 index f19762545ac1..e9efdf9eaa10 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMailboxAccess.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMailboxAccess.ps1 @@ -5,25 +5,24 @@ function Set-CIPPMailboxAccess { $AccessUser, [bool]$Automap, $TenantFilter, - $APIName = "Manage Shared Mailbox Access", + $APIName = 'Manage Shared Mailbox Access', $ExecutingUser, [array]$AccessRights ) try { - $permissions = New-ExoRequest -tenantid $TenantFilter -cmdlet "Add-MailboxPermission" -cmdParams @{Identity = $userid; user = $AccessUser; automapping = $Automap; accessRights = $AccessRights; InheritanceType = "all" } -Anchor $userid - + $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Add-MailboxPermission' -cmdParams @{Identity = $userid; user = $AccessUser; automapping = $Automap; accessRights = $AccessRights; InheritanceType = 'all' } -Anchor $userid + if ($Automap) { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Gave $AccessRights permissions to $($AccessUser) on $($userid) with automapping" -Sev "Info" -tenant $TenantFilter + Write-LogMessage -user $ExecutingUser -API $APIName -message "Gave $AccessRights permissions to $($AccessUser) on $($userid) with automapping" -Sev 'Info' -tenant $TenantFilter return "added $($AccessUser) to $($userid) Shared Mailbox with automapping, with the following permissions: $AccessRights" - } - else { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Gave $AccessRights permissions to $($AccessUser) on $($userid) without automapping" -Sev "Info" -tenant $TenantFilter + } else { + Write-LogMessage -user $ExecutingUser -API $APIName -message "Gave $AccessRights permissions to $($AccessUser) on $($userid) without automapping" -Sev 'Info' -tenant $TenantFilter return "added $($AccessUser) to $($userid) Shared Mailbox without automapping, with the following permissions: $AccessRights" } - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add mailbox permissions for $($AccessUser) on $($userid)" -Sev "Error" -tenant $TenantFilter - return "Could not add shared mailbox permissions for $($userid). Error: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add mailbox permissions for $($AccessUser) on $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not add shared mailbox permissions for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPMailboxArchive.ps1 b/Modules/CIPPCore/Public/Set-CIPPMailboxArchive.ps1 index 8ab1795e7fb5..0df033a87d15 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMailboxArchive.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMailboxArchive.ps1 @@ -4,19 +4,21 @@ function Set-CIPPMailboxArchive { $ExecutingUser, $userid, $username, - $APIName = "Mailbox Archive", + $APIName = 'Mailbox Archive', $TenantFilter, [bool]$ArchiveEnabled ) + $User = $request.headers.'x-ms-client-principal-name' + Try { if (!$username) { $username = $userid } - New-ExoRequest -tenantid $TenantFilter -cmdlet "Enable-Mailbox" -cmdParams @{Identity = $userid; Archive = $ArchiveEnabled } + $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Enable-Mailbox' -cmdParams @{Identity = $userid; Archive = $ArchiveEnabled } "Successfully set archive for $username to $ArchiveEnabled" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Successfully set archive for $username to $ArchiveEnabled" -Sev "Info" - } - catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $($tenantfilter) -message "Failed to set archive $($_.Exception.Message)" -Sev "Error" - "Failed. $($_.Exception.Message)" + Write-LogMessage -user $User -API $APINAME -tenant $($tenantfilter) -message "Successfully set archive for $username to $ArchiveEnabled" -Sev 'Info' + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -tenant $($tenantfilter) -message "Failed to set archive for $username. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + "Failed. $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPMailboxType.ps1 b/Modules/CIPPCore/Public/Set-CIPPMailboxType.ps1 index 03fc1236f269..fdde77d25a09 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMailboxType.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMailboxType.ps1 @@ -4,20 +4,20 @@ function Set-CIPPMailboxType { $ExecutingUser, $userid, $username, - $APIName = "Mailbox Conversion", + $APIName = 'Mailbox Conversion', $TenantFilter, [Parameter()] - [ValidateSet('shared', 'Regular', 'Room', 'Equipment')]$MailboxType + [ValidateSet('Shared', 'Regular', 'Room', 'Equipment')]$MailboxType ) try { - $Mailbox = New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-mailbox" -cmdParams @{Identity = $userid; type = $MailboxType } -Anchor $username - Write-LogMessage -user $ExecutingUser -API $APIName -message "Converted $($username) to a $MailboxType mailbox" -Sev "Info" -tenant $TenantFilter + $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-mailbox' -cmdParams @{Identity = $userid; type = $MailboxType } -Anchor $username + Write-LogMessage -user $ExecutingUser -API $APIName -message "Converted $($username) to a $MailboxType mailbox" -Sev 'Info' -tenant $TenantFilter if (!$username) { $username = $userid } return "Converted $($username) to a $MailboxType mailbox" - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not convert $username to $MailboxType mailbox" -Sev "Error" -tenant $TenantFilter - return "Could not convert $($username) to a $MailboxType mailbox. Error: $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not convert $username to $MailboxType mailbox. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not convert $($username) to a $MailboxType mailbox. Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPMessageCopy.ps1 b/Modules/CIPPCore/Public/Set-CIPPMessageCopy.ps1 index 745c138bebae..dae07baf9bf4 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMessageCopy.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMessageCopy.ps1 @@ -4,16 +4,16 @@ function Set-CIPPMessageCopy { $userid, $MessageCopyForSentAsEnabled, $TenantFilter, - $APIName = "Manage OneDrive Access", + $APIName = 'Manage OneDrive Access', $ExecutingUser ) Try { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-mailbox" -cmdParams @{Identity = $userid; MessageCopyForSentAsEnabled = $MessageCopyForSentAsEnabled } - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantfilter) -message "Successfully set MessageCopyForSentAsEnabled as $MessageCopyForSentAsEnabled on $($userid)." -Sev "Info" + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $userid; MessageCopyForSentAsEnabled = $MessageCopyForSentAsEnabled } + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantfilter) -message "Successfully set MessageCopyForSentAsEnabled as $MessageCopyForSentAsEnabled on $($userid)." -Sev 'Info' return "Successfully set MessageCopyForSentAsEnabled as $MessageCopyForSentAsEnabled on $($userid)." + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantfilter) -message "set MessageCopyForSentAsEnabled to $MessageCopyForSentAsEnabled failed: $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + return "set MessageCopyForSentAsEnabled to $MessageCopyForSentAsEnabled failed - $($ErrorMessage.NormalizedError)" } - catch { - Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $($tenantfilter) -message "set MessageCopyForSentAsEnabled to $MessageCopyForSentAsEnabled failed: $($_.Exception.Message)" -Sev "Error" - return "set MessageCopyForSentAsEnabled to $MessageCopyForSentAsEnabled failed - $($_.Exception.Message)" - } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Set-CIPPMobileDevice.ps1 b/Modules/CIPPCore/Public/Set-CIPPMobileDevice.ps1 index f3a3392eeb75..830a02cd2564 100644 --- a/Modules/CIPPCore/Public/Set-CIPPMobileDevice.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPMobileDevice.ps1 @@ -6,41 +6,39 @@ function Set-CIPPMobileDevice( [string]$TenantFilter, [string]$Delete, [string]$Guid, - [string]$APIName = "Mobile Device" + [string]$APIName = 'Mobile Device' ) { - + try { - if ($Quarantine -eq "false") { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-CASMailbox" -cmdParams @{Identity = $UserId; ActiveSyncAllowedDeviceIDs = @{'@odata.type' = '#Exchange.GenericHashTable'; add = $DeviceId } } - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Allow Active Sync Device for $UserId" -Sev "Info" + if ($Quarantine -eq 'false') { + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-CASMailbox' -cmdParams @{Identity = $UserId; ActiveSyncAllowedDeviceIDs = @{'@odata.type' = '#Exchange.GenericHashTable'; add = $DeviceId } } + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Allow Active Sync Device for $UserId" -Sev 'Info' return "Allowed Active Sync Device for $UserId" - } - elseif ($Quarantine -eq "true") { - New-ExoRequest -tenantid $TenantFilter -cmdlet "Set-CASMailbox" -cmdParams @{Identity = $UserId; ActiveSyncBlockedDeviceIDs = @{'@odata.type' = '#Exchange.GenericHashTable'; add = $DeviceId } } - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Blocked Active Sync Device for $UserId" -Sev "Info" + } elseif ($Quarantine -eq 'true') { + New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-CASMailbox' -cmdParams @{Identity = $UserId; ActiveSyncBlockedDeviceIDs = @{'@odata.type' = '#Exchange.GenericHashTable'; add = $DeviceId } } + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Blocked Active Sync Device for $UserId" -Sev 'Info' return "Blocked Active Sync Device for $UserId" } - } - catch { + } catch { + $ErrorMessage = Get-CippException -Exception $_ if ($Quarantine -eq 'false') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to Allow Active Sync Device for $($UserId): $($_.Exception.Message)" -Sev "Error" - return "Failed to Allow Active Sync Device for $($UserId): $($_.Exception.Message)" - } - elseif ($Quarantine -eq 'true') { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to Block Active Sync Device for $($UserId): $($_.Exception.Message)" -Sev "Error" - return "Failed to Block Active Sync Device for $($UserId): $($_.Exception.Message)" + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to Allow Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + return "Failed to Allow Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" + } elseif ($Quarantine -eq 'true') { + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to Block Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + return "Failed to Block Active Sync Device for $($UserId): $($ErrorMessage.NormalizedError)" } } try { if ($Delete -eq 'true') { - New-ExoRequest -tenant $TenantFilter -cmdlet "Remove-MobileDevice" -cmdParams @{Identity = $Guid; Confirm = $false } -UseSystemMailbox $true - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Deleted Active Sync Device for $UserId" -Sev "Info" + New-ExoRequest -tenant $TenantFilter -cmdlet 'Remove-MobileDevice' -cmdParams @{Identity = $Guid; Confirm = $false } -UseSystemMailbox $true + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Deleted Active Sync Device for $UserId" -Sev 'Info' return "Deleted Active Sync Device for $UserId" } - } - catch { - Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to delete Mobile Device $($Guid): $($_.Exception.Message)" -Sev "Error" - return "Failed to delete Mobile Device $($Guid): $($_.Exception.Message)" + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -tenant $TenantFilter -message "Failed to delete Mobile Device $($Guid): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage + return "Failed to delete Mobile Device $($Guid): $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPOutOfoffice.ps1 b/Modules/CIPPCore/Public/Set-CIPPOutOfoffice.ps1 index ee1266ca949d..116c503486c1 100644 --- a/Modules/CIPPCore/Public/Set-CIPPOutOfoffice.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPOutOfoffice.ps1 @@ -20,16 +20,17 @@ function Set-CIPPOutOfOffice { $EndTime = (Get-Date $StartTime).AddDays(7) } if ($State -ne 'Scheduled') { - $OutOfOffice = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-MailboxAutoReplyConfiguration' -cmdParams @{Identity = $userid; AutoReplyState = $State; InternalMessage = $InternalMessage; ExternalMessage = $ExternalMessage } -Anchor $userid + $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-MailboxAutoReplyConfiguration' -cmdParams @{Identity = $userid; AutoReplyState = $State; InternalMessage = $InternalMessage; ExternalMessage = $ExternalMessage } -Anchor $userid Write-LogMessage -user $ExecutingUser -API $APIName -message "Set Out-of-office for $($userid) to $state" -Sev 'Info' -tenant $TenantFilter return "Set Out-of-office for $($userid) to $state." } else { - $OutOfOffice = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-MailboxAutoReplyConfiguration' -cmdParams @{Identity = $userid; AutoReplyState = $State; InternalMessage = $InternalMessage; ExternalMessage = $ExternalMessage; StartTime = $StartTime; EndTime = $EndTime } -Anchor $userid + $null = New-ExoRequest -tenantid $TenantFilter -cmdlet 'Set-MailboxAutoReplyConfiguration' -cmdParams @{Identity = $userid; AutoReplyState = $State; InternalMessage = $InternalMessage; ExternalMessage = $ExternalMessage; StartTime = $StartTime; EndTime = $EndTime } -Anchor $userid Write-LogMessage -user $ExecutingUser -API $APIName -message "Scheduled Out-of-office for $($userid) between $StartTime and $EndTime" -Sev 'Info' -tenant $TenantFilter return "Scheduled Out-of-office for $($userid) between $($StartTime.toString()) and $($EndTime.toString())" } } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid)" -Sev 'Error' -tenant $TenantFilter -LogData (Get-CippException -Exception $_) - return "Could not add out of office message for $($userid). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not add out of office message for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPPerUserMFA.ps1 b/Modules/CIPPCore/Public/Set-CIPPPerUserMFA.ps1 index f7f88a53fe11..f1fd6b5c2121 100644 --- a/Modules/CIPPCore/Public/Set-CIPPPerUserMFA.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPPerUserMFA.ps1 @@ -63,7 +63,8 @@ function Set-CIPPPerUserMFA { Set-CIPPUserSchemaProperties -TenantFilter $TenantFilter -Users $Users Write-LogMessage -user $executingUser -API 'Set-CIPPPerUserMFA' -message "Successfully set Per user MFA State to $State for $id" -Sev 'Info' -tenant $TenantFilter } catch { - "Failed to set MFA State for $id : $_" - Write-LogMessage -user $executingUser -API 'Set-CIPPPerUserMFA' -message "Failed to set MFA State to $State for $id : $_" -Sev 'Error' -tenant $TenantFilter + $ErrorMessage = Get-CippException -Exception $_ + "Failed to set MFA State for $id. Error: $($ErrorMessage.NormalizedError)" + Write-LogMessage -user $executingUser -API 'Set-CIPPPerUserMFA' -message "Failed to set MFA State to $State for $id. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Set-CIPPProfilePhoto.ps1 b/Modules/CIPPCore/Public/Set-CIPPProfilePhoto.ps1 index 5ea431302eec..fb829701390c 100644 --- a/Modules/CIPPCore/Public/Set-CIPPProfilePhoto.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPProfilePhoto.ps1 @@ -15,7 +15,8 @@ function Set-CIPPProfilePhoto { "Successfully set profile photo for $id" Write-LogMessage -user $executingUser -API 'Set-CIPPUserProfilePhoto' -message "Successfully set profile photo for $id" -Sev 'Info' -tenant $TenantFilter } catch { - "Failed to set profile photo for $id : $_" - Write-LogMessage -user $executingUser -API 'Set-CIPPUserProfilePhoto' -message "Failed to set profile photo for $id : $_" -Sev 'Error' -tenant $TenantFilter + $ErrorMessage = Get-CippException -Exception $_ + "Failed to set profile photo for $id. Error: $($ErrorMessage.NormalizedError)" + Write-LogMessage -user $executingUser -API 'Set-CIPPUserProfilePhoto' -message "Failed to set profile photo for $id. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Set-CIPPResetPassword.ps1 b/Modules/CIPPCore/Public/Set-CIPPResetPassword.ps1 index aff8463210be..e4d69e2c05d7 100644 --- a/Modules/CIPPCore/Public/Set-CIPPResetPassword.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPResetPassword.ps1 @@ -17,7 +17,8 @@ function Set-CIPPResetPassword { } } | ConvertTo-Json -Compress - $GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/users/$($userid)" -tenantid $TenantFilter -type PATCH -body $passwordProfile -verbose + $UserDetails = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$($UserId)?`$select=onPremisesSyncEnabled" -noPagination $true -tenantid $TenantFilter -verbose + $null = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/users/$($userid)" -tenantid $TenantFilter -type PATCH -body $passwordProfile -verbose #PWPush $PasswordLink = New-PwPushLink -Payload $password @@ -25,9 +26,15 @@ function Set-CIPPResetPassword { $password = $PasswordLink } Write-LogMessage -user $ExecutingUser -API $APIName -message "Reset the password for $($userid). User must change password is set to $forceChangePasswordNextSignIn" -Sev 'Info' -tenant $TenantFilter - return "Reset the password for $($userid). User must change password is set to $forceChangePasswordNextSignIn. The new password is $password" + + if($UserDetails.onPremisesSyncEnabled -eq $true){ + return "Reset the password for $($userid). User must change password is set to $forceChangePasswordNextSignIn. The new password is $password. WARNING: This user is AD synced. Please confirm passthrough or writeback is enabled." + }else{ + return "Reset the password for $($userid). User must change password is set to $forceChangePasswordNextSignIn. The new password is $password" + } } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not reset password for $($userid)" -Sev 'Error' -tenant $TenantFilter - return "Could not reset password for $($userid). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not reset password for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not reset password for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPSharePointPerms.ps1 b/Modules/CIPPCore/Public/Set-CIPPSharePointPerms.ps1 index d7c6419c32df..2a0a97be79a2 100644 --- a/Modules/CIPPCore/Public/Set-CIPPSharePointPerms.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPSharePointPerms.ps1 @@ -1,27 +1,27 @@ function Set-CIPPSharePointPerms { - [CmdletBinding()] - param ( - $userid, - $OnedriveAccessUser, - $TenantFilter, - $APIName = 'Manage SharePoint Owner', - $RemovePermission, - $ExecutingUser, - $URL - ) - if ($RemovePermission -eq $true) { - $SiteAdmin = 'false' - } else { - $SiteAdmin = 'true' - } - - try { - if (!$URL) { - $URL = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$($UserId)/Drives" -asapp $true -tenantid $TenantFilter).WebUrl + [CmdletBinding()] + param ( + $userid, + $OnedriveAccessUser, + $TenantFilter, + $APIName = 'Manage SharePoint Owner', + $RemovePermission, + $ExecutingUser, + $URL + ) + if ($RemovePermission -eq $true) { + $SiteAdmin = 'false' + } else { + $SiteAdmin = 'true' } - $tenantName = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/sites/root' -asApp $true -tenantid $TenantFilter).id.Split('.')[0] - $AdminUrl = "https://$($tenantName)-admin.sharepoint.com" - $XML = @" + + try { + if (!$URL) { + $URL = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$($UserId)/Drives" -asapp $true -tenantid $TenantFilter).WebUrl + } + $tenantName = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/sites/root' -asApp $true -tenantid $TenantFilter).id.Split('.')[0] + $AdminUrl = "https://$($tenantName)-admin.sharepoint.com" + $XML = @" @@ -38,19 +38,20 @@ function Set-CIPPSharePointPerms { "@ - $request = New-GraphPostRequest -scope "$AdminURL/.default" -tenantid $TenantFilter -Uri "$AdminURL/_vti_bin/client.svc/ProcessQuery" -Type POST -Body $XML -ContentType 'text/xml' - Write-Host $($request) - if (!$request.ErrorInfo.ErrorMessage) { - $Message = "$($OnedriveAccessUser) has been $($RemovePermission ? 'removed from' : 'given') access to $URL" - Write-LogMessage -user $ExecutingUser -API $APIName -message $Message -Sev 'Info' -tenant $TenantFilter - return $Message - } else { - $message = "Failed to change access: $($request.ErrorInfo.ErrorMessage)" - Write-LogMessage -user $ExecutingUser -API $APIName -message $message -Sev 'Info' -tenant $TenantFilter - return $message + $request = New-GraphPostRequest -scope "$AdminURL/.default" -tenantid $TenantFilter -Uri "$AdminURL/_vti_bin/client.svc/ProcessQuery" -Type POST -Body $XML -ContentType 'text/xml' + Write-Host $($request) + if (!$request.ErrorInfo.ErrorMessage) { + $Message = "$($OnedriveAccessUser) has been $($RemovePermission ? 'removed from' : 'given') access to $URL" + Write-LogMessage -user $ExecutingUser -API $APIName -message $Message -Sev 'Info' -tenant $TenantFilter + return $Message + } else { + $message = "Failed to change access: $($request.ErrorInfo.ErrorMessage)" + Write-LogMessage -user $ExecutingUser -API $APIName -message $message -Sev 'Info' -tenant $TenantFilter + return $message + } + } catch { + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add new owner to $($OnedriveAccessUser) on $URL. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not add owner for $($URL). Error: $($ErrorMessage.NormalizedError)" } - } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add new owner to $($OnedriveAccessUser) on $URL" -Sev 'Error' -tenant $TenantFilter - return "Could not add owner for $($URL). Error: $($_.Exception.Message)" - } } diff --git a/Modules/CIPPCore/Public/Set-CIPPSignInState.ps1 b/Modules/CIPPCore/Public/Set-CIPPSignInState.ps1 index 4c99b82c84df..5daf3173b974 100644 --- a/Modules/CIPPCore/Public/Set-CIPPSignInState.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPSignInState.ps1 @@ -13,12 +13,19 @@ function Set-CIPPSignInState { accountEnabled = [bool]$AccountEnabled } $body = ConvertTo-Json -InputObject $body -Compress -Depth 5 + $UserDetails = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/users/$($UserId)?`$select=onPremisesSyncEnabled" -noPagination $true -tenantid $TenantFilter -verbose $null = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/users/$($UserId)" -tenantid $TenantFilter -type PATCH -body $body -verbose Write-LogMessage -user $ExecutingUser -API $APIName -message "Set account enabled state to $AccountEnabled for $UserId" -Sev 'Info' -tenant $TenantFilter - return "Set account enabled state to $AccountEnabled for $UserId" + + if($UserDetails.onPremisesSyncEnabled -eq $true){ + return "WARNING: User is AD Sync enabled. Please enable/disable in AD." + }else{ + return "Set account enabled state to $AccountEnabled for $UserId" + } + } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not disable sign in for $UserId. Error: $($_.Exception.Message)" -Sev 'Error' -tenant $TenantFilter - return "Could not disable $UserId. Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not disable sign in for $UserId. Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not disable $UserId. Error: $($ErrorMessage.NormalizedError)" } } - diff --git a/Modules/CIPPCore/Public/Set-CIPPSignature.ps1 b/Modules/CIPPCore/Public/Set-CIPPSignature.ps1 index e3ad3c8dd83e..81a985bf6d36 100644 --- a/Modules/CIPPCore/Public/Set-CIPPSignature.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPSignature.ps1 @@ -16,12 +16,13 @@ function Set-CIPPSignature { $SignatureProfile = @' [{"name":"Roaming_New_Signature","itemClass":"","id":"","scope":"AdeleV@M365x42953883.OnMicrosoft.com","parentSetting":"","secondaryKey":"","type":"String","timestamp":638296273181532792,"metadata":"","value":"Kelvin","isFirstSync":"true","source":"UserOverride"}] '@ - $GraphRequest = New-GraphPostRequest -uri 'https://substrate.office.com/ows/beta/outlookcloudsettings/settings/global' -tenantid $TenantFilter -type PATCH -contentType 'application/json' -verbose -scope 'https://outlook.office.com/.default' + $null = New-GraphPostRequest -uri 'https://substrate.office.com/ows/beta/outlookcloudsettings/settings/global' -tenantid $TenantFilter -type PATCH -contentType 'application/json' -verbose -scope 'https://outlook.office.com/.default' Write-LogMessage -user $ExecutingUser -API $APIName -message "Set Out-of-office for $($userid) to $state" -Sev 'Info' -tenant $TenantFilter return "Set Out-of-office for $($userid) to $state." } catch { - Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid)" -Sev 'Error' -tenant $TenantFilter - return "Could not add out of office message for $($userid). Error: $($_.Exception.Message)" + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APIName -message "Could not add OOO for $($userid). Error: $($ErrorMessage.NormalizedError)" -Sev 'Error' -tenant $TenantFilter -LogData $ErrorMessage + return "Could not add out of office message for $($userid). Error: $($ErrorMessage.NormalizedError)" } } diff --git a/Modules/CIPPCore/Public/Set-CIPPUserJITAdmin.ps1 b/Modules/CIPPCore/Public/Set-CIPPUserJITAdmin.ps1 index dcb9e525bdc5..51da2f11d762 100644 --- a/Modules/CIPPCore/Public/Set-CIPPUserJITAdmin.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPUserJITAdmin.ps1 @@ -83,8 +83,9 @@ function Set-CIPPUserJITAdmin { password = $Password } } catch { - Write-Information "Error creating user: $($_.Exception.Message)" - throw $_.Exception.Message + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + Write-Information "Error creating user: $ErrorMessage" + throw $ErrorMessage } } 'AddRoles' { @@ -125,7 +126,8 @@ function Set-CIPPUserJITAdmin { $null = New-GraphPOSTRequest -type DELETE -uri "https://graph.microsoft.com/beta/users/$($UserObj.id)" -tenantid $TenantFilter return "Deleted user $($UserObj.displayName) ($($UserObj.userPrincipalName)) with id $($UserObj.id)" } catch { - return "Error deleting user $($UserObj.displayName) ($($UserObj.userPrincipalName)): $($_.Exception.Message)" + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + return "Error deleting user $($UserObj.displayName) ($($UserObj.userPrincipalName)): $ErrorMessage" } } 'DisableUser' { @@ -141,8 +143,9 @@ function Set-CIPPUserJITAdmin { Set-CIPPUserJITAdminProperties -TenantFilter $TenantFilter -UserId $User.UserPrincipalName -Clear | Out-Null return "Disabled user $($UserObj.displayName) ($($UserObj.userPrincipalName))" } catch { - $ErrrorMessage = Get-NormalizedError -Message $_.Exception.Message - return "Error disabling user $($UserObj.displayName) ($($UserObj.userPrincipalName)): $ErrrorMessage" + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + return "Error disabling user $($UserObj.displayName) ($($UserObj.userPrincipalName)): $ErrorMessage" + } } } diff --git a/Modules/CIPPCore/Public/Set-CIPPUserJITAdminProperties.ps1 b/Modules/CIPPCore/Public/Set-CIPPUserJITAdminProperties.ps1 index d9d3dfb8c9af..b4b2bd5fe88f 100644 --- a/Modules/CIPPCore/Public/Set-CIPPUserJITAdminProperties.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPUserJITAdminProperties.ps1 @@ -24,7 +24,7 @@ function Set-CIPPUserJITAdminProperties { } } } - + $Json = ConvertTo-Json -Depth 5 -InputObject $Body Write-Information $Json New-GraphPOSTRequest -type PATCH -Uri "https://graph.microsoft.com/beta/users/$UserId" -Body $Json -tenantid $TenantFilter | Out-Null diff --git a/Modules/CIPPCore/Public/Set-CIPPUserSchemaProperties.ps1 b/Modules/CIPPCore/Public/Set-CIPPUserSchemaProperties.ps1 index b006a27069ef..975bd401e179 100644 --- a/Modules/CIPPCore/Public/Set-CIPPUserSchemaProperties.ps1 +++ b/Modules/CIPPCore/Public/Set-CIPPUserSchemaProperties.ps1 @@ -43,4 +43,4 @@ function Set-CIPPUserSchemaProperties { if ($PSCmdlet.ShouldProcess("User: $($Users.userId -join ', ')", 'Set Schema Properties')) { $Requests = New-GraphBulkRequest -tenantid $tenantfilter -Requests @($Requests) } -} \ No newline at end of file +} diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardQuarantineRequestAlert.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardQuarantineRequestAlert.ps1 new file mode 100644 index 000000000000..18d829bc3915 --- /dev/null +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardQuarantineRequestAlert.ps1 @@ -0,0 +1,89 @@ +function Invoke-CIPPStandardQuarantineRequestAlert { + <# + .FUNCTIONALITY + Internal + .COMPONENT + (APIName) QuarantineRequestAlert + .SYNOPSIS + (Label) Quarantine Release Request Alert + .DESCRIPTION + (Helptext) Sets a e-mail address to alert when a User requests to release a quarantined message. + (DocsDescription) Sets a e-mail address to alert when a User requests to release a quarantined message. This is useful for monitoring and ensuring that the correct messages are released. + .NOTES + CAT + Defender Standards + TAG + "lowimpact" + ADDEDCOMPONENT + {"type":"input","name":"standards.QuarantineRequestAlert.NotifyUser","label":"E-mail to receive the alert"} + IMPACT + Low Impact + POWERSHELLEQUIVALENT + New-ProtectionAlert and Set-ProtectionAlert + RECOMMENDEDBY + UPDATECOMMENTBLOCK + Run the Tools\Update-StandardsComments.ps1 script to update this comment block + .LINK + https://docs.cipp.app/user-documentation/tenant/standards/edit-standards + #> + + param ($Tenant, $Settings) + $PolicyName = 'CIPP User requested to release a quarantined message' + + $CurrentState = New-ExoRequest -TenantId $Tenant -cmdlet 'Get-ProtectionAlert' -Compliance | + Where-Object { $_.Name -eq $PolicyName } | + Select-Object -Property * + + $StateIsCorrect = ($CurrentState.NotifyUser -contains $Settings.NotifyUser) + + if ($Settings.remediate -eq $true) { + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message 'Quarantine Request Alert is configured correctly' -sev Info + } else { + $cmdparams = @{ + 'NotifyUser' = $Settings.NotifyUser + 'Category' = 'ThreatManagement' + 'Operation' = 'QuarantineRequestReleaseMessage' + 'Severity' = 'Informational' + 'AggregationType' = 'None' + } + + if ($CurrentState.Name -eq $PolicyName) { + try { + $cmdparams += @{ + 'Identity' = $PolicyName + } + New-ExoRequest -TenantId $Tenant -cmdlet 'Set-ProtectionAlert' -Compliance -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message 'Successfully configured Quarantine Request Alert' -sev Info + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message "Failed to configure Quarantine Request Alert. Error: $ErrorMessage" -sev Error + } + } else { + try { + $cmdparams += @{ + 'Name' = $PolicyName + 'ThreatType' = 'Activity' + } + New-ExoRequest -TenantId $Tenant -cmdlet 'New-ProtectionAlert' -Compliance -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message 'Successfully created Quarantine Request Alert' -sev Info + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message "Failed to create Quarantine Request Alert. Error: $ErrorMessage" -sev Error + } + } + } + } + + if ($Settings.alert -eq $true) { + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message 'Quarantine Request Alert is enabled' -sev Info + } else { + Write-LogMessage -API 'Standards' -Tenant $Tenant -Message 'Quarantine Request Alert is disabled' -sev Info + } + } + + if ($Settings.report -eq $true) { + Add-CIPPBPAField -FieldName 'QuarantineRequestAlert' -FieldValue $StateIsCorrect -StoreAs bool -Tenant $Tenant + } +} diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSPDisableLegacyWorkflows.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSPDisableLegacyWorkflows.ps1 new file mode 100644 index 000000000000..a01122e3c188 --- /dev/null +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSPDisableLegacyWorkflows.ps1 @@ -0,0 +1,67 @@ +function Invoke-CIPPStandardSPDisableLegacyWorkflows { + <# + .FUNCTIONALITY + Internal + .COMPONENT + (APIName) SPDisableLegacyWorkflows + .SYNOPSIS + (Label) Disable Legacy Workflows + .DESCRIPTION + (Helptext) Disables the creation of new SharePoint 2010 and 2013 classic workflows and removes the 'Return to classic SharePoint' link on modern SharePoint list and library pages. + (DocsDescription) Disables the creation of new SharePoint 2010 and 2013 classic workflows and removes the 'Return to classic SharePoint' link on modern SharePoint list and library pages. + .NOTES + CAT + SharePoint Standards + TAG + "lowimpact" + ADDEDCOMPONENT + IMPACT + Low Impact + POWERSHELLEQUIVALENT + Set-SPOTenant -DisableWorkflow2010 $true -DisableWorkflow2013 $true -DisableBackToClassic $true + RECOMMENDEDBY + UPDATECOMMENTBLOCK + Run the Tools\Update-StandardsComments.ps1 script to update this comment block + .LINK + https://docs.cipp.app/user-documentation/tenant/standards/edit-standards + #> + param($Tenant, $Settings) + $CurrentState = Get-CIPPSPOTenant -TenantFilter $Tenant | + Select-Object -Property * + + $StateIsCorrect = ($CurrentState.StopNew2010Workflows -eq $true) -and + ($CurrentState.StopNew2013Workflows -eq $true) -and + ($CurrentState.DisableBackToClassic -eq $true) + + if ($Settings.remediate -eq $true) { + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -Message 'Legacy Workflows are already disabled.' -Sev Info + } else { + $Properties = @{ + StopNew2010Workflows = $true + StopNew2013Workflows = $true + DisableBackToClassic = $true + } + + try { + Get-CIPPSPOTenant -TenantFilter $Tenant | Set-CIPPSPOTenant -Properties $Properties + Write-LogMessage -API 'Standards' -Message 'Successfully disabled Legacy Workflows' -Sev Info + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + Write-LogMessage -API 'Standards' -Message "Failed to disable Legacy Workflows. Error: $ErrorMessage" -Sev Error + } + } + } + + if ($Settings.alert -eq $true) { + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -Message 'Legacy Workflows are disabled' -Sev Info + } else { + Write-LogMessage -API 'Standards' -Message 'Legacy Workflows are enabled' -Sev Info + } + } + + if ($Settings.report -eq $true) { + Add-CIPPBPAField -FieldName 'SPDisableLegacyWorkflows' -FieldValue $StateIsCorrect -StoreAs bool -Tenant $Tenant + } +} diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSpamFilterPolicy.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSpamFilterPolicy.ps1 new file mode 100644 index 000000000000..4357e0ae7ba0 --- /dev/null +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardSpamFilterPolicy.ps1 @@ -0,0 +1,171 @@ +function Invoke-CIPPStandardSpamFilterPolicy { + <# + .FUNCTIONALITY + Internal + .COMPONENT + (APIName) SpamFilterPolicy + .SYNOPSIS + (Label) Default Spam Filter Policy + .DESCRIPTION + (Helptext) This standard creates a Spam filter policy similar to the default strict policy. + (DocsDescription) This standard creates a Spam filter policy similar to the default strict policy. + .NOTES + CAT + Defender Standards + TAG + "mediumimpact" + ADDEDCOMPONENT + {"type":"Select","label":"Spam Action","name":"standards.SpamFilterPolicy.SpamAction","values":[{"label":"Move message to Junk Email folder","value":"MoveToJmf"},{"label":"Quarantine the message","value":"Quarantine"}]} + {"type":"Select","label":"Spam Quarantine Tag","name":"standards.SpamFilterPolicy.SpamQuarantineTag","values":[{"label":"AdminOnlyAccessPolicy","value":"AdminOnlyAccessPolicy"},{"label":"DefaultFullAccessPolicy","value":"DefaultFullAccessPolicy"},{"label":"DefaultFullAccessWithNotificationPolicy","value":"DefaultFullAccessWithNotificationPolicy"}]} + {"type":"Select","label":"High Confidence Spam Quarantine Tag","name":"standards.SpamFilterPolicy.HighConfidenceSpamQuarantineTag","values":[{"label":"AdminOnlyAccessPolicy","value":"AdminOnlyAccessPolicy"},{"label":"DefaultFullAccessPolicy","value":"DefaultFullAccessPolicy"},{"label":"DefaultFullAccessWithNotificationPolicy","value":"DefaultFullAccessWithNotificationPolicy"}]} + {"type":"Select","label":"Bulk Quarantine Tag","name":"standards.SpamFilterPolicy.BulkQuarantineTag","values":[{"label":"AdminOnlyAccessPolicy","value":"AdminOnlyAccessPolicy"},{"label":"DefaultFullAccessPolicy","value":"DefaultFullAccessPolicy"},{"label":"DefaultFullAccessWithNotificationPolicy","value":"DefaultFullAccessWithNotificationPolicy"}]} + {"type":"Select","label":"Phish Quarantine Tag","name":"standards.SpamFilterPolicy.PhishQuarantineTag","values":[{"label":"AdminOnlyAccessPolicy","value":"AdminOnlyAccessPolicy"},{"label":"DefaultFullAccessPolicy","value":"DefaultFullAccessPolicy"},{"label":"DefaultFullAccessWithNotificationPolicy","value":"DefaultFullAccessWithNotificationPolicy"}]} + {"type":"Select","label":"High Confidence Phish Quarantine Tag","name":"standards.SpamFilterPolicy.HighConfidencePhishQuarantineTag","values":[{"label":"AdminOnlyAccessPolicy","value":"AdminOnlyAccessPolicy"},{"label":"DefaultFullAccessPolicy","value":"DefaultFullAccessPolicy"},{"label":"DefaultFullAccessWithNotificationPolicy","value":"DefaultFullAccessWithNotificationPolicy"}]} + IMPACT + Medium Impact + POWERSHELLEQUIVALENT + New-HostedContentFilterPolicy or Set-HostedContentFilterPolicy + RECOMMENDEDBY + UPDATECOMMENTBLOCK + Run the Tools\Update-StandardsComments.ps1 script to update this comment block + .LINK + https://docs.cipp.app/user-documentation/tenant/standards/edit-standards + #> + + param($Tenant, $Settings) + $PolicyName = 'CIPP Default Spam Filter Policy' + + $CurrentState = New-ExoRequest -TenantId $Tenant -cmdlet 'Get-HostedContentFilterPolicy' | + Where-Object -Property Name -EQ $PolicyName | + Select-Object -Property * + + $StateIsCorrect = ($CurrentState.Name -eq $PolicyName) -and + ($CurrentState.HighConfidenceSpamAction -eq 'Quarantine') -and + ($CurrentState.HighConfidenceSpamQuarantineTag -eq $Settings.HighConfidenceSpamQuarantineTag) -and + ($CurrentState.SpamAction -eq $Settings.SpamAction) -and + ($CurrentState.SpamQuarantineTag -eq $Settings.SpamQuarantineTag) -and + ($CurrentState.PhishSpamAction -eq 'MoveToJmf') -and + ($CurrentState.BulkSpamAction -eq 'MoveToJmf') -and + ($CurrentState.BulkQuarantineTag -eq $Settings.BulkQuarantineTag) -and + ($CurrentState.PhishQuarantineTag -eq $Settings.PhishQuarantineTag) -and + ($CurrentState.HighConfidencePhishAction -eq 'Quarantine') -and + ($CurrentState.HighConfidencePhishQuarantineTag -eq $Settings.HighConfidencePhishQuarantineTag) -and + ($CurrentState.BulkThreshold -eq 7) -and + ($CurrentState.QuarantineRetentionPeriod -eq 30) -and + ($CurrentState.IncreaseScoreWithNumericIps -eq 'On') -and + ($CurrentState.IncreaseScoreWithRedirectToOtherPort -eq 'On') -and + ($CurrentState.MarkAsSpamEmptyMessages -eq 'On') -and + ($CurrentState.MarkAsSpamJavaScriptInHtml -eq 'On') -and + ($CurrentState.MarkAsSpamSpfRecordHardFail -eq 'On') -and + ($CurrentState.MarkAsSpamFromAddressAuthFail -eq 'On') -and + ($CurrentState.MarkAsSpamNdrBackscatter -eq 'On') -and + ($CurrentState.MarkAsSpamBulkMail -eq 'On') -and + ($CurrentState.InlineSafetyTipsEnabled -eq $true) -and + ($CurrentState.PhishZapEnabled -eq $true) -and + ($CurrentState.SpamZapEnabled -eq $true) + + $AcceptedDomains = New-ExoRequest -TenantId $Tenant -cmdlet 'Get-AcceptedDomain' + + $RuleState = New-ExoRequest -TenantId $Tenant -cmdlet 'Get-HostedContentFilterRule' | + Where-Object -Property Name -EQ $PolicyName | + Select-Object -Property * + + $RuleStateIsCorrect = ($RuleState.Name -eq $PolicyName) -and + ($RuleState.HostedContentFilterPolicy -eq $PolicyName) -and + ($RuleState.Priority -eq 0) -and + (!(Compare-Object -ReferenceObject $RuleState.RecipientDomainIs -DifferenceObject $AcceptedDomains.Name)) + + if ($Settings.remediate -eq $true) { + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -Tenant $Tenant -message 'Spam Filter Policy already correctly configured' -sev Info + } else { + $cmdparams = @{ + HighConfidenceSpamAction = 'Quarantine' + HighConfidenceSpamQuarantineTag = $Settings.HighConfidenceSpamQuarantineTag + SpamAction = $Settings.SpamAction + SpamQuarantineTag = $Settings.SpamQuarantineTag + PhishSpamAction = 'MoveToJmf' + BulkSpamAction = 'MoveToJmf' + BulkQuarantineTag = $Settings.BulkQuarantineTag + PhishQuarantineTag = $Settings.PhishQuarantineTag + HighConfidencePhishAction = 'Quarantine' + HighConfidencePhishQuarantineTag = $Settings.HighConfidencePhishQuarantineTag + BulkThreshold = 7 + QuarantineRetentionPeriod = 30 + IncreaseScoreWithNumericIps = 'On' + IncreaseScoreWithRedirectToOtherPort= 'On' + MarkAsSpamEmptyMessages = 'On' + MarkAsSpamJavaScriptInHtml = 'On' + MarkAsSpamSpfRecordHardFail = 'On' + MarkAsSpamFromAddressAuthFail = 'On' + MarkAsSpamNdrBackscatter = 'On' + MarkAsSpamBulkMail = 'On' + InlineSafetyTipsEnabled = $true + PhishZapEnabled = $true + SpamZapEnabled = $true + } + + if ($CurrentState.Name -eq $PolicyName) { + try { + $cmdparams.Add('Identity', $PolicyName) + New-ExoRequest -TenantId $Tenant -cmdlet 'Set-HostedContentFilterPolicy' -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -Tenant $Tenant -message 'Updated Spam Filter Policy' -sev Info + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + Write-LogMessage -API 'Standards' -Tenant $Tenant -message "Failed to update Spam Filter Policy. Error: $ErrorMessage" -sev Error + } + } else { + try { + $cmdparams.Add('Name', $PolicyName) + New-ExoRequest -TenantId $Tenant -cmdlet 'New-HostedContentFilterPolicy' -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -Tenant $Tenant -message 'Created Spam Filter Policy' -sev Info + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + Write-LogMessage -API 'Standards' -Tenant $Tenant -message "Failed to create Spam Filter Policy. Error: $ErrorMessage" -sev Error + } + } + } + + if ($RuleStateIsCorrect -eq $false) { + $cmdparams = @{ + HostedContentFilterPolicy = $PolicyName + Priority = 0 + RecipientDomainIs = $AcceptedDomains.Name + } + + if ($RuleState.Name -eq $PolicyName) { + try { + $cmdparams.Add('Identity', "$PolicyName") + New-ExoRequest -TenantId $Tenant -cmdlet 'Set-HostedContentFilterRule' -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -Tenant $Tenant -message 'Updated Spam Filter Rule' -sev Info + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + Write-LogMessage -API 'Standards' -Tenant $Tenant -message "Failed to update Spam Filter Rule. Error: $ErrorMessage" -sev Error + } + } else { + try { + $cmdparams.Add('Name', "$PolicyName") + New-ExoRequest -TenantId $Tenant -cmdlet 'New-HostedContentFilterRule' -cmdparams $cmdparams -UseSystemMailbox $true + Write-LogMessage -API 'Standards' -Tenant $Tenant -message 'Created Spam Filter Rule' -sev Info + } catch { + $ErrorMessage = Get-NormalizedError -Message $_.Exception.Message + Write-LogMessage -API 'Standards' -Tenant $Tenant -message "Failed to create Spam Filter Rule. Error: $ErrorMessage" -sev Error + } + } + } + } + + if ($Settings.alert -eq $true) { + + if ($StateIsCorrect -eq $true) { + Write-LogMessage -API 'Standards' -Tenant $Tenant -message 'Spam Filter Policy is enabled' -sev Info + } else { + Write-LogMessage -API 'Standards' -Tenant $Tenant -message 'Spam Filter Policy is not enabled' -sev Alert + } + } + + if ($Settings.report -eq $true) { + Add-CIPPBPAField -FieldName 'SpamFilterPolicy' -FieldValue $StateIsCorrect -StoreAs bool -Tenant $tenant + } + +} diff --git a/Modules/CIPPCore/Public/Test-CIPPAccessPermissions.ps1 b/Modules/CIPPCore/Public/Test-CIPPAccessPermissions.ps1 index f8a83a85bcaf..68709c2fac10 100644 --- a/Modules/CIPPCore/Public/Test-CIPPAccessPermissions.ps1 +++ b/Modules/CIPPCore/Public/Test-CIPPAccessPermissions.ps1 @@ -5,7 +5,9 @@ function Test-CIPPAccessPermissions { $APIName = 'Access Check', $ExecutingUser ) - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Started permissions check' -Sev 'Debug' + + $User = $request.headers.'x-ms-client-principal-name' + Write-LogMessage -user $User -API $APINAME -message 'Started permissions check' -Sev 'Debug' $Messages = [System.Collections.Generic.List[string]]::new() $ErrorMessages = [System.Collections.Generic.List[string]]::new() $MissingPermissions = [System.Collections.Generic.List[string]]::new() @@ -52,18 +54,20 @@ function Test-CIPPAccessPermissions { $Messages.Add('Your refresh token matches key vault.') | Out-Null } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Key vault exception: $($_) " -Sev 'Error' + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -tenant $tenant -message "Key vault exception: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } try { $AccessTokenDetails = Read-JwtAccessDetails -Token $GraphToken.access_token -erroraction SilentlyContinue } catch { + $ErrorMessage = Get-CippException -Exception $_ $AccessTokenDetails = [PSCustomObject]@{ Name = '' AuthMethods = @() } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Token exception: $($_) " -Sev 'Error' + Write-LogMessage -user $User -API $APINAME -tenant $tenant -message "Token exception: $($ErrorMessage.NormalizedError_) " -Sev 'Error' -LogData $ErrorMessage $Success = $false Write-Host 'Setting success to false due to not able to decode token.' @@ -108,8 +112,9 @@ function Test-CIPPAccessPermissions { } } catch { - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Permissions check failed: $($_) " -Sev 'Error' - $ErrorMessages.Add("We could not connect to the API to retrieve the permissions. There might be a problem with the secure application model configuration. The returned error is: $(Get-NormalizedError -message $_)") | Out-Null + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $User -API $APINAME -message "Permissions check failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage + $ErrorMessages.Add("We could not connect to the API to retrieve the permissions. There might be a problem with the secure application model configuration. The returned error is: $($ErrorMessage.NormalizedError)") | Out-Null Write-Host 'Setting success to False due to not being able to connect.' $Success = $false diff --git a/Modules/CIPPCore/Public/Test-CIPPAccessTenant.ps1 b/Modules/CIPPCore/Public/Test-CIPPAccessTenant.ps1 index 842b4f4b66aa..3cce53bebe39 100644 --- a/Modules/CIPPCore/Public/Test-CIPPAccessTenant.ps1 +++ b/Modules/CIPPCore/Public/Test-CIPPAccessTenant.ps1 @@ -68,34 +68,36 @@ function Test-CIPPAccessTenant { GDAPRoles = $GDAPRoles MissingRoles = $MissingRoles } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message 'Tenant access check executed successfully' -Sev 'Info' + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $tenant -message 'Tenant access check executed successfully' -Sev 'Info' } catch { + $ErrorMessage = Get-CippException -Exception $_ @{ TenantName = "$($tenant)" - Status = "Failed to connect: $(Get-NormalizedError -message $_.Exception.Message)" + Status = "Failed to connect: $($ErrorMessage.NormalizedError)" GDAP = '' } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Tenant access check failed: $(Get-NormalizedError -message $_) " -Sev 'Error' + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $tenant -message "Tenant access check failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } try { - $GraphRequest = New-ExoRequest -tenantid $Tenant -cmdlet 'Get-OrganizationConfig' -ErrorAction Stop + $null = New-ExoRequest -tenantid $Tenant -cmdlet 'Get-OrganizationConfig' -ErrorAction Stop @{ TenantName = "$($Tenant)" Status = 'Successfully connected to Exchange' } } catch { + $ErrorMessage = Get-CippException -Exception $_ $ReportedError = ($_.ErrorDetails | ConvertFrom-Json -ErrorAction SilentlyContinue) $Message = if ($ReportedError.error.details.message) { $ReportedError.error.details.message } else { $ReportedError.error.innererror.internalException.message } if ($null -eq $Message) { $Message = $($_.Exception.Message) } @{ TenantName = "$($Tenant)" - Status = "Failed to connect to Exchange: $(Get-NormalizedError -message $Message)" + Status = "Failed to connect to Exchange: $($ErrorMessage.NormalizedError)" } - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Tenant access check for Exchange failed: $(Get-NormalizedError -message $Message) " -Sev 'Error' + Write-LogMessage -user $ExecutingUser -API $APINAME -tenant $tenant -message "Tenant access check for Exchange failed: $($ErrorMessage.NormalizedError) " -Sev 'Error' -LogData $ErrorMessage } } if (!$Tenants) { $results = 'Could not load the tenants list from cache. Please run permissions check first, or visit the tenants page.' } diff --git a/Modules/CIPPCore/Public/Test-CIPPGDAPRelationships.ps1 b/Modules/CIPPCore/Public/Test-CIPPGDAPRelationships.ps1 index d527bdd0ff3b..2d8b95ff2ea2 100644 --- a/Modules/CIPPCore/Public/Test-CIPPGDAPRelationships.ps1 +++ b/Modules/CIPPCore/Public/Test-CIPPGDAPRelationships.ps1 @@ -89,7 +89,8 @@ function Test-CIPPGDAPRelationships { } } catch { - Write-LogMessage -user $ExecutingUser -API $APINAME -message "Failed to run GDAP check for $($TenantFilter): $($_.Exception.Message)" -Sev 'Error' + $ErrorMessage = Get-CippException -Exception $_ + Write-LogMessage -user $ExecutingUser -API $APINAME -message "Failed to run GDAP check for $($TenantFilter): $($ErrorMessage.NormalizedError)" -Sev 'Error' -LogData $ErrorMessage } return [PSCustomObject]@{ diff --git a/Modules/CippExtensions/Public/Extension Functions/Register-CippExtensionScheduledTasks.ps1 b/Modules/CippExtensions/Public/Extension Functions/Register-CippExtensionScheduledTasks.ps1 index ba3ba64a9f42..d8b2d6cfd01f 100644 --- a/Modules/CippExtensions/Public/Extension Functions/Register-CippExtensionScheduledTasks.ps1 +++ b/Modules/CippExtensions/Public/Extension Functions/Register-CippExtensionScheduledTasks.ps1 @@ -50,13 +50,13 @@ function Register-CIPPExtensionScheduledTasks { $ExistingTask = $ScheduledTasks | Where-Object { $_.Tenant -eq $Tenant.defaultDomainName -and $_.SyncType -eq $SyncType } if (!$ExistingTask -or $Reschedule.IsPresent) { $unixtime = [int64](([datetime]::UtcNow) - (Get-Date '1/1/1970')).TotalSeconds - $Task = @{ + $Task = [pscustomobject]@{ Name = "Extension Sync - $SyncType" Command = @{ value = 'Sync-CippExtensionData' label = 'Sync-CippExtensionData' } - Parameters = @{ + Parameters = [pscustomobject]@{ TenantFilter = $Tenant.defaultDomainName SyncType = $SyncType } @@ -65,7 +65,7 @@ function Register-CIPPExtensionScheduledTasks { TenantFilter = $Tenant.defaultDomainName } if ($ExistingTask) { - $Task.RowKey = $ExistingTask.RowKey + $Task | Add-Member -NotePropertyName 'RowKey' -NotePropertyValue $ExistingTask.RowKey -Force } $null = Add-CIPPScheduledTask -Task $Task -hidden $true -SyncType $SyncType Write-Information "Creating $SyncType task for tenant $($Tenant.defaultDomainName)" @@ -76,13 +76,13 @@ function Register-CIPPExtensionScheduledTasks { if (!$ExistingPushTask -or $Reschedule.IsPresent) { # push cached data to extension $in30mins = [int64](([datetime]::UtcNow.AddMinutes(30)) - (Get-Date '1/1/1970')).TotalSeconds - $Task = @{ + $Task = [pscustomobject]@{ Name = "$Extension Extension Sync" Command = @{ value = 'Push-CippExtensionData' label = 'Push-CippExtensionData' } - Parameters = @{ + Parameters = [pscustomobject]@{ TenantFilter = $Tenant.defaultDomainName Extension = $Extension } @@ -91,7 +91,7 @@ function Register-CIPPExtensionScheduledTasks { TenantFilter = $Tenant.defaultDomainName } if ($ExistingPushTask) { - $Task.RowKey = $ExistingTask.RowKey + $task | Add-Member -NotePropertyName 'RowKey' -NotePropertyValue $ExistingPushTask.RowKey -Force } $null = Add-CIPPScheduledTask -Task $Task -hidden $true -SyncType $Extension Write-Information "Creating $Extension task for tenant $($Tenant.defaultDomainName)" diff --git a/Tools/Update-StandardsComments.ps1 b/Tools/Update-StandardsComments.ps1 index a4f6c6a0f082..6660c3c5e901 100644 --- a/Tools/Update-StandardsComments.ps1 +++ b/Tools/Update-StandardsComments.ps1 @@ -1,110 +1,110 @@ -<# -.SYNOPSIS - This script updates the comment block in the CIPP standard files. - -.DESCRIPTION - The script reads the standards.json file and updates the comment block in the corresponding CIPP standard files. - It adds or modifies the comment block based on the properties defined in the standards.json file. - This is made to be able to generate the help documentation for the CIPP standards automatically. - -.INPUTS - None. You cannot pipe objects to this script. - -.OUTPUTS - None. The script modifies the CIPP standard files directly. - -.EXAMPLE - Update-StandardsComments.ps1 - - This example runs the script to update the comment block in the CIPP standard files. - - -#> -param ( - [switch]$WhatIf -) - -# Find the paths to the standards.json file based on the current script path -$StandardsJSONPath = Split-Path (Split-Path $PSScriptRoot) -$StandardsJSONPath = Resolve-Path "$StandardsJSONPath\*\src\data\standards.json" -$StandardsInfo = Get-Content -Path $StandardsJSONPath | ConvertFrom-Json -Depth 10 - -foreach ($Standard in $StandardsInfo) { - - # Calculate the standards file name and path - $StandardFileName = $Standard.name -replace 'standards.', 'Invoke-CIPPStandard' - $StandardsFilePath = Resolve-Path "$(Split-Path $PSScriptRoot)\Modules\CIPPCore\Public\Standards\$StandardFileName.ps1" - if (-not (Test-Path $StandardsFilePath)) { - Write-Host "No file found for standard $($Standard.name)" -ForegroundColor Yellow - continue - } - $Content = (Get-Content -Path $StandardsFilePath -Raw).TrimEnd() - - # Remove random newlines before the param block - $regexPattern = '#>\s*\r?\n\s*\r?\n\s*param' - $Content = $Content -replace $regexPattern, "#>`n`n param" - - # Regex to match the existing comment block - $Regex = '<#(.|\n)*?\.FUNCTIONALITY\s*Internal(.|\n)*?#>' - - if ($Content -match $Regex) { - $NewComment = [System.Collections.Generic.List[string]]::new() - # Add the initial scatic comments - $NewComment.Add("<#`r`n") - $NewComment.Add(" .FUNCTIONALITY`r`n") - $NewComment.Add(" Internal`r`n") - $NewComment.Add(" .COMPONENT`r`n") - $NewComment.Add(" (APIName) $($Standard.name -replace 'standards.', '')`r`n") - $NewComment.Add(" .SYNOPSIS`r`n") - $NewComment.Add(" (Label) $($Standard.label.ToString())`r`n") - $NewComment.Add(" .DESCRIPTION`r`n") - if ([string]::IsNullOrWhiteSpace($Standard.docsDescription)) { - $NewComment.Add(" (Helptext) $($Standard.helpText.ToString())`r`n") - $NewComment.Add(" (DocsDescription) $($Standard.helpText.ToString())`r`n") - } else { - $NewComment.Add(" (Helptext) $($Standard.helpText.ToString())`r`n") - $NewComment.Add(" (DocsDescription) $($Standard.docsDescription.ToString())`r`n") - } - $NewComment.Add(" .NOTES`r`n") - - # Loop through the rest of the properties of the standard and add them to the NOTES field - foreach ($Property in $Standard.PSObject.Properties) { - switch ($Property.Name) { - 'name' { continue } - 'impactColour' { continue } - 'docsDescription' { continue } - 'helpText' { continue } - 'label' { continue } - Default { - $NewComment.Add(" $($Property.Name.ToUpper())`r`n") - if ($Property.Value -is [System.Object[]]) { - foreach ($Value in $Property.Value) { - $NewComment.Add(" $(ConvertTo-Json -InputObject $Value -Depth 5 -Compress)`r`n") - } - continue - } - $NewComment.Add(" $($Property.Value.ToString())`r`n") - } - } - - } - - # Add header about how to update the comment block with this script - $NewComment.Add(" UPDATECOMMENTBLOCK`r`n") - $NewComment.Add(" Run the Tools\Update-StandardsComments.ps1 script to update this comment block`r`n") - # -Online help link - $NewComment.Add(" .LINK`r`n") - $NewComment.Add(" https://docs.cipp.app/user-documentation/tenant/standards/edit-standards`r`n") - $NewComment.Add(' #>') - - # Write the new comment block to the file - if ($WhatIf.IsPresent) { - Write-Host "Would update $StandardsFilePath with the following comment block:" - $NewComment - } else { - $Content -replace $Regex, $NewComment | Set-Content -Path $StandardsFilePath -Encoding utf8 - } - } else { - Write-Host "No comment block found in $StandardsFilePath" -ForegroundColor Yellow - } -} +<# +.SYNOPSIS + This script updates the comment block in the CIPP standard files. + +.DESCRIPTION + The script reads the standards.json file and updates the comment block in the corresponding CIPP standard files. + It adds or modifies the comment block based on the properties defined in the standards.json file. + This is made to be able to generate the help documentation for the CIPP standards automatically. + +.INPUTS + None. You cannot pipe objects to this script. + +.OUTPUTS + None. The script modifies the CIPP standard files directly. + +.EXAMPLE + Update-StandardsComments.ps1 + + This example runs the script to update the comment block in the CIPP standard files. + + +#> +param ( + [switch]$WhatIf +) + +# Find the paths to the standards.json file based on the current script path +$StandardsJSONPath = Split-Path (Split-Path $PSScriptRoot) +$StandardsJSONPath = Resolve-Path "$StandardsJSONPath\*\src\data\standards.json" +$StandardsInfo = Get-Content -Path $StandardsJSONPath | ConvertFrom-Json -Depth 10 + +foreach ($Standard in $StandardsInfo) { + + # Calculate the standards file name and path + $StandardFileName = $Standard.name -replace 'standards.', 'Invoke-CIPPStandard' + $StandardsFilePath = Resolve-Path "$(Split-Path $PSScriptRoot)\Modules\CIPPCore\Public\Standards\$StandardFileName.ps1" + if (-not (Test-Path $StandardsFilePath)) { + Write-Host "No file found for standard $($Standard.name)" -ForegroundColor Yellow + continue + } + $Content = (Get-Content -Path $StandardsFilePath -Raw).TrimEnd() + "`r`n" + + # Remove random newlines before the param block + $regexPattern = '#>\s*\r?\n\s*\r?\n\s*param' + $Content = $Content -replace $regexPattern, "#>`r`n`r`n param" + + # Regex to match the existing comment block + $Regex = '<#(.|\n)*?\.FUNCTIONALITY\s*Internal(.|\n)*?#>' + + if ($Content -match $Regex) { + $NewComment = [System.Collections.Generic.List[string]]::new() + # Add the initial scatic comments + $NewComment.Add("<#`r`n") + $NewComment.Add(" .FUNCTIONALITY`r`n") + $NewComment.Add(" Internal`r`n") + $NewComment.Add(" .COMPONENT`r`n") + $NewComment.Add(" (APIName) $($Standard.name -replace 'standards.', '')`r`n") + $NewComment.Add(" .SYNOPSIS`r`n") + $NewComment.Add(" (Label) $($Standard.label.ToString())`r`n") + $NewComment.Add(" .DESCRIPTION`r`n") + if ([string]::IsNullOrWhiteSpace($Standard.docsDescription)) { + $NewComment.Add(" (Helptext) $($Standard.helpText.ToString())`r`n") + $NewComment.Add(" (DocsDescription) $($Standard.helpText.ToString())`r`n") + } else { + $NewComment.Add(" (Helptext) $($Standard.helpText.ToString())`r`n") + $NewComment.Add(" (DocsDescription) $($Standard.docsDescription.ToString())`r`n") + } + $NewComment.Add(" .NOTES`r`n") + + # Loop through the rest of the properties of the standard and add them to the NOTES field + foreach ($Property in $Standard.PSObject.Properties) { + switch ($Property.Name) { + 'name' { continue } + 'impactColour' { continue } + 'docsDescription' { continue } + 'helpText' { continue } + 'label' { continue } + Default { + $NewComment.Add(" $($Property.Name.ToUpper())`r`n") + if ($Property.Value -is [System.Object[]]) { + foreach ($Value in $Property.Value) { + $NewComment.Add(" $(ConvertTo-Json -InputObject $Value -Depth 5 -Compress)`r`n") + } + continue + } + $NewComment.Add(" $($Property.Value.ToString())`r`n") + } + } + + } + + # Add header about how to update the comment block with this script + $NewComment.Add(" UPDATECOMMENTBLOCK`r`n") + $NewComment.Add(" Run the Tools\Update-StandardsComments.ps1 script to update this comment block`r`n") + # -Online help link + $NewComment.Add(" .LINK`r`n") + $NewComment.Add(" https://docs.cipp.app/user-documentation/tenant/standards/edit-standards`r`n") + $NewComment.Add(' #>') + + # Write the new comment block to the file + if ($WhatIf.IsPresent) { + Write-Host "Would update $StandardsFilePath with the following comment block:" + $NewComment + } else { + $Content -replace $Regex, $NewComment | Set-Content -Path $StandardsFilePath -Encoding utf8 -NoNewLine + } + } else { + Write-Host "No comment block found in $StandardsFilePath" -ForegroundColor Yellow + } +} diff --git a/version_latest.txt b/version_latest.txt index 1aa5e414fd3a..288b2cd9a306 100644 --- a/version_latest.txt +++ b/version_latest.txt @@ -1 +1 @@ -6.0.4 +6.0.5