@@ -5,7 +5,8 @@ function Set-CIPPUserLicense {
55 [Parameter (Mandatory )][string ]$TenantFilter ,
66 [Parameter ()][array ]$AddLicenses = @ (),
77 [Parameter ()][array ]$RemoveLicenses = @ (),
8- $Headers
8+ $Headers ,
9+ $APIName = ' Set User License'
910 )
1011
1112 # Build the addLicenses array
@@ -28,7 +29,25 @@ function Set-CIPPUserLicense {
2829 Write-Host " License body JSON: $LicenseBodyJson "
2930
3031 try {
31- $null = New-GraphPostRequest - uri " https://graph.microsoft.com/beta/users/$UserId /assignLicense" - tenantid $TenantFilter - type POST - body $LicenseBodyJson - Verbose
32+ try {
33+ $null = New-GraphPostRequest - uri " https://graph.microsoft.com/beta/users/$UserId /assignLicense" - tenantid $TenantFilter - type POST - body $LicenseBodyJson - Verbose
34+ } catch {
35+ # Handle if the error is due to missing usage location
36+ if ($_.Exception.Message -like ' *invalid usage location*' ) {
37+ $Table = Get-CippTable - tablename ' UserSettings'
38+ $UserSettings = Get-CIPPAzDataTableEntity @Table - Filter " PartitionKey eq 'UserSettings' and RowKey eq 'allUsers'"
39+ if ($UserSettings ) { $DefaultUsageLocation = (ConvertFrom-Json $UserSettings.JSON - Depth 5 - ErrorAction SilentlyContinue).usageLocation.value }
40+ $DefaultUsageLocation ?? = ' US' # Fallback to US if not set
41+
42+ $UsageLocationJson = ConvertTo-Json - InputObject @ {' usageLocation' = $DefaultUsageLocation } - Depth 5 - Compress
43+ $null = New-GraphPostRequest - uri " https://graph.microsoft.com/beta/users/$UserId " - tenantid $TenantFilter - type PATCH - body $UsageLocationJson - Verbose
44+ Write-LogMessage - Headers $Headers - API $APIName - tenant $TenantFilter - message " Set usage location for user $UserId to $DefaultUsageLocation " - Sev ' Info'
45+ # Retry assigning the license
46+ $null = New-GraphPostRequest - uri " https://graph.microsoft.com/beta/users/$UserId /assignLicense" - tenantid $TenantFilter - type POST - body $LicenseBodyJson - Verbose
47+ } else {
48+ throw $_
49+ }
50+ }
3251 } catch {
3352 $ErrorMessage = Get-CippException - Exception $_
3453 Write-LogMessage - Headers $Headers - API $APIName - tenant $TenantFilter - message " Failed to assign the license. Error: $ ( $ErrorMessage.NormalizedError ) " - Sev Error - LogData $ErrorMessage
0 commit comments