Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change to use Get-CippException for error logging #974

Merged
merged 2 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Modules/CIPPCore/CIPPCore.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -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): $_"
}
}
Expand Down
5 changes: 3 additions & 2 deletions Modules/CIPPCore/Public/Add-CIPPApplicationPermission.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
Expand Down
3 changes: 2 additions & 1 deletion Modules/CIPPCore/Public/Add-CIPPAzDataTableEntity.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down
4 changes: 2 additions & 2 deletions Modules/CIPPCore/Public/Add-CIPPBPAField.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ 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' {
$Result[$fieldName], [string]$FieldValue
}
}
Add-CIPPAzDataTableEntity @Table -Entity $Result -Force
}
}
3 changes: 2 additions & 1 deletion Modules/CIPPCore/Public/Add-CIPPScheduledTask.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
}
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/Assert-CippVersion.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ function Assert-CippVersion {
OutOfDateCIPP = ([version]$RemoteCIPPVersion -gt [version]$CIPPVersion)
OutOfDateCIPPAPI = ([version]$RemoteAPIVersion -gt [version]$APIVersion)
}
}
}
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/Clear-CippDurables.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,4 @@ function Clear-CippDurables {
}
$null = Get-CippTable -TableName ('{0}History' -f $FunctionName)
Write-Information 'Durable Orchestrators and Queues have been cleared'
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,17 @@ Function Invoke-RemoveScheduledItem {
[CmdletBinding()]
param($Request, $TriggerMetadata)

$APIName = 'RemoveScheduledItem'
$User = $request.headers.'x-ms-client-principal'

$task = @{
RowKey = $Request.Query.ID
PartitionKey = 'ScheduledTask'
}
$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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions Modules/CIPPCore/Public/Get-CIPPBitlockerKey.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}


2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/Get-CIPPDomainAnalyser.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ function Get-CIPPDomainAnalyser {
$Results = @()
}
return $Results
}
}
10 changes: 5 additions & 5 deletions Modules/CIPPCore/Public/Get-CIPPLAPSPassword.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ function Get-CIPPLapsPassword {
param (
$device,
$TenantFilter,
$APIName = "Get LAPS Password",
$APIName = 'Get LAPS Password',
$ExecutingUser
)

Expand All @@ -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)"
}
}

Expand Down
6 changes: 3 additions & 3 deletions Modules/CIPPCore/Public/Get-CIPPLicenseOverview.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 }
Expand Down Expand Up @@ -63,7 +63,7 @@ function Get-CIPPLicenseOverview {
TermInfo = [string]($TermInfo | ConvertTo-Json -Depth 10 -Compress)
'PartitionKey' = 'License'
'RowKey' = "$($singlereq.Tenant) - $($sku.skuid)"
}
}
}
}
return $GraphRequest
Expand Down
6 changes: 3 additions & 3 deletions Modules/CIPPCore/Public/Get-CIPPMFAState.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function Get-CIPPMFAState {
$Policy.conditions.users.excludeUsers.foreach({ $ExcludeAllUsers.Add($_) | Out-Null })
continue
}
}
}
}
} catch {
}
Expand Down Expand Up @@ -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
Expand All @@ -92,7 +92,7 @@ function Get-CIPPMFAState {
RowKey = [string]($_.UserPrincipalName).replace('#', '')
PartitionKey = 'users'
}

}
return $GraphRequest
}
16 changes: 8 additions & 8 deletions Modules/CIPPCore/Public/Get-CIPPOutOfOffice.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
36 changes: 19 additions & 17 deletions Modules/CIPPCore/Public/Get-CIPPPartnerAzSubscriptions.ps1
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
function Get-CIPPPartnerAzSubscriptions {
param (
$TenantFilter,
$APIName = "Get-CIPPPartnerAzSubscriptions"
$APIName = 'Get-CIPPPartnerAzSubscriptions'
)

try {
Expand All @@ -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 {
Expand All @@ -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
}
}
5 changes: 3 additions & 2 deletions Modules/CIPPCore/Public/Get-CIPPPerUserMFA.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
}
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/Get-CIPPSPOTenant.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 } }
}
}
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/Get-CIPPSchemaExtensions.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
}
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/Get-SlackAlertBlocks.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -262,4 +262,4 @@ function Get-SlackAlertBlocks {
blocks = $Blocks
}
}
}
}
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/GraphHelper/New-passwordString.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 7 additions & 6 deletions Modules/CIPPCore/Public/Invoke-RemoveAPDevice.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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]@{
Expand Down
Loading