From 4e4a4affbc3a46c391c2a863761f296bf18966f7 Mon Sep 17 00:00:00 2001 From: KelvinTegelaar Date: Tue, 27 Feb 2024 13:53:26 +0100 Subject: [PATCH 01/16] improvements to mailbox auditing to make it faster --- .../Standards/Invoke-CIPPStandardEnableMailboxAuditing.ps1 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableMailboxAuditing.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableMailboxAuditing.ps1 index 3a9e7ef1eacd..6d959f03d8d9 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableMailboxAuditing.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardEnableMailboxAuditing.ps1 @@ -21,7 +21,7 @@ function Invoke-CIPPStandardEnableMailboxAuditing { } # Check for mailbox audit on all mailboxes. Enable for all that it's not enabled for - $Mailboxes = New-ExoRequest -tenantid $Tenant -cmdlet 'Get-Mailbox' -cmdParams @{ResultSize = 'Unlimited' } | Where-Object { $_.AuditEnabled -ne $true } + $Mailboxes = New-ExoRequest -tenantid $Tenant -cmdlet 'Get-Mailbox' -cmdParams @{filter = "auditenabled -eq 'False'" } -useSystemMailbox $true -Select 'AuditEnabled,UserPrincipalName' $Mailboxes | ForEach-Object { try { New-ExoRequest -tenantid $Tenant -cmdlet 'Set-Mailbox' -cmdParams @{Identity = $_.UserPrincipalName; AuditEnabled = $true } -Anchor $_.UserPrincipalName @@ -32,7 +32,8 @@ function Invoke-CIPPStandardEnableMailboxAuditing { } # Disable audit bypass for all mailboxes that have it enabled - $BypassMailboxes = New-ExoRequest -tenantid $Tenant -cmdlet 'Get-MailboxAuditBypassAssociation' -cmdParams @{ResultSize = 'Unlimited' } | Where-Object { $_.AuditBypassEnabled -eq $true } + + $BypassMailboxes = New-ExoRequest -tenantid $Tenant -cmdlet 'Get-MailboxAuditBypassAssociation' -select 'GUID, AuditBypassEnabled, Name' -useSystemMailbox $true | Where-Object { $_.AuditBypassEnabled -eq $true } $BypassMailboxes | ForEach-Object { try { New-ExoRequest -tenantid $Tenant -cmdlet 'Set-MailboxAuditBypassAssociation' -cmdParams @{Identity = $_.Guid; AuditBypassEnabled = $false } -UseSystemMailbox $true From a268f187576296efdea790342b5fc21c88c96d95 Mon Sep 17 00:00:00 2001 From: BNWEIN Date: Tue, 27 Feb 2024 18:12:14 +0000 Subject: [PATCH 02/16] Update run.ps1 added DKIM Records to table and export --- DomainAnalyser_All/run.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DomainAnalyser_All/run.ps1 b/DomainAnalyser_All/run.ps1 index d0da4a3e09da..468962b0ec20 100644 --- a/DomainAnalyser_All/run.ps1 +++ b/DomainAnalyser_All/run.ps1 @@ -52,6 +52,7 @@ $Result = [PSCustomObject]@{ DNSSECPresent = '' MailProvider = '' DKIMEnabled = '' + DKIMRecords = '' Score = '' MaximumScore = 160 ScorePercentage = '' @@ -218,6 +219,7 @@ try { if ($DkimRecordCount -gt 0 -and $DkimFailCount -eq 0) { $Result.DKIMEnabled = $true $ScoreDomain += $Scores.DKIMActiveAndWorking + $Result.DKIMRecords = $DkimRecord.Records | Select-Object Selector, Record } else { $Result.DKIMEnabled = $false $ScoreExplanation.Add('DKIM Not Configured') | Out-Null From c0739fb224f5c64e8be74ad95f891b19e4431477 Mon Sep 17 00:00:00 2001 From: KelvinTegelaar Date: Wed, 28 Feb 2024 14:41:21 +0100 Subject: [PATCH 03/16] fixes sign in log --- .../Public/Entrypoints/Invoke-ListUserSigninLogs.ps1 | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListUserSigninLogs.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListUserSigninLogs.ps1 index d4fe27a93764..d421b79441d5 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ListUserSigninLogs.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ListUserSigninLogs.ps1 @@ -40,9 +40,14 @@ Function Invoke-ListUserSigninLogs { @{ Name = 'FailureReason'; Expression = { $_.status.failureReason } }, @{ Name = 'FullDetails'; Expression = { $_ } } # Associate values to output bindings by calling 'Push-OutputBinding'. + if ($GraphRequest.FullDetails -eq $null) { + $GraphRequest = $null + } else { + $GraphRequest = @($GraphRequest) + } Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{ StatusCode = [HttpStatusCode]::OK - Body = @($GraphRequest) + Body = $GraphRequest }) } catch { Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to retrieve Sign In report: $($_.Exception.message) " -Sev 'Error' -tenant $TenantFilter From aadb9b79e5d6a4a80e6c1456737af0b938dc8671 Mon Sep 17 00:00:00 2001 From: BNWEIN Date: Wed, 28 Feb 2024 14:29:22 +0000 Subject: [PATCH 04/16] Added custom thresholds for SharePoint and Mailbox Quota alerts Added custom thresholds for SharePoint and Mailbox Quota alerts --- .../CIPPCore/Public/Entrypoints/Invoke-AddAlert.ps1 | 4 ++-- .../Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 | 9 +++++++-- .../Entrypoints/Push-CIPPAlertSharepointQuota.ps1 | 9 +++++++-- .../Public/Entrypoints/Push-SchedulerAlert.ps1 | 11 ++++++----- 4 files changed, 22 insertions(+), 11 deletions(-) diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-AddAlert.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-AddAlert.ps1 index 9bc6df14e424..ad22d9aef8b1 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-AddAlert.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-AddAlert.ps1 @@ -32,7 +32,7 @@ Function Invoke-AddAlert { MFAAlertUsers = [bool]$Request.body.MFAAlertUsers NewGA = [bool]$Request.body.NewGA NewRole = [bool]$Request.body.NewRole - QuotaUsed = [bool]$Request.body.QuotaUsed + QuotaUsed = [int]$Request.body.QuotaUsedQuota UnusedLicenses = [bool]$Request.body.UnusedLicenses OverusedLicenses = [bool]$Request.body.OverusedLicenses AppSecretExpiry = [bool]$Request.body.AppSecretExpiry @@ -41,7 +41,7 @@ Function Invoke-AddAlert { DepTokenExpiry = [bool]$Request.body.DepTokenExpiry NoCAConfig = [bool]$Request.body.NoCAConfig SecDefaultsUpsell = [bool]$Request.body.SecDefaultsUpsell - SharePointQuota = [bool]$Request.body.SharePointQuota + SharePointQuota = [int]$Request.body.SharePointQuotaQuota ExpiringLicenses = [bool]$Request.body.ExpiringLicenses type = 'Alert' RowKey = $TenantID diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 index 47d455057c19..1d008a4c784d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 @@ -11,8 +11,13 @@ function Push-CIPPAlertQuotaUsed { New-GraphGetRequest -uri "https://graph.microsoft.com/beta/reports/getMailboxUsageDetail(period='D7')?`$format=application/json" -tenantid $QueueItem.tenant | ForEach-Object { if ($_.StorageUsedInBytes -eq 0) { continue } $PercentLeft = [math]::round($_.StorageUsedInBytes / $_.prohibitSendReceiveQuotaInBytes * 100) - if ($PercentLeft -gt 90) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.UserPrincipalName): Mailbox has less than 10% space left. Mailbox is $PercentLeft% full" + if ($QueueItem.value -eq $true) { + if ($PercentLeft -gt 90) { + Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.UserPrincipalName): Mailbox is more than $($QueueItem.value)% full. Mailbox is $PercentLeft% full" + } + } + elseif ($PercentLeft -gt $QueueItem.value) { + Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.UserPrincipalName): Mailbox is more than $($QueueItem.value)% full. Mailbox is $PercentLeft% full" } } } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 index 0f010b2bb59c..d96dd801aedb 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 @@ -13,8 +13,13 @@ function Push-CIPPAlertSharepointQuota { $sharepointQuota = (Invoke-RestMethod -Method 'GET' -Headers $sharepointToken -Uri "https://$($tenantName)-admin.sharepoint.com/_api/StorageQuotas()?api-version=1.3.2" -ErrorAction Stop).value if ($sharepointQuota) { $UsedStoragePercentage = [int](($sharepointQuota.GeoUsedStorageMB / $sharepointQuota.TenantStorageMB) * 100) - if ($UsedStoragePercentage -gt 90) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "SharePoint Storage is at $($UsedStoragePercentage)%" + if ($QueueItem.value -eq $true){ + if ($UsedStoragePercentage -gt 90) { + Write-AlertMessage -tenant $($QueueItem.tenant) -message "SharePoint Storage is at $($UsedStoragePercentage)%. Your alert threshold is 90%" + } + } + elseif ($UsedStoragePercentage -gt $QueueItem.value) { + Write-AlertMessage -tenant $($QueueItem.tenant) -message "SharePoint Storage is at $($UsedStoragePercentage)%. Your alert threshold is $($QueueItem.value)%" } } } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-SchedulerAlert.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-SchedulerAlert.ps1 index 5b32b6fb3c51..30a4b2583cde 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-SchedulerAlert.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-SchedulerAlert.ps1 @@ -15,22 +15,23 @@ function Push-SchedulerAlert { $IgnoreList = @('Etag', 'PartitionKey', 'Timestamp', 'RowKey', 'tenantid', 'tenant', 'type') $alertList = $Alerts | Select-Object * -ExcludeProperty $IgnoreList - foreach ($task in ($AlertList.psobject.members | Where-Object { $_.MemberType -EQ 'NoteProperty' -and $_.value -eq $True }).name) { + foreach ($task in ($AlertList.psobject.members | Where-Object { $_.MemberType -EQ 'NoteProperty' -and $_.value -ne $false })) { $Table = Get-CIPPTable -TableName AlertRunCheck - $Filter = "PartitionKey eq '{0}' and RowKey eq '{1}' and Timestamp ge datetime'{2}'" -f $tenant.tenant, $task, (Get-Date).AddMinutes(-10).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss') + $Filter = "PartitionKey eq '{0}' and RowKey eq '{1}' and Timestamp ge datetime'{2}'" -f $tenant.tenant, $task.Name, (Get-Date).AddMinutes(-10).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss') $ExistingMessage = Get-CIPPAzDataTableEntity @Table -Filter $Filter if (!$ExistingMessage) { $QueueItem = [pscustomobject]@{ tenant = $tenant.tenant tenantid = $tenant.tenantid - FunctionName = "CIPPAlert$($Task)" + FunctionName = "CIPPAlert$($Task.Name)" + value = $Task.value } Push-OutputBinding -Name QueueItemOut -Value $QueueItem - $QueueItem | Add-Member -MemberType NoteProperty -Name 'RowKey' -Value $task -Force + $QueueItem | Add-Member -MemberType NoteProperty -Name 'RowKey' -Value $task.Name -Force $QueueItem | Add-Member -MemberType NoteProperty -Name 'PartitionKey' -Value $tenant.tenant -Force Add-CIPPAzDataTableEntity @Table -Entity $QueueItem -Force } else { - Write-Host ('ALERTS: Duplicate run found. Ignoring. Tenant: {0}, Task: {1}' -f $tenant.tenant, $task) + Write-Host ('ALERTS: Duplicate run found. Ignoring. Tenant: {0}, Task: {1}' -f $tenant.tenant, $task.Name) } } From e4032a8005eb3790926ce5b5a45b9b24dfdf297e Mon Sep 17 00:00:00 2001 From: John Duprey Date: Wed, 28 Feb 2024 11:24:35 -0500 Subject: [PATCH 05/16] Tweak ExecScheduledCommand --- ExecScheduledCommand/run.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ExecScheduledCommand/run.ps1 b/ExecScheduledCommand/run.ps1 index 180df3368b87..d0031f771c5c 100644 --- a/ExecScheduledCommand/run.ps1 +++ b/ExecScheduledCommand/run.ps1 @@ -19,7 +19,7 @@ try { if ($results -is [String]) { $results = @{ Results = $results } } - if ($results -is [array]) { + if ($results -is [array] -and $results[0] -is [string]) { $results = $results | Where-Object { $_ -is [string] } $results = $results | ForEach-Object { @{ Results = $_ } } } From a825f3ad8c5ac79f68aeeae4d7e68287fb6a0606 Mon Sep 17 00:00:00 2001 From: KelvinTegelaar Date: Wed, 28 Feb 2024 22:57:59 +0100 Subject: [PATCH 06/16] fixes api --- .../Entrypoints/Push-CIPPAlertSharepointQuota.ps1 | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 index d96dd801aedb..7eb8f351a6ca 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 @@ -12,16 +12,14 @@ function Push-CIPPAlertSharepointQuota { $sharepointToken.Add('accept', 'application/json') $sharepointQuota = (Invoke-RestMethod -Method 'GET' -Headers $sharepointToken -Uri "https://$($tenantName)-admin.sharepoint.com/_api/StorageQuotas()?api-version=1.3.2" -ErrorAction Stop).value if ($sharepointQuota) { + if ($QueueItem.value) { $Value = $QueueItem.value } else { $Value = 90 } $UsedStoragePercentage = [int](($sharepointQuota.GeoUsedStorageMB / $sharepointQuota.TenantStorageMB) * 100) - if ($QueueItem.value -eq $true){ - if ($UsedStoragePercentage -gt 90) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "SharePoint Storage is at $($UsedStoragePercentage)%. Your alert threshold is 90%" - } - } - elseif ($UsedStoragePercentage -gt $QueueItem.value) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "SharePoint Storage is at $($UsedStoragePercentage)%. Your alert threshold is $($QueueItem.value)%" + if ($UsedStoragePercentage -gt $Value) { + Write-AlertMessage -tenant $($QueueItem.tenant) -message "SharePoint Storage is at $($UsedStoragePercentage)%. Your alert threshold is $($Value)%" } } } catch { } -} + + +} \ No newline at end of file From 0f6ebaef80cac288ad48c539fbaa6ebf4b24c45c Mon Sep 17 00:00:00 2001 From: KelvinTegelaar Date: Wed, 28 Feb 2024 22:59:28 +0100 Subject: [PATCH 07/16] fixes mailbox quota --- .../CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 index 1d008a4c784d..ecb2aaf7b4ad 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 @@ -12,13 +12,11 @@ function Push-CIPPAlertQuotaUsed { if ($_.StorageUsedInBytes -eq 0) { continue } $PercentLeft = [math]::round($_.StorageUsedInBytes / $_.prohibitSendReceiveQuotaInBytes * 100) if ($QueueItem.value -eq $true) { + if ($QueueItem.value) { $Value = $QueueItem.value } else { $Value = 90 } if ($PercentLeft -gt 90) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.UserPrincipalName): Mailbox is more than $($QueueItem.value)% full. Mailbox is $PercentLeft% full" + Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.UserPrincipalName): Mailbox is more than $($value)% full. Mailbox is $PercentLeft% full" } } - elseif ($PercentLeft -gt $QueueItem.value) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.UserPrincipalName): Mailbox is more than $($QueueItem.value)% full. Mailbox is $PercentLeft% full" - } } } catch { } From be4fc52697665ffc848041e543e542d382555793 Mon Sep 17 00:00:00 2001 From: Roel van der Wegen Date: Sat, 2 Mar 2024 20:24:15 +0100 Subject: [PATCH 08/16] Account for people using ; as delimiter --- Modules/CIPPCore/Public/Send-CIPPAlert.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 b/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 index a253311fae29..55d7e9db9803 100644 --- a/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 +++ b/Modules/CIPPCore/Public/Send-CIPPAlert.ps1 @@ -18,7 +18,7 @@ function Send-CIPPAlert { Write-Host "Trying to send email" try { if ($Config.email -like '*@*') { - $Recipients = $Config.email.split(",").trim() | ForEach-Object { if ($_ -like '*@*') { [pscustomobject]@{EmailAddress = @{Address = $_ } } } } + $Recipients = $Config.email.split($(if ($Config.email -like "*,*") { ',' } else { ';' })).trim() | ForEach-Object { if ($_ -like '*@*') { [pscustomobject]@{EmailAddress = @{Address = $_ } } } } $PowerShellBody = [PSCustomObject]@{ message = @{ subject = $Title From 7118b825d0d67649f982bcec407a2c8450d4998a Mon Sep 17 00:00:00 2001 From: John Duprey Date: Mon, 4 Mar 2024 14:25:12 -0500 Subject: [PATCH 09/16] Update Entra Device actions --- .../Public/Entrypoints/Invoke-ExecDeviceDelete.ps1 | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecDeviceDelete.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecDeviceDelete.ps1 index 843764a6d5d4..25e64be478b3 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecDeviceDelete.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-ExecDeviceDelete.ps1 @@ -14,13 +14,16 @@ Function Invoke-ExecDeviceDelete { # Interact with query parameters or the body of the request. - try { + try { $url = "https://graph.microsoft.com/beta/devices/$($request.query.id)" if ($Request.query.action -eq 'delete') { $ActionResult = New-GraphPOSTRequest -uri $url -type DELETE -tenantid $Request.Query.TenantFilter - } else { + } elseif ($Request.query.action -eq 'disable') { $ActionResult = New-GraphPOSTRequest -uri $url -type PATCH -tenantid $Request.Query.TenantFilter -body '{"accountEnabled": false }' + } elseif ($Request.query.action -eq 'enable') { + $ActionResult = New-GraphPOSTRequest -uri $url -type PATCH -tenantid $Request.Query.TenantFilter -body '{"accountEnabled": true }' } + Write-Host $ActionResult $body = [pscustomobject]@{'Results' = "Executed action $($Request.query.action) on $($Request.query.id)" } } catch { $body = [pscustomobject]@{'Results' = "Failed to queue action $($Request.query.action) on $($request.query.id): $($_.Exception.Message)" } From c7140d873e728bd4d35bedbddce961aee4017cdd Mon Sep 17 00:00:00 2001 From: John Duprey Date: Mon, 4 Mar 2024 14:25:44 -0500 Subject: [PATCH 10/16] Add entrypoints for generic durables --- CIPPActivityFunction/function.json | 11 ++++ CIPPOrchestrator/function.json | 11 ++++ Modules/CippEntrypoints/CippEntrypoints.psm1 | 58 +++++++++++++++++++- 3 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 CIPPActivityFunction/function.json create mode 100644 CIPPOrchestrator/function.json diff --git a/CIPPActivityFunction/function.json b/CIPPActivityFunction/function.json new file mode 100644 index 000000000000..b4007235d549 --- /dev/null +++ b/CIPPActivityFunction/function.json @@ -0,0 +1,11 @@ +{ + "scriptFile": "../Modules/CippEntryPoints/CippEntryPoints.psm1", + "entryPoint": "Receive-CippActivityTrigger", + "bindings": [ + { + "name": "name", + "type": "activityTrigger", + "direction": "in" + } + ] +} diff --git a/CIPPOrchestrator/function.json b/CIPPOrchestrator/function.json new file mode 100644 index 000000000000..011113dbc618 --- /dev/null +++ b/CIPPOrchestrator/function.json @@ -0,0 +1,11 @@ +{ + "scriptFile": "../Modules/CippEntryPoints/CippEntryPoints.psm1", + "entryPoint": "Receive-CippOrchestrationTrigger", + "bindings": [ + { + "name": "Context", + "type": "orchestrationTrigger", + "direction": "in" + } + ] +} diff --git a/Modules/CippEntrypoints/CippEntrypoints.psm1 b/Modules/CippEntrypoints/CippEntrypoints.psm1 index d6d80cdcf143..119187c412d0 100644 --- a/Modules/CippEntrypoints/CippEntrypoints.psm1 +++ b/Modules/CippEntrypoints/CippEntrypoints.psm1 @@ -19,7 +19,7 @@ function Receive-CippHttpTrigger { function Receive-CippQueueTrigger { Param($QueueItem, $TriggerMetadata) - + $Start = (Get-Date).ToUniversalTime() $APIName = $TriggerMetadata.FunctionName Write-Host "#### Running $APINAME" @@ -48,5 +48,59 @@ function Receive-CippQueueTrigger { Write-CippFunctionStats @Stats } -Export-ModuleMember -Function @('Receive-CippHttpTrigger', 'Receive-CippQueueTrigger') +function Receive-CippOrchestrationTrigger { + param($Context) + + $DurableRetryOptions = @{ + FirstRetryInterval = (New-TimeSpan -Seconds 5) + MaxNumberOfAttempts = 3 + BackoffCoefficient = 2 + } + $RetryOptions = New-DurableRetryOptions @DurableRetryOptions + Write-LogMessage -API $Context.Input.OrchestratorName -tenant $Context.Input.TenantFilter -message "Started $($Context.Input.OrchestratorName)" -sev info + + if (!$Context.Input.Batch -or ($Context.Input.Batch | Measure-Object).Count -eq 0) { + $Batch = (Invoke-ActivityFunction -FunctionName 'CIPPActivityFunction' -Input $Context.Input.QueueFunction) + } else { + $Batch = $Context.Input.Batch + } + + foreach ($Item in $Batch) { + Invoke-DurableActivity -FunctionName 'CIPPActivityFunction' -Input $Item -NoWait -RetryOptions $RetryOptions + } + + Write-LogMessage -API $Context.Input.OrchestratorName -tenant $tenant -message "Finished $($Context.Input.OrchestratorName)" -sev Info +} + +function Receive-CippActivityTrigger { + Param($Item) + + $Start = (Get-Date).ToUniversalTime() + Set-Location (Get-Item $PSScriptRoot).Parent.Parent.FullName + + if ($Item.FunctionName) { + $FunctionName = 'Push-{0}' -f $Item.FunctionName + try { + & $FunctionName @Item + } catch { + $ErrorMsg = $_.Exception.Message + } + } else { + $ErrorMsg = 'Function not provided' + } + + $End = (Get-Date).ToUniversalTime() + + $Stats = @{ + FunctionType = 'Durable' + Entity = $Item + Start = $Start + End = $End + ErrorMsg = $ErrorMsg + } + Write-Information '####### Adding stats' + Write-CippFunctionStats @Stats +} + +Export-ModuleMember -Function @('Receive-CippHttpTrigger', 'Receive-CippQueueTrigger', 'Receive-CippOrchestrationTrigger', 'Receive-CippActivityTrigger') From 5c87c669c71f068d91f0b85d815d172a99c10d03 Mon Sep 17 00:00:00 2001 From: John Duprey Date: Mon, 4 Mar 2024 15:47:40 -0500 Subject: [PATCH 11/16] Standards to durable --- CIPPActivityFunction/function.json | 2 +- .../Public/Entrypoints/Push-CIPPStandard.ps1 | 10 +++--- .../GraphHelper/Write-CippFunctionStats.ps1 | 2 +- .../Public/Invoke-CIPPStandardsRun.ps1 | 32 ++++++++++++------- Modules/CippEntrypoints/CippEntrypoints.psm1 | 1 + Scheduler_Standards/function.json | 5 +++ 6 files changed, 33 insertions(+), 19 deletions(-) diff --git a/CIPPActivityFunction/function.json b/CIPPActivityFunction/function.json index b4007235d549..a9529e73be54 100644 --- a/CIPPActivityFunction/function.json +++ b/CIPPActivityFunction/function.json @@ -3,7 +3,7 @@ "entryPoint": "Receive-CippActivityTrigger", "bindings": [ { - "name": "name", + "name": "Item", "type": "activityTrigger", "direction": "in" } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPStandard.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPStandard.ps1 index 89a9024a9389..2431afb0c8e6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPStandard.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPStandard.ps1 @@ -1,15 +1,15 @@ function Push-CIPPStandard { param ( - $QueueItem, $TriggerMetadata + $Tenant, + $Standard, + $Settings ) - Write-Host "Received queue item for $($QueueItem.Tenant) and standard $($QueueItem.Standard)." - $Tenant = $QueueItem.Tenant - $Standard = $QueueItem.Standard + Write-Host "Received queue item for $Tenant and standard $Standard." $FunctionName = 'Invoke-CIPPStandard{0}' -f $Standard Write-Host "We'll be running $FunctionName" try { - & $FunctionName -Tenant $Tenant -Settings $QueueItem.Settings -ErrorAction Stop + & $FunctionName -Tenant $Tenant -Settings $Settings -ErrorAction Stop } catch { throw $_.Exception.Message } diff --git a/Modules/CIPPCore/Public/GraphHelper/Write-CippFunctionStats.ps1 b/Modules/CIPPCore/Public/GraphHelper/Write-CippFunctionStats.ps1 index cac4bf0a3173..e4102cd31521 100644 --- a/Modules/CIPPCore/Public/GraphHelper/Write-CippFunctionStats.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/Write-CippFunctionStats.ps1 @@ -15,7 +15,7 @@ function Write-CippFunctionStats { $RowKey = [string](New-Guid).Guid $TimeSpan = New-TimeSpan -Start $Start -End $End $Duration = [int]$TimeSpan.TotalSeconds - + # Flatten data to json string $Entity.PartitionKey = $FunctionType $Entity.RowKey = $RowKey diff --git a/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 b/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 index 353551cdaadf..37d85bba93b4 100644 --- a/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 +++ b/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 @@ -1,4 +1,4 @@ - + function Invoke-CIPPStandardsRun { [CmdletBinding()] param( @@ -20,7 +20,7 @@ function Invoke-CIPPStandardsRun { $OldStd = $_ $OldStd.standards.psobject.properties.name | ForEach-Object { if ($_ -eq 'MailContacts') { - $OldStd.Standards.$_ = [pscustomobject]@{ + $OldStd.Standards.$_ = [pscustomobject]@{ GeneralContact = $OldStd.Standards.MailContacts.GeneralContact.Mail SecurityContact = $OldStd.Standards.MailContacts.SecurityContact.Mail MarketingContact = $OldStd.Standards.MailContacts.MarketingContact.Mail @@ -28,16 +28,16 @@ function Invoke-CIPPStandardsRun { remediate = $true } } else { - if ($OldStd.Standards.$_ -eq $true -and $_ -ne 'v2.1') { - $OldStd.Standards.$_ = @{ remediate = $true } - } else { - $OldStd.Standards.$_ | Add-Member -NotePropertyName 'remediate' -NotePropertyValue $true -Force + if ($OldStd.Standards.$_ -eq $true -and $_ -ne 'v2.1') { + $OldStd.Standards.$_ = @{ remediate = $true } + } else { + $OldStd.Standards.$_ | Add-Member -NotePropertyName 'remediate' -NotePropertyValue $true -Force } - + } } $OldStd | Add-Member -NotePropertyName 'v2.1' -NotePropertyValue $true -PassThru -Force - $Entity = @{ + $Entity = @{ PartitionKey = 'standards' RowKey = "$($OldStd.Tenant)" JSON = "$($OldStd | ConvertTo-Json -Depth 10)" @@ -76,15 +76,23 @@ function Invoke-CIPPStandardsRun { } } - #For each item in our object, run the queue. + #For each item in our object, run the queue. - foreach ($task in $object | Where-Object -Property Standard -NotLike 'v2*') { - $QueueItem = [pscustomobject]@{ + $Batch = foreach ($task in $object | Where-Object -Property Standard -NotLike 'v2*') { + [PSCustomObject]@{ Tenant = $task.Tenant Standard = $task.Standard Settings = $task.Settings FunctionName = 'CIPPStandard' } - Push-OutputBinding -Name QueueItem -Value $QueueItem } + + $InputObject = [PSCustomObject]@{ + OrchestratorName = 'Standards' + Batch = @($Batch) + } + + $InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject $InputObject + Write-Host "Started orchestration with ID = '$InstanceId'" + $Orchestrator = New-OrchestrationCheckStatusResponse -Request $Request -InstanceId $InstanceId } \ No newline at end of file diff --git a/Modules/CippEntrypoints/CippEntrypoints.psm1 b/Modules/CippEntrypoints/CippEntrypoints.psm1 index 119187c412d0..3d9d1f631186 100644 --- a/Modules/CippEntrypoints/CippEntrypoints.psm1 +++ b/Modules/CippEntrypoints/CippEntrypoints.psm1 @@ -98,6 +98,7 @@ function Receive-CippActivityTrigger { End = $End ErrorMsg = $ErrorMsg } + Write-Information '####### Adding stats' Write-CippFunctionStats @Stats } diff --git a/Scheduler_Standards/function.json b/Scheduler_Standards/function.json index 35ec29f027f7..81d53b9a1598 100644 --- a/Scheduler_Standards/function.json +++ b/Scheduler_Standards/function.json @@ -11,6 +11,11 @@ "direction": "out", "name": "QueueItem", "queueName": "CIPPGenericQueue" + }, + { + "name": "starter", + "type": "durableClient", + "direction": "in" } ] } From 575ae066f56ae5364a0d82eafc9656b749c8817b Mon Sep 17 00:00:00 2001 From: John Duprey Date: Mon, 4 Mar 2024 18:54:56 -0500 Subject: [PATCH 12/16] tweak orchestrator allow for json input for larger depth --- .../Public/Entrypoints/Push-CIPPStandard.ps1 | 10 +++++----- .../Public/Invoke-CIPPStandardsRun.ps1 | 2 +- Modules/CippEntrypoints/CippEntrypoints.psm1 | 18 ++++++++++++------ 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPStandard.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPStandard.ps1 index 2431afb0c8e6..dd9849da8514 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPStandard.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPStandard.ps1 @@ -1,15 +1,15 @@ function Push-CIPPStandard { param ( - $Tenant, - $Standard, - $Settings + $Item ) - Write-Host "Received queue item for $Tenant and standard $Standard." + Write-Host "Received queue item for $($Item.Tenant) and standard $($Item.Standard)." + $Tenant = $Item.Tenant + $Standard = $Item.Standard $FunctionName = 'Invoke-CIPPStandard{0}' -f $Standard Write-Host "We'll be running $FunctionName" try { - & $FunctionName -Tenant $Tenant -Settings $Settings -ErrorAction Stop + & $FunctionName -Tenant $Item.Tenant -Settings $Item.Settings -ErrorAction Stop } catch { throw $_.Exception.Message } diff --git a/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 b/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 index 37d85bba93b4..dd4acff806e8 100644 --- a/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 +++ b/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 @@ -92,7 +92,7 @@ function Invoke-CIPPStandardsRun { Batch = @($Batch) } - $InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject $InputObject + $InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject ($InputObject | ConvertTo-Json -Depth 5) Write-Host "Started orchestration with ID = '$InstanceId'" $Orchestrator = New-OrchestrationCheckStatusResponse -Request $Request -InstanceId $InstanceId } \ No newline at end of file diff --git a/Modules/CippEntrypoints/CippEntrypoints.psm1 b/Modules/CippEntrypoints/CippEntrypoints.psm1 index 3d9d1f631186..a651d072339f 100644 --- a/Modules/CippEntrypoints/CippEntrypoints.psm1 +++ b/Modules/CippEntrypoints/CippEntrypoints.psm1 @@ -56,20 +56,26 @@ function Receive-CippOrchestrationTrigger { MaxNumberOfAttempts = 3 BackoffCoefficient = 2 } + if (Test-Json -Json $Context.Input) { + $OrchestratorInput = $Context.Input | ConvertFrom-Json + } else { + $OrchestratorInput = $Context.Input + } + Write-Host ($Context | ConvertTo-Json -Depth 10) $RetryOptions = New-DurableRetryOptions @DurableRetryOptions - Write-LogMessage -API $Context.Input.OrchestratorName -tenant $Context.Input.TenantFilter -message "Started $($Context.Input.OrchestratorName)" -sev info + Write-LogMessage -API $OrchestratorInput.OrchestratorName -tenant $OrchestratorInput.TenantFilter -message "Started $($OrchestratorInput.OrchestratorName)" -sev info - if (!$Context.Input.Batch -or ($Context.Input.Batch | Measure-Object).Count -eq 0) { - $Batch = (Invoke-ActivityFunction -FunctionName 'CIPPActivityFunction' -Input $Context.Input.QueueFunction) + if (!$OrchestratorInput.Batch -or ($OrchestratorInput.Batch | Measure-Object).Count -eq 0) { + $Batch = (Invoke-ActivityFunction -FunctionName 'CIPPActivityFunction' -Input $OrchestratorInput.QueueFunction) } else { - $Batch = $Context.Input.Batch + $Batch = $OrchestratorInput.Batch } foreach ($Item in $Batch) { Invoke-DurableActivity -FunctionName 'CIPPActivityFunction' -Input $Item -NoWait -RetryOptions $RetryOptions } - Write-LogMessage -API $Context.Input.OrchestratorName -tenant $tenant -message "Finished $($Context.Input.OrchestratorName)" -sev Info + Write-LogMessage -API $OrchestratorInput.OrchestratorName -tenant $tenant -message "Finished $($OrchestratorInput.OrchestratorName)" -sev Info } function Receive-CippActivityTrigger { @@ -81,7 +87,7 @@ function Receive-CippActivityTrigger { if ($Item.FunctionName) { $FunctionName = 'Push-{0}' -f $Item.FunctionName try { - & $FunctionName @Item + & $FunctionName -Item $Item } catch { $ErrorMsg = $_.Exception.Message } From d4d09f9cbffdb611d8fb2d5ba890a4b2220653ee Mon Sep 17 00:00:00 2001 From: Mo Date: Thu, 7 Mar 2024 11:47:05 +0000 Subject: [PATCH 13/16] Update adding Connectors with the correct text --- .../CIPPCore/Public/Entrypoints/Invoke-AddExConnector.ps1 | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Modules/CIPPCore/Public/Entrypoints/Invoke-AddExConnector.ps1 b/Modules/CIPPCore/Public/Entrypoints/Invoke-AddExConnector.ps1 index 3686d66c124d..b3246cea773d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Invoke-AddExConnector.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Invoke-AddExConnector.ps1 @@ -18,12 +18,12 @@ Function Invoke-AddExConnector { $Result = foreach ($Tenantfilter in $tenants) { try { $GraphRequest = New-ExoRequest -tenantid $Tenantfilter -cmdlet "New-$($ConnectorType)connector" -cmdParams $RequestParams - "Successfully created transport rule for $Tenantfilter." - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Tenantfilter -message "Created transport rule for $($Tenantfilter)" -sev 'Info' + "Successfully created Connector for $Tenantfilter." + Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Tenantfilter -message "Created Connector for $($Tenantfilter)" -sev 'Info' } catch { - "Could not create created transport rule for $($Tenantfilter): $($_.Exception.message)" - Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Tenantfilter -message "Could not create created transport rule for $($Tenantfilter): $($_.Exception.message)" -sev 'Error' + "Could not create created Connector for $($Tenantfilter): $($_.Exception.message)" + Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $Tenantfilter -message "Could not create created Connector for $($Tenantfilter): $($_.Exception.message)" -sev 'Error' } } From 24b0eaab6457c65e35411567ae09f0bbf19a8a40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristian=20Kj=C3=A6rg=C3=A5rd?= Date: Sat, 9 Mar 2024 14:57:31 +0100 Subject: [PATCH 14/16] Handle rare error case and change to use v1.0 endpoint --- .../Invoke-CIPPStandardPasswordExpireDisabled.ps1 | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardPasswordExpireDisabled.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardPasswordExpireDisabled.ps1 index e9182bb95717..47cdc60712c8 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardPasswordExpireDisabled.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardPasswordExpireDisabled.ps1 @@ -4,7 +4,7 @@ function Invoke-CIPPStandardPasswordExpireDisabled { Internal #> param($Tenant, $Settings) - $GraphRequest = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/domains' -tenantid $Tenant + $GraphRequest = New-GraphGetRequest -uri 'https://graph.microsoft.com/v1.0/domains' -tenantid $Tenant $DomainswithoutPassExpire = $GraphRequest | Where-Object -Property passwordValidityPeriodInDays -NE '2147483647' If ($Settings.remediate) { @@ -12,7 +12,13 @@ function Invoke-CIPPStandardPasswordExpireDisabled { if ($DomainswithoutPassExpire) { $DomainswithoutPassExpire | ForEach-Object { try { - New-GraphPostRequest -type Patch -tenantid $Tenant -uri "https://graph.microsoft.com/beta/domains/$($_.id)" -body '{"passwordValidityPeriodInDays": 2147483647 }' + if ( $null -eq $_.passwordNotificationWindowInDays ) { + $Body = '{"passwordValidityPeriodInDays": 2147483647, "passwordNotificationWindowInDays": 14 }' + Write-Host "PasswordNotificationWindowInDays is null for $($_.id). Setting to the default of 14 days." + } else { + $Body = '{"passwordValidityPeriodInDays": 2147483647 }' + } + New-GraphPostRequest -type Patch -tenantid $Tenant -uri "https://graph.microsoft.com/v1.0/domains/$($_.id)" -body $Body Write-LogMessage -API 'Standards' -tenant $tenant -message "Disabled Password Expiration for $($_.id)." -sev Info } catch { Write-LogMessage -API 'Standards' -tenant $tenant -message "Failed to disable Password Expiration for $($_.id). Error: $($_.exception.message)" -sev Error From 7c1c526ab9a2ee2403c3e64eea5d4e2d8689092b Mon Sep 17 00:00:00 2001 From: John Duprey Date: Sat, 9 Mar 2024 11:37:38 -0800 Subject: [PATCH 15/16] Alerts Durable --- CIPPActivityFunction/function.json | 5 ++ .../Push-CIPPAlertAdminPassword.ps1 | 11 ++-- .../Push-CIPPAlertApnCertExpiry.ps1 | 11 ++-- .../Push-CIPPAlertAppSecretExpiry.ps1 | 17 +++--- .../Push-CIPPAlertDefenderMalware.ps1 | 9 ++- .../Push-CIPPAlertDefenderStatus.ps1 | 10 ++-- .../Push-CIPPAlertDepTokenExpiry.ps1 | 11 ++-- .../Push-CIPPAlertExpiringLicenses.ps1 | 7 +-- .../Entrypoints/Push-CIPPAlertMFAAdmins.ps1 | 15 +++-- .../Push-CIPPAlertMFAAlertUsers.ps1 | 11 ++-- .../Entrypoints/Push-CIPPAlertNewRole.ps1 | 13 ++-- .../Entrypoints/Push-CIPPAlertNoCAConfig.ps1 | 11 ++-- .../Push-CIPPAlertOverusedLicenses.ps1 | 9 ++- .../Entrypoints/Push-CIPPAlertQuotaUsed.ps1 | 13 ++-- .../Push-CIPPAlertSecDefaultsUpsell.ps1 | 11 ++-- .../Push-CIPPAlertSharepointQuota.ps1 | 11 ++-- .../Push-CIPPAlertUnusedLicenses.ps1 | 9 ++- .../Push-CIPPAlertVppTokenExpiry.ps1 | 13 ++-- .../Entrypoints/Push-SchedulerAlert.ps1 | 51 ++++++++++------ .../GraphHelper/Write-CippFunctionStats.ps1 | 19 +++--- .../Public/Invoke-CIPPStandardsRun.ps1 | 2 +- .../Standards/Invoke-CIPPStandardAuditLog.ps1 | 10 ++-- Modules/CippEntrypoints/CippEntrypoints.psm1 | 59 +++++++++++-------- Scheduler_GetQueue/function.json | 5 ++ Scheduler_GetQueue/run.ps1 | 25 ++++---- 25 files changed, 198 insertions(+), 170 deletions(-) diff --git a/CIPPActivityFunction/function.json b/CIPPActivityFunction/function.json index a9529e73be54..e8a29dde00c3 100644 --- a/CIPPActivityFunction/function.json +++ b/CIPPActivityFunction/function.json @@ -6,6 +6,11 @@ "name": "Item", "type": "activityTrigger", "direction": "in" + }, + { + "name": "starter", + "type": "durableClient", + "direction": "in" } ] } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertAdminPassword.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertAdminPassword.ps1 index af03360c1973..63f371b10aa6 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertAdminPassword.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertAdminPassword.ps1 @@ -3,17 +3,16 @@ function Push-CIPPAlertAdminPassword { [CmdletBinding()] param( [Parameter(Mandatory = $true)] - [pscustomobject]$QueueItem, - $TriggerMetadata + [pscustomobject]$Item ) try { - New-GraphGETRequest -uri "https://graph.microsoft.com/beta/roleManagement/directory/roleAssignments?`$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'&`$expand=principal" -tenantid $($QueueItem.tenant) | Where-Object { ($_.principalOrganizationId -EQ $QueueItem.tenantid) -and ($_.principal.'@odata.type' -eq '#microsoft.graph.user') } | ForEach-Object { - $LastChanges = New-GraphGETRequest -uri "https://graph.microsoft.com/beta/users/$($_.principalId)?`$select=UserPrincipalName,lastPasswordChangeDateTime" -tenant $($QueueItem.tenant) + New-GraphGETRequest -uri "https://graph.microsoft.com/beta/roleManagement/directory/roleAssignments?`$filter=roleDefinitionId eq '62e90394-69f5-4237-9190-012177145e10'&`$expand=principal" -tenantid $($Item.tenant) | Where-Object { ($_.principalOrganizationId -EQ $Item.tenantid) -and ($_.principal.'@odata.type' -eq '#microsoft.graph.user') } | ForEach-Object { + $LastChanges = New-GraphGETRequest -uri "https://graph.microsoft.com/beta/users/$($_.principalId)?`$select=UserPrincipalName,lastPasswordChangeDateTime" -tenant $($Item.tenant) if ($LastChanges.LastPasswordChangeDateTime -gt (Get-Date).AddDays(-1)) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "Admin password has been changed for $($LastChanges.UserPrincipalName) in last 24 hours" + Write-AlertMessage -tenant $($Item.tenant) -message "Admin password has been changed for $($LastChanges.UserPrincipalName) in last 24 hours" } } } catch { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "Could not get admin password changes for $($QueueItem.tenant): $(Get-NormalizedError -message $_.Exception.message)" + Write-AlertMessage -tenant $($Item.tenant) -message "Could not get admin password changes for $($Item.tenant): $(Get-NormalizedError -message $_.Exception.message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertApnCertExpiry.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertApnCertExpiry.ps1 index 07571db760aa..9ef318273f8d 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertApnCertExpiry.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertApnCertExpiry.ps1 @@ -2,26 +2,25 @@ function Push-CIPPAlertApnCertExpiry { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) $LastRunTable = Get-CIPPTable -Table AlertLastRun try { - $Filter = "RowKey eq 'ApnCertExpiry' and PartitionKey eq '{0}'" -f $QueueItem.tenantid + $Filter = "RowKey eq 'ApnCertExpiry' and PartitionKey eq '{0}'" -f $Item.tenantid $LastRun = Get-CIPPAzDataTableEntity @LastRunTable -Filter $Filter $Yesterday = (Get-Date).AddDays(-1) if (-not $LastRun.Timestamp.DateTime -or ($LastRun.Timestamp.DateTime -le $Yesterday)) { try { - $Apn = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/applePushNotificationCertificate' -tenantid $QueueItem.tenant + $Apn = New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/applePushNotificationCertificate' -tenantid $Item.tenant if ($Apn.expirationDateTime -lt (Get-Date).AddDays(30) -and $Apn.expirationDateTime -gt (Get-Date).AddDays(-7)) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message ('Intune: Apple Push Notification certificate for {0} is expiring on {1}' -f $Apn.appleIdentifier, $Apn.expirationDateTime) + Write-AlertMessage -tenant $($Item.tenant) -message ('Intune: Apple Push Notification certificate for {0} is expiring on {1}' -f $Apn.appleIdentifier, $Apn.expirationDateTime) } } catch {} } $LastRun = @{ RowKey = 'ApnCertExpiry' - PartitionKey = $QueueItem.tenantid + PartitionKey = $Item.tenantid } Add-CIPPAzDataTableEntity @LastRunTable -Entity $LastRun -Force } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertAppSecretExpiry.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertAppSecretExpiry.ps1 index 82bcde9bb74f..06477e708ff7 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertAppSecretExpiry.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertAppSecretExpiry.ps1 @@ -2,26 +2,25 @@ function Push-CIPPAlertAppSecretExpiry { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) $LastRunTable = Get-CIPPTable -Table AlertLastRun - + try { - $Filter = "RowKey eq 'AppSecretExpiry' and PartitionKey eq '{0}'" -f $QueueItem.tenantid + $Filter = "RowKey eq 'AppSecretExpiry' and PartitionKey eq '{0}'" -f $Item.tenantid $LastRun = Get-CIPPAzDataTableEntity @LastRunTable -Filter $Filter $Yesterday = (Get-Date).AddDays(-1) if (-not $LastRun.Timestamp.DateTime -or ($LastRun.Timestamp.DateTime -le $Yesterday)) { - Write-Host "Checking app expire for $($QueueItem.tenant)" - New-GraphGetRequest -uri "https://graph.microsoft.com/beta/applications?`$select=appId,displayName,passwordCredentials" -tenantid $QueueItem.tenant | ForEach-Object { + Write-Host "Checking app expire for $($Item.tenant)" + New-GraphGetRequest -uri "https://graph.microsoft.com/beta/applications?`$select=appId,displayName,passwordCredentials" -tenantid $Item.tenant | ForEach-Object { foreach ($App in $_) { Write-Host "checking $($App.displayName)" if ($App.passwordCredentials) { foreach ($Credential in $App.passwordCredentials) { if ($Credential.endDateTime -lt (Get-Date).AddDays(30) -and $Credential.endDateTime -gt (Get-Date).AddDays(-7)) { Write-Host ("Application '{0}' has secrets expiring on {1}" -f $App.displayName, $Credential.endDateTime) - Write-AlertMessage -tenant $($QueueItem.tenant) -message ("Application '{0}' has secrets expiring on {1}" -f $App.displayName, $Credential.endDateTime) + Write-AlertMessage -tenant $($Item.tenant) -message ("Application '{0}' has secrets expiring on {1}" -f $App.displayName, $Credential.endDateTime) } } } @@ -29,12 +28,12 @@ function Push-CIPPAlertAppSecretExpiry { } $LastRun = @{ RowKey = 'AppSecretExpiry' - PartitionKey = $QueueItem.tenantid + PartitionKey = $Item.tenantid } Add-CIPPAzDataTableEntity @LastRunTable -Entity $LastRun -Force } } catch { - + } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDefenderMalware.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDefenderMalware.ps1 index b69ed1b50ab2..0d4d1c7b02ab 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDefenderMalware.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDefenderMalware.ps1 @@ -3,14 +3,13 @@ function Push-CIPPAlertDefenderMalware { [CmdletBinding()] param( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { - New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/managedTenants/windowsDeviceMalwareStates?`$top=999&`$filter=tenantId eq '$($QueueItem.tenantid)'" | Where-Object { $_.malwareThreatState -eq 'Active' } | ForEach-Object { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.managedDeviceName): Malware found and active. Severity: $($_.MalwareSeverity). Malware name: $($_.MalwareDisplayName)" + New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/managedTenants/windowsDeviceMalwareStates?`$top=999&`$filter=tenantId eq '$($Item.tenantid)'" | Where-Object { $_.malwareThreatState -eq 'Active' } | ForEach-Object { + Write-AlertMessage -tenant $($Item.tenant) -message "$($_.managedDeviceName): Malware found and active. Severity: $($_.MalwareSeverity). Malware name: $($_.MalwareDisplayName)" } } catch { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "Could not get malware data for $($QueueItem.tenant): $(Get-NormalizedError -message $_.Exception.message)" + Write-AlertMessage -tenant $($Item.tenant) -message "Could not get malware data for $($Item.tenant): $(Get-NormalizedError -message $_.Exception.message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDefenderStatus.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDefenderStatus.ps1 index e9d4e06adae0..7b42affa4e00 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDefenderStatus.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDefenderStatus.ps1 @@ -1,16 +1,14 @@ - function Push-CIPPAlertDefenderStatus { [CmdletBinding()] param( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { - New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/managedTenants/windowsProtectionStates?`$top=999&`$filter=tenantId eq '$($QueueItem.tenantid)'" | Where-Object { $_.realTimeProtectionEnabled -eq $false -or $_.MalwareprotectionEnabled -eq $false } | ForEach-Object { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.managedDeviceName) - Real Time Protection: $($_.realTimeProtectionEnabled) & Malware Protection: $($_.MalwareprotectionEnabled)" + New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/managedTenants/windowsProtectionStates?`$top=999&`$filter=tenantId eq '$($Item.tenantid)'" | Where-Object { $_.realTimeProtectionEnabled -eq $false -or $_.MalwareprotectionEnabled -eq $false } | ForEach-Object { + Write-AlertMessage -tenant $($Item.tenant) -message "$($_.managedDeviceName) - Real Time Protection: $($_.realTimeProtectionEnabled) & Malware Protection: $($_.MalwareprotectionEnabled)" } } catch { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "Could not get defender status for $($QueueItem.tenant): $(Get-NormalizedError -message $_.Exception.message)" + Write-AlertMessage -tenant $($Item.tenant) -message "Could not get defender status for $($Item.tenant): $(Get-NormalizedError -message $_.Exception.message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDepTokenExpiry.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDepTokenExpiry.ps1 index 804750e60705..4246a5364ef3 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDepTokenExpiry.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertDepTokenExpiry.ps1 @@ -2,27 +2,26 @@ function Push-CIPPAlertDepTokenExpiry { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) $LastRunTable = Get-CIPPTable -Table AlertLastRun try { - $Filter = "RowKey eq 'DepTokenExpiry' and PartitionKey eq '{0}'" -f $QueueItem.tenantid + $Filter = "RowKey eq 'DepTokenExpiry' and PartitionKey eq '{0}'" -f $Item.tenantid $LastRun = Get-CIPPAzDataTableEntity @LastRunTable -Filter $Filter $Yesterday = (Get-Date).AddDays(-1) if (-not $LastRun.Timestamp.DateTime -or ($LastRun.Timestamp.DateTime -le $Yesterday)) { try { - $DepTokens = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/depOnboardingSettings' -tenantid $QueueItem.tenant).value + $DepTokens = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceManagement/depOnboardingSettings' -tenantid $Item.tenant).value foreach ($Dep in $DepTokens) { if ($Dep.tokenExpirationDateTime -lt (Get-Date).AddDays(30) -and $Dep.tokenExpirationDateTime -gt (Get-Date).AddDays(-7)) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message ('Apple Device Enrollment Program token expiring on {0}' -f $Dep.tokenExpirationDateTime) + Write-AlertMessage -tenant $($Item.tenant) -message ('Apple Device Enrollment Program token expiring on {0}' -f $Dep.tokenExpirationDateTime) } } } catch {} $LastRun = @{ RowKey = 'DepTokenExpiry' - PartitionKey = $QueueItem.tenantid + PartitionKey = $Item.tenantid } Add-CIPPAzDataTableEntity @LastRunTable -Entity $LastRun -Force } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertExpiringLicenses.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertExpiringLicenses.ps1 index 99a861bfb5d7..6e2a704b9ba3 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertExpiringLicenses.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertExpiringLicenses.ps1 @@ -2,15 +2,14 @@ function Push-CIPPAlertExpiringLicenses { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { - Get-CIPPLicenseOverview -TenantFilter $QueueItem.tenant | ForEach-Object { + Get-CIPPLicenseOverview -TenantFilter $Item.tenant | ForEach-Object { $timeTorenew = [int64]$_.TimeUntilRenew if ($timeTorenew -lt 30 -and $_.TimeUntilRenew -gt 0) { Write-Host "$($_.License) will expire in $($_.TimeUntilRenew) days. The estimated term is $($_.EstTerm)" - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.License) will expire in $($_.TimeUntilRenew) days. The estimated term is $($_.EstTerm)" + Write-AlertMessage -tenant $($Item.tenant) -message "$($_.License) will expire in $($_.TimeUntilRenew) days. The estimated term is $($_.EstTerm)" } } } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAdmins.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAdmins.ps1 index b0c8056e1f03..66685982d956 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAdmins.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAdmins.ps1 @@ -2,26 +2,25 @@ function Push-CIPPAlertMFAAdmins { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { - $CAPolicies = (New-GraphGetRequest -Uri 'https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies?$top=999' -tenantid $QueueItem.tenant -ErrorAction Stop) + $CAPolicies = (New-GraphGetRequest -Uri 'https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies?$top=999' -tenantid $Item.tenant -ErrorAction Stop) foreach ($Policy in $CAPolicies) { if ($policy.grantControls.customAuthenticationFactors -eq 'RequireDuoMfa') { $DuoActive = $true } } if (!$DuoActive) { - $users = New-GraphGETRequest -uri 'https://graph.microsoft.com/beta/reports/authenticationMethods/userRegistrationDetails?$top=999&$filter=IsAdmin eq true' -tenantid $($QueueItem.tenant) | Where-Object -Property 'isMfaRegistered' -EQ $false + $users = New-GraphGETRequest -uri 'https://graph.microsoft.com/beta/reports/authenticationMethods/userRegistrationDetails?$top=999&$filter=IsAdmin eq true' -tenantid $($Item.tenant) | Where-Object -Property 'isMfaRegistered' -EQ $false if ($users) { - Write-AlertMessage -tenant $QueueItem.tenant -message "The following admins do not have MFA registered: $($users.UserPrincipalName -join ', ')" + Write-AlertMessage -tenant $Item.tenant -message "The following admins do not have MFA registered: $($users.UserPrincipalName -join ', ')" } } else { - Write-LogMessage -message 'Potentially using Duo for MFA, could not check MFA status for Admins with 100% accuracy' -API 'MFA Alerts - Informational' -tenant $QueueItem.tenant -sev Info - } + Write-LogMessage -message 'Potentially using Duo for MFA, could not check MFA status for Admins with 100% accuracy' -API 'MFA Alerts - Informational' -tenant $Item.tenant -sev Info + } } catch { - Write-LogMessage -message "Failed to check MFA status for Admins: $($_.exception.message)" -API 'MFA Alerts - Informational' -tenant $QueueItem.tenant -sev Error + Write-LogMessage -message "Failed to check MFA status for Admins: $($_.exception.message)" -API 'MFA Alerts - Informational' -tenant $Item.tenant -sev Error } } \ No newline at end of file diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAlertUsers.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAlertUsers.ps1 index 3537616d02ed..a02d2afcdc34 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAlertUsers.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertMFAAlertUsers.ps1 @@ -2,18 +2,17 @@ function Push-CIPPAlertMFAAlertUsers { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { - $users = New-GraphGETRequest -uri 'https://graph.microsoft.com/beta/reports/authenticationMethods/userRegistrationDetails?$filter=isMfaRegistered eq false and userType eq ''member''&$select=userPrincipalName,lastUpdatedDateTime,isMfaRegistered' -tenantid $($QueueItem.tenant) + $users = New-GraphGETRequest -uri 'https://graph.microsoft.com/beta/reports/authenticationMethods/userRegistrationDetails?$filter=isMfaRegistered eq false and userType eq ''member''&$select=userPrincipalName,lastUpdatedDateTime,isMfaRegistered' -tenantid $($Item.tenant) if ($users) { - Write-AlertMessage -tenant $QueueItem.tenant -message "The following $($users.Count) users do not have MFA registered: $($users.UserPrincipalName -join ', ')" + Write-AlertMessage -tenant $Item.tenant -message "The following $($users.Count) users do not have MFA registered: $($users.UserPrincipalName -join ', ')" } - + } catch { - Write-LogMessage -message "Failed to check MFA status for all users: $($_.exception.message)" -API 'MFA Alerts - Informational' -tenant $QueueItem.tenant -sev Info + Write-LogMessage -message "Failed to check MFA status for all users: $($_.exception.message)" -API 'MFA Alerts - Informational' -tenant $Item.tenant -sev Info } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertNewRole.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertNewRole.ps1 index 504bb3ea3153..8ef2727ebb66 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertNewRole.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertNewRole.ps1 @@ -2,14 +2,13 @@ function Push-CIPPAlertNewRole { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) $Deltatable = Get-CIPPTable -Table DeltaCompare try { - $Filter = "PartitionKey eq 'AdminDelta' and RowKey eq '{0}'" -f $QueueItem.tenantid + $Filter = "PartitionKey eq 'AdminDelta' and RowKey eq '{0}'" -f $Item.tenantid $AdminDelta = (Get-CIPPAzDataTableEntity @Deltatable -Filter $Filter).delta | ConvertFrom-Json -ErrorAction SilentlyContinue - $NewDelta = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/directoryRoles?`$expand=members" -tenantid $QueueItem.tenant) | Select-Object displayname, Members | ForEach-Object { + $NewDelta = (New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/directoryRoles?`$expand=members" -tenantid $Item.tenant) | Select-Object displayname, Members | ForEach-Object { @{ GroupName = $_.displayname Members = $_.Members.UserPrincipalName @@ -18,7 +17,7 @@ function Push-CIPPAlertNewRole { $NewDeltatoSave = $NewDelta | ConvertTo-Json -Depth 10 -Compress -ErrorAction SilentlyContinue | Out-String $DeltaEntity = @{ PartitionKey = 'AdminDelta' - RowKey = [string]$QueueItem.tenantid + RowKey = [string]$Item.tenantid delta = "$NewDeltatoSave" } Add-CIPPAzDataTableEntity @DeltaTable -Entity $DeltaEntity -Force @@ -27,11 +26,11 @@ function Push-CIPPAlertNewRole { foreach ($Group in $NewDelta) { $OldDelta = $AdminDelta | Where-Object { $_.GroupName -eq $Group.GroupName } $Group.members | Where-Object { $_ -notin $OldDelta.members } | ForEach-Object { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$_ has been added to the $($Group.GroupName) Role" + Write-AlertMessage -tenant $($Item.tenant) -message "$_ has been added to the $($Group.GroupName) Role" } } } } catch { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "Could not get get role changes for $($QueueItem.tenant): $(Get-NormalizedError -message $_.Exception.message)" + Write-AlertMessage -tenant $($Item.tenant) -message "Could not get get role changes for $($Item.tenant): $(Get-NormalizedError -message $_.Exception.message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertNoCAConfig.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertNoCAConfig.ps1 index 17b5363a1c54..c9b8309963ca 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertNoCAConfig.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertNoCAConfig.ps1 @@ -2,20 +2,19 @@ function Push-CIPPAlertNoCAConfig { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { - $CAAvailable = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/subscribedSkus' -tenantid $QueueItem.Tenant -erroraction stop).serviceplans + $CAAvailable = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/subscribedSkus' -tenantid $Item.Tenant -erroraction stop).serviceplans if ('AAD_PREMIUM' -in $CAAvailable.servicePlanName) { - $CAPolicies = (New-GraphGetRequest -uri 'https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies' -tenantid $QueueItem.Tenant) + $CAPolicies = (New-GraphGetRequest -uri 'https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies' -tenantid $Item.Tenant) if (!$CAPolicies.id) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message 'Conditional Access is available, but no policies could be found.' + Write-AlertMessage -tenant $($Item.tenant) -message 'Conditional Access is available, but no policies could be found.' } } } catch { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "Conditional Access Config Alert: Error occurred: $(Get-NormalizedError -message $_.Exception.message)" + Write-AlertMessage -tenant $($Item.tenant) -message "Conditional Access Config Alert: Error occurred: $(Get-NormalizedError -message $_.Exception.message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertOverusedLicenses.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertOverusedLicenses.ps1 index af90000fa4d0..d314a064a88a 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertOverusedLicenses.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertOverusedLicenses.ps1 @@ -2,26 +2,25 @@ function Push-CIPPAlertOverusedLicenses { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { $LicenseTable = Get-CIPPTable -TableName ExcludedLicenses $ExcludedSkuList = Get-CIPPAzDataTableEntity @LicenseTable - New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/subscribedSkus' -tenantid $QueueItem.tenant | ForEach-Object { + New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/subscribedSkus' -tenantid $Item.tenant | ForEach-Object { $skuid = $_ foreach ($sku in $skuid) { 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 } if ($sku.prepaidUnits.enabled - $sku.consumedUnits -lt 0) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$PrettyName has Overused licenses. Using $($_.consumedUnits) of $($_.prepaidUnits.enabled)." + Write-AlertMessage -tenant $($Item.tenant) -message "$PrettyName has Overused licenses. Using $($_.consumedUnits) of $($_.prepaidUnits.enabled)." } } } } catch { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "Overused Licenses Alert Error occurred: $(Get-NormalizedError -message $_.Exception.message)" + Write-AlertMessage -tenant $($Item.tenant) -message "Overused Licenses Alert Error occurred: $(Get-NormalizedError -message $_.Exception.message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 index ecb2aaf7b4ad..49ae4105071c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertQuotaUsed.ps1 @@ -2,19 +2,18 @@ function Push-CIPPAlertQuotaUsed { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { - New-GraphGetRequest -uri "https://graph.microsoft.com/beta/reports/getMailboxUsageDetail(period='D7')?`$format=application/json" -tenantid $QueueItem.tenant | ForEach-Object { + New-GraphGetRequest -uri "https://graph.microsoft.com/beta/reports/getMailboxUsageDetail(period='D7')?`$format=application/json" -tenantid $Item.tenant | ForEach-Object { if ($_.StorageUsedInBytes -eq 0) { continue } $PercentLeft = [math]::round($_.StorageUsedInBytes / $_.prohibitSendReceiveQuotaInBytes * 100) - if ($QueueItem.value -eq $true) { - if ($QueueItem.value) { $Value = $QueueItem.value } else { $Value = 90 } - if ($PercentLeft -gt 90) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$($_.UserPrincipalName): Mailbox is more than $($value)% full. Mailbox is $PercentLeft% full" + if ($Item.value -eq $true) { + if ($Item.value) { $Value = $Item.value } else { $Value = 90 } + if ($PercentLeft -gt 90) { + Write-AlertMessage -tenant $($Item.tenant) -message "$($_.UserPrincipalName): Mailbox is more than $($value)% full. Mailbox is $PercentLeft% full" } } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSecDefaultsUpsell.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSecDefaultsUpsell.ps1 index 1380b73b4233..b89347a828a8 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSecDefaultsUpsell.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSecDefaultsUpsell.ps1 @@ -2,26 +2,25 @@ function Push-CIPPAlertSecDefaultsUpsell { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) $LastRunTable = Get-CIPPTable -Table AlertLastRun try { - $Filter = "RowKey eq 'SecDefaultsUpsell' and PartitionKey eq '{0}'" -f $QueueItem.tenantid + $Filter = "RowKey eq 'SecDefaultsUpsell' and PartitionKey eq '{0}'" -f $Item.tenantid $LastRun = Get-CIPPAzDataTableEntity @LastRunTable -Filter $Filter $Yesterday = (Get-Date).AddDays(-1) if (-not $LastRun.Timestamp.DateTime -or ($LastRun.Timestamp.DateTime -le $Yesterday)) { try { - $SecDefaults = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/policies/identitySecurityDefaultsEnforcementPolicy' -tenantid $QueueItem.tenant) + $SecDefaults = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/policies/identitySecurityDefaultsEnforcementPolicy' -tenantid $Item.tenant) if ($SecDefaults.isEnabled -eq $false -and $SecDefaults.securityDefaultsUpsell.action -in @('autoEnable', 'autoEnabledNotify')) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message ('Security Defaults will be automatically enabled on {0}' -f $SecDefaults.securityDefaultsUpsell.dueDateTime) + Write-AlertMessage -tenant $($Item.tenant) -message ('Security Defaults will be automatically enabled on {0}' -f $SecDefaults.securityDefaultsUpsell.dueDateTime) } } catch {} $LastRun = @{ RowKey = 'SecDefaultsUpsell' - PartitionKey = $QueueItem.tenantid + PartitionKey = $Item.tenantid } Add-CIPPAzDataTableEntity @LastRunTable -Entity $LastRun -Force } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 index 7eb8f351a6ca..9614e59d340c 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertSharepointQuota.ps1 @@ -3,19 +3,18 @@ function Push-CIPPAlertSharepointQuota { [CmdletBinding()] param( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) Try { - $tenantName = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/domains' -tenantid $QueueItem.Tenant | Where-Object { $_.isInitial -eq $true }).id.Split('.')[0] - $sharepointToken = (Get-GraphToken -scope "https://$($tenantName)-admin.sharepoint.com/.default" -tenantid $QueueItem.Tenant) + $tenantName = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/domains' -tenantid $Item.Tenant | Where-Object { $_.isInitial -eq $true }).id.Split('.')[0] + $sharepointToken = (Get-GraphToken -scope "https://$($tenantName)-admin.sharepoint.com/.default" -tenantid $Item.Tenant) $sharepointToken.Add('accept', 'application/json') $sharepointQuota = (Invoke-RestMethod -Method 'GET' -Headers $sharepointToken -Uri "https://$($tenantName)-admin.sharepoint.com/_api/StorageQuotas()?api-version=1.3.2" -ErrorAction Stop).value if ($sharepointQuota) { - if ($QueueItem.value) { $Value = $QueueItem.value } else { $Value = 90 } + if ($Item.value) { $Value = $Item.value } else { $Value = 90 } $UsedStoragePercentage = [int](($sharepointQuota.GeoUsedStorageMB / $sharepointQuota.TenantStorageMB) * 100) if ($UsedStoragePercentage -gt $Value) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "SharePoint Storage is at $($UsedStoragePercentage)%. Your alert threshold is $($Value)%" + Write-AlertMessage -tenant $($Item.tenant) -message "SharePoint Storage is at $($UsedStoragePercentage)%. Your alert threshold is $($Value)%" } } } catch { diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertUnusedLicenses.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertUnusedLicenses.ps1 index 2bd58f8b6178..74be1a6e4030 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertUnusedLicenses.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertUnusedLicenses.ps1 @@ -2,26 +2,25 @@ function Push-CIPPAlertUnusedLicenses { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) try { $LicenseTable = Get-CIPPTable -TableName ExcludedLicenses $ExcludedSkuList = Get-CIPPAzDataTableEntity @LicenseTable - New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/subscribedSkus' -tenantid $QueueItem.tenant | ForEach-Object { + New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/subscribedSkus' -tenantid $Item.tenant | ForEach-Object { $skuid = $_ foreach ($sku in $skuid) { 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 } if ($sku.prepaidUnits.enabled - $sku.consumedUnits -gt 0) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "$PrettyName has unused licenses. Using $($_.consumedUnits) of $($_.prepaidUnits.enabled)." + Write-AlertMessage -tenant $($Item.tenant) -message "$PrettyName has unused licenses. Using $($_.consumedUnits) of $($_.prepaidUnits.enabled)." } } } } catch { - Write-AlertMessage -tenant $($QueueItem.tenant) -message "Unused Licenses Alert Error occurred: $(Get-NormalizedError -message $_.Exception.message)" + Write-AlertMessage -tenant $($Item.tenant) -message "Unused Licenses Alert Error occurred: $(Get-NormalizedError -message $_.Exception.message)" } } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertVppTokenExpiry.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertVppTokenExpiry.ps1 index d18dd28dd11d..d9a2e70d6531 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertVppTokenExpiry.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-CIPPAlertVppTokenExpiry.ps1 @@ -2,31 +2,30 @@ function Push-CIPPAlertVppTokenExpiry { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] - $QueueItem, - $TriggerMetadata + $Item ) $LastRunTable = Get-CIPPTable -Table AlertLastRun try { - $Filter = "RowKey eq 'VppTokenExpiry' and PartitionKey eq '{0}'" -f $QueueItem.tenantid + $Filter = "RowKey eq 'VppTokenExpiry' and PartitionKey eq '{0}'" -f $Item.tenantid $LastRun = Get-CIPPAzDataTableEntity @LastRunTable -Filter $Filter $Yesterday = (Get-Date).AddDays(-1) if (-not $LastRun.Timestamp.DateTime -or ($LastRun.Timestamp.DateTime -le $Yesterday)) { try { - $VppTokens = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceAppManagement/vppTokens' -tenantid $QueueItem.tenant).value + $VppTokens = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/deviceAppManagement/vppTokens' -tenantid $Item.tenant).value foreach ($Vpp in $VppTokens) { if ($Vpp.state -ne 'valid') { - Write-AlertMessage -tenant $($QueueItem.tenant) -message 'Apple Volume Purchase Program Token is not valid, new token required' + Write-AlertMessage -tenant $($Item.tenant) -message 'Apple Volume Purchase Program Token is not valid, new token required' } if ($Vpp.expirationDateTime -lt (Get-Date).AddDays(30) -and $Vpp.expirationDateTime -gt (Get-Date).AddDays(-7)) { - Write-AlertMessage -tenant $($QueueItem.tenant) -message ('Apple Volume Purchase Program token expiring on {0}' -f $Vpp.expirationDateTime) + Write-AlertMessage -tenant $($Item.tenant) -message ('Apple Volume Purchase Program token expiring on {0}' -f $Vpp.expirationDateTime) } } } catch {} $LastRun = @{ RowKey = 'VppTokenExpiry' - PartitionKey = $QueueItem.tenantid + PartitionKey = $Item.tenantid } Add-CIPPAzDataTableEntity @LastRunTable -Entity $LastRun -Force } diff --git a/Modules/CIPPCore/Public/Entrypoints/Push-SchedulerAlert.ps1 b/Modules/CIPPCore/Public/Entrypoints/Push-SchedulerAlert.ps1 index 30a4b2583cde..48b5ac8f474b 100644 --- a/Modules/CIPPCore/Public/Entrypoints/Push-SchedulerAlert.ps1 +++ b/Modules/CIPPCore/Public/Entrypoints/Push-SchedulerAlert.ps1 @@ -1,42 +1,59 @@ function Push-SchedulerAlert { param ( - $QueueItem, $TriggerMetadata + $Item ) - $Tenant = $QueueItem + try { $Table = Get-CIPPTable -Table SchedulerConfig - if ($Tenant.tag -eq 'AllTenants') { + if ($Item.Tag -eq 'AllTenants') { $Filter = "RowKey eq 'AllTenants' and PartitionKey eq 'Alert'" } else { - $Filter = "RowKey eq '{0}' and PartitionKey eq 'Alert'" -f $Tenant.tenantid + $Filter = "RowKey eq '{0}' and PartitionKey eq 'Alert'" -f $Item.Tenantid } $Alerts = Get-CIPPAzDataTableEntity @Table -Filter $Filter - $IgnoreList = @('Etag', 'PartitionKey', 'Timestamp', 'RowKey', 'tenantid', 'tenant', 'type') - $alertList = $Alerts | Select-Object * -ExcludeProperty $IgnoreList - foreach ($task in ($AlertList.psobject.members | Where-Object { $_.MemberType -EQ 'NoteProperty' -and $_.value -ne $false })) { + $AlertList = $Alerts | Select-Object * -ExcludeProperty $IgnoreList + $Batch = foreach ($task in ($AlertList.psobject.members | Where-Object { $_.MemberType -EQ 'NoteProperty' -and $_.value -ne $false })) { $Table = Get-CIPPTable -TableName AlertRunCheck - $Filter = "PartitionKey eq '{0}' and RowKey eq '{1}' and Timestamp ge datetime'{2}'" -f $tenant.tenant, $task.Name, (Get-Date).AddMinutes(-10).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss') + $Filter = "PartitionKey eq '{0}' and RowKey eq '{1}' and Timestamp ge datetime'{2}'" -f $Item.Tenant, $task.Name, (Get-Date).AddMinutes(-10).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss') $ExistingMessage = Get-CIPPAzDataTableEntity @Table -Filter $Filter if (!$ExistingMessage) { - $QueueItem = [pscustomobject]@{ - tenant = $tenant.tenant - tenantid = $tenant.tenantid + [pscustomobject]@{ + Tenant = $Item.Tenant + Tenantid = $Item.Tenantid FunctionName = "CIPPAlert$($Task.Name)" value = $Task.value } - Push-OutputBinding -Name QueueItemOut -Value $QueueItem - $QueueItem | Add-Member -MemberType NoteProperty -Name 'RowKey' -Value $task.Name -Force - $QueueItem | Add-Member -MemberType NoteProperty -Name 'PartitionKey' -Value $tenant.tenant -Force - Add-CIPPAzDataTableEntity @Table -Entity $QueueItem -Force + #Push-OutputBinding -Name QueueItemOut -Value $Item + $Item | Add-Member -MemberType NoteProperty -Name 'RowKey' -Value $task.Name -Force + $Item | Add-Member -MemberType NoteProperty -Name 'PartitionKey' -Value $Item.Tenant -Force + + try { + $null = Add-CIPPAzDataTableEntity @Table -Entity $Item -Force -ErrorAction Stop + } catch { + Write-Host "################### Error updating alert $($_.Exception.Message) - $($Item | ConvertTo-Json)" + } } else { - Write-Host ('ALERTS: Duplicate run found. Ignoring. Tenant: {0}, Task: {1}' -f $tenant.tenant, $task.Name) + Write-Host ('ALERTS: Duplicate run found. Ignoring. Tenant: {0}, Task: {1}' -f $Item.tenant, $task.Name) } } + if (($Batch | Measure-Object).Count -gt 0) { + $InputObject = [PSCustomObject]@{ + OrchestratorName = 'Alerts' + SkipLog = $true + Batch = @($Batch) + } + #Write-Host ($Batch | ConvertTo-Json) + $InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject ($InputObject | ConvertTo-Json -Depth 5) + Write-Host "Started alert orchestration with ID = '$InstanceId'" + #$Orchestrator = New-OrchestrationCheckStatusResponse -Request $Request -InstanceId $InstanceId + } else { + Write-Host 'No alerts to process' + } } catch { $Message = 'Exception on line {0} - {1}' -f $_.InvocationInfo.ScriptLineNumber, $_.Exception.Message - Write-LogMessage -message $Message -API 'Alerts' -tenant $tenant.tenant -sev Error + Write-LogMessage -message $Message -API 'Alerts' -tenant $Item.tenant -sev Error } } \ No newline at end of file diff --git a/Modules/CIPPCore/Public/GraphHelper/Write-CippFunctionStats.ps1 b/Modules/CIPPCore/Public/GraphHelper/Write-CippFunctionStats.ps1 index e4102cd31521..f302cfcfb306 100644 --- a/Modules/CIPPCore/Public/GraphHelper/Write-CippFunctionStats.ps1 +++ b/Modules/CIPPCore/Public/GraphHelper/Write-CippFunctionStats.ps1 @@ -16,20 +16,23 @@ function Write-CippFunctionStats { $TimeSpan = New-TimeSpan -Start $Start -End $End $Duration = [int]$TimeSpan.TotalSeconds + $StatEntity = @{} # Flatten data to json string - $Entity.PartitionKey = $FunctionType - $Entity.RowKey = $RowKey - $Entity.Start = $Start - $Entity.End = $End - $Entity.Duration = $Duration - $Entity.ErrorMsg = $ErrorMsg + $StatEntity.PartitionKey = $FunctionType + $StatEntity.RowKey = $RowKey + $StatEntity.Start = $Start + $StatEntity.End = $End + $StatEntity.Duration = $Duration + $StatEntity.ErrorMsg = $ErrorMsg $Entity = [PSCustomObject]$Entity foreach ($Property in $Entity.PSObject.Properties.Name) { if ($Entity.$Property.GetType().Name -in ('Hashtable', 'PSCustomObject')) { - $Entity.$Property = [string]($Entity.$Property | ConvertTo-Json -Compress) + $StatEntity.$Property = [string]($Entity.$Property | ConvertTo-Json -Compress) } } - Add-CIPPAzDataTableEntity @Table -Entity $Entity -Force + $StatsEntity = [PSCustomObject]$StatsEntity + Write-Host ($StatEntity | ConvertTo-Json) + Add-CIPPAzDataTableEntity @Table -Entity $StatsEntity -Force } catch { Write-Host "Exception logging stats $($_.Exception.Message)" } diff --git a/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 b/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 index dd4acff806e8..1c7e177e3555 100644 --- a/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 +++ b/Modules/CIPPCore/Public/Invoke-CIPPStandardsRun.ps1 @@ -94,5 +94,5 @@ function Invoke-CIPPStandardsRun { $InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject ($InputObject | ConvertTo-Json -Depth 5) Write-Host "Started orchestration with ID = '$InstanceId'" - $Orchestrator = New-OrchestrationCheckStatusResponse -Request $Request -InstanceId $InstanceId + #$Orchestrator = New-OrchestrationCheckStatusResponse -Request $Request -InstanceId $InstanceId } \ No newline at end of file diff --git a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAuditLog.ps1 b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAuditLog.ps1 index 1dcd16e89cdb..e3682928503c 100644 --- a/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAuditLog.ps1 +++ b/Modules/CIPPCore/Public/Standards/Invoke-CIPPStandardAuditLog.ps1 @@ -4,13 +4,13 @@ function Invoke-CIPPStandardAuditLog { Internal #> param($Tenant, $Settings) - - $AuditLogEnabled = (New-ExoRequest -tenantid $Tenant -cmdlet 'Get-AdminAuditLogConfig').UnifiedAuditLogIngestionEnabled + Write-Host ($Settings | ConvertTo-Json) + $AuditLogEnabled = (New-ExoRequest -tenantid $Tenant -cmdlet 'Get-AdminAuditLogConfig' -Select UnifiedAuditLogIngestionEnabled).UnifiedAuditLogIngestionEnabled If ($Settings.remediate) { Write-Host 'Time to remediate' - - $DehydratedTenant = (New-ExoRequest -tenantid $Tenant -cmdlet 'Get-OrganizationConfig').IsDehydrated + + $DehydratedTenant = (New-ExoRequest -tenantid $Tenant -cmdlet 'Get-OrganizationConfig' -Select IsDehydrated).IsDehydrated if ($DehydratedTenant) { try { New-ExoRequest -tenantid $Tenant -cmdlet 'Enable-OrganizationCustomization' @@ -20,7 +20,7 @@ function Invoke-CIPPStandardAuditLog { Write-LogMessage -API 'Standards' -tenant $tenant -message "Failed to enable organization customization. Error: $ErrorMessage" -sev Debug } } - + try { if ($AuditLogEnabled) { Write-LogMessage -API 'Standards' -tenant $tenant -message 'Unified Audit Log already enabled.' -sev Info diff --git a/Modules/CippEntrypoints/CippEntrypoints.psm1 b/Modules/CippEntrypoints/CippEntrypoints.psm1 index a651d072339f..67a480956b2d 100644 --- a/Modules/CippEntrypoints/CippEntrypoints.psm1 +++ b/Modules/CippEntrypoints/CippEntrypoints.psm1 @@ -51,31 +51,44 @@ function Receive-CippQueueTrigger { function Receive-CippOrchestrationTrigger { param($Context) - $DurableRetryOptions = @{ - FirstRetryInterval = (New-TimeSpan -Seconds 5) - MaxNumberOfAttempts = 3 - BackoffCoefficient = 2 - } - if (Test-Json -Json $Context.Input) { - $OrchestratorInput = $Context.Input | ConvertFrom-Json - } else { - $OrchestratorInput = $Context.Input - } - Write-Host ($Context | ConvertTo-Json -Depth 10) - $RetryOptions = New-DurableRetryOptions @DurableRetryOptions - Write-LogMessage -API $OrchestratorInput.OrchestratorName -tenant $OrchestratorInput.TenantFilter -message "Started $($OrchestratorInput.OrchestratorName)" -sev info + try { - if (!$OrchestratorInput.Batch -or ($OrchestratorInput.Batch | Measure-Object).Count -eq 0) { - $Batch = (Invoke-ActivityFunction -FunctionName 'CIPPActivityFunction' -Input $OrchestratorInput.QueueFunction) - } else { - $Batch = $OrchestratorInput.Batch - } + if (Test-Json -Json $Context.Input) { + $OrchestratorInput = $Context.Input | ConvertFrom-Json + } else { + $OrchestratorInput = $Context.Input + } - foreach ($Item in $Batch) { - Invoke-DurableActivity -FunctionName 'CIPPActivityFunction' -Input $Item -NoWait -RetryOptions $RetryOptions - } + $DurableRetryOptions = @{ + FirstRetryInterval = (New-TimeSpan -Seconds 5) + MaxNumberOfAttempts = if ($OrchestratorInput.MaxAttempts) { $OrchestratorInput.MaxAttempts } else { 3 } + BackoffCoefficient = 2 + } + #Write-Host ($OrchestratorInput | ConvertTo-Json -Depth 10) + $RetryOptions = New-DurableRetryOptions @DurableRetryOptions - Write-LogMessage -API $OrchestratorInput.OrchestratorName -tenant $tenant -message "Finished $($OrchestratorInput.OrchestratorName)" -sev Info + if ($Context.IsReplaying -ne $true -and -not $Context.Input.SkipLog) { + Write-LogMessage -API $OrchestratorInput.OrchestratorName -tenant $OrchestratorInput.TenantFilter -message "Started $($OrchestratorInput.OrchestratorName)" -sev info + } + + if (!$OrchestratorInput.Batch -or ($OrchestratorInput.Batch | Measure-Object).Count -eq 0) { + $Batch = (Invoke-ActivityFunction -FunctionName 'CIPPActivityFunction' -Input $OrchestratorInput.QueueFunction -ErrorAction Stop) + } else { + $Batch = $OrchestratorInput.Batch + } + + if (($Batch | Measure-Object).Count -gt 0) { + foreach ($Item in $Batch) { + $null = Invoke-DurableActivity -FunctionName 'CIPPActivityFunction' -Input $Item -NoWait -RetryOptions $RetryOptions -ErrorAction Stop + } + } + + if ($Context.IsReplaying -ne $true -and -not $Context.Input.SkipLog) { + Write-LogMessage -API $OrchestratorInput.OrchestratorName -tenant $tenant -message "Finished $($OrchestratorInput.OrchestratorName)" -sev Info + } + } catch { + Write-Host "Orchestrator error $($_.Exception.Message)" + } } function Receive-CippActivityTrigger { @@ -105,7 +118,7 @@ function Receive-CippActivityTrigger { ErrorMsg = $ErrorMsg } - Write-Information '####### Adding stats' + #Write-Information '####### Adding stats' Write-CippFunctionStats @Stats } diff --git a/Scheduler_GetQueue/function.json b/Scheduler_GetQueue/function.json index d0f59a682e3c..122f86c71d70 100644 --- a/Scheduler_GetQueue/function.json +++ b/Scheduler_GetQueue/function.json @@ -11,6 +11,11 @@ "direction": "out", "name": "QueueItem", "queueName": "CIPPGenericQueue" + }, + { + "name": "starter", + "type": "durableClient", + "direction": "in" } ] } diff --git a/Scheduler_GetQueue/run.ps1 b/Scheduler_GetQueue/run.ps1 index f14ccc274dd4..2e80dfd588a1 100644 --- a/Scheduler_GetQueue/run.ps1 +++ b/Scheduler_GetQueue/run.ps1 @@ -5,7 +5,7 @@ $Tenants = Get-CIPPAzDataTableEntity @Table | Where-Object -Property PartitionKe $Tasks = foreach ($Tenant in $Tenants) { if ($Tenant.tenant -ne 'AllTenants') { - [pscustomobject]@{ + [pscustomobject]@{ Tenant = $Tenant.tenant Tag = 'SingleTenant' TenantID = $Tenant.tenantid @@ -15,7 +15,7 @@ $Tasks = foreach ($Tenant in $Tenants) { Write-Host 'All tenants, doing them all' $TenantList = Get-Tenants foreach ($t in $TenantList) { - [pscustomobject]@{ + [pscustomobject]@{ Tenant = $t.defaultDomainName Tag = 'AllTenants' TenantID = $t.customerId @@ -23,19 +23,22 @@ $Tasks = foreach ($Tenant in $Tenants) { } } } -} +} -foreach ($Task in $Tasks) { - $QueueItem = [pscustomobject]@{ +$Batch = foreach ($Task in $Tasks) { + [pscustomobject]@{ Tenant = $task.tenant Tenantid = $task.tenantid Tag = $task.tag Type = $task.type FunctionName = "Scheduler$($Task.Type)" } - try { - Push-OutputBinding -Name QueueItem -Value $QueueItem - } catch { - Write-Host "Could not launch queue item for $($Task.tenant): $($_.Exception.Message)" - } -} \ No newline at end of file +} +$InputObject = [PSCustomObject]@{ + OrchestratorName = 'Scheduler' + Batch = @($Batch) +} +#Write-Host ($InputObject | ConvertTo-Json) +$InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject ($InputObject | ConvertTo-Json -Depth 5) +Write-Host "Started orchestration with ID = '$InstanceId'" +#$Orchestrator = New-OrchestrationCheckStatusResponse -Request $Request -InstanceId $InstanceId \ No newline at end of file From 9ec149fa2dedb4388761c436516e3b02470f0013 Mon Sep 17 00:00:00 2001 From: John Duprey Date: Sat, 9 Mar 2024 11:40:06 -0800 Subject: [PATCH 16/16] up version --- version_latest.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version_latest.txt b/version_latest.txt index 804440660c71..fb467b15735a 100644 --- a/version_latest.txt +++ b/version_latest.txt @@ -1 +1 @@ -5.2.1 \ No newline at end of file +5.2.2 \ No newline at end of file