private/New-PhoneLicense.ps1
function New-PhoneLicense { Param ([String]$ObjectId, [Boolean]$WaitForLicense) Write-OutputProxy " Activating Phone License... " $user = $null $tries = 0 while ($null -eq $user -and $tries -lt 10) { try { $user = Get-MsolUser -ObjectId $ObjectId | Select-Object UsageLocation, UserPrincipalName, Licenses } catch { $tries++ if ($tries -eq 10) { Write-OutputProxy " [Failed]" Write-OutputProxy " Finding ApplicationInstance timed out" return $false } Write-OutputProxy "" Write-OutputProxy " Waiting for ApplicationInstance to be synced" for ($i = 0; $i -lt 6; $i++) { Write-OutputProxy "." Start-Sleep -Seconds 5 } Write-OutputProxy "." } } if ($user.Licenses.Where( { $_.AccountSkuId -match "MCOEV$" }, 'First').Count -gt 0) { $teamsSkuId = (Get-MsolAccountSku | Where-Object { $_.SkuPartNumber -eq "TEAMS_COMMERCIAL_TRIAL" }).AccountSkuId $mcoevSkuId = (Get-MsolAccountSku | Where-Object { $_.SkuPartNumber -eq "MCOEV" }).AccountSkuId Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicenses $mcoevSkuId -ErrorAction SilentlyContinue Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -RemoveLicenses $teamsSkuId -ErrorAction SilentlyContinue } if ($user.Licenses.Where( { $_.AccountSkuId -like "*PHONESYSTEM_VIRTUALUSER" }, 'First').Count -gt 0) { Write-OutputProxy " [Done]" Write-OutputProxy " Phone License is already assigned" return $true } if ( [string]::IsNullOrEmpty($user.UsageLocation) ) { # set location based on phonenumber Set-MsolUser -ObjectId $ObjectId -UsageLocation "US" Start-Sleep -Seconds 5 } $phoneSku = Get-MsolAccountSku | Where-Object { $_.SkuPartNumber -eq "PHONESYSTEM_VIRTUALUSER" } $tries = 0 while ( ( $phoneSku.ActiveUnits -le $phoneSku.ConsumedUnits ) -and $tries -le 10 ) { if ( $phoneSku.ActiveUnits -le $phoneSku.ConsumedUnits ) { if ( -not $WaitForLicense -or $tries -eq 10 ) { Write-OutputProxy "[Failed]" Write-OutputProxy " No Phone Licenses available" return $false } } Write-OutputProxy " Waiting for Licenses to be freed" (0..5).foreach{ Write-OutputProxy "." Start-Sleep -Seconds 5 } Write-OutputProxy "." $phoneSku = Get-MsolAccountSku | Where-Object { $_.SkuPartNumber -eq "PHONESYSTEM_VIRTUALUSER" } $tries++ } try { Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -AddLicenses $phoneSku.AccountSkuId Write-OutputProxy " [Done]" return $true } catch { Write-OutputProxy "[Failed]" Write-OutputProxy " $($_.Exception)" return $false } } |