1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| function Manage-Office365Resources { [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [ValidateSet('User','Team')] [string]$ResourceType, [string]$DisplayName )
$managementReport = [PSCustomObject]@{ Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' Operations = @() SuccessRate = 0 LicenseDetails = @{} }
try { $token = Get-MsalToken -ClientId $env:AZURE_CLIENT_ID -TenantId $env:AZURE_TENANT_ID
switch ($ResourceType) { 'User' { $userParams = @{ Method = 'POST' Uri = "https://graph.microsoft.com/v1.0/users" Headers = @{ Authorization = "Bearer $($token.AccessToken)" } Body = @{ accountEnabled = $true displayName = $DisplayName mailNickname = $DisplayName.Replace(' ','').ToLower() userPrincipalName = "$($DisplayName.Replace(' ',''))@$env:AZURE_DOMAIN" passwordProfile = @{ forceChangePasswordNextSignIn = $true password = [System.Convert]::ToBase64String((1..12 | ForEach-Object { [char](Get-Random -Minimum 33 -Maximum 126) })) } } | ConvertTo-Json } $response = Invoke-RestMethod @userParams $managementReport.Operations += [PSCustomObject]@{ Type = 'UserCreated' ID = $response.id } } 'Team' { $teamParams = @{ Method = 'POST' Uri = "https://graph.microsoft.com/v1.0/teams" Headers = @{ Authorization = "Bearer $($token.AccessToken)" } Body = @{ "template@odata.bind" = "https://graph.microsoft.com/v1.0/teamsTemplates('standard')" displayName = $DisplayName description = "Automatically created team" } | ConvertTo-Json } $response = Invoke-RestMethod @teamParams $managementReport.Operations += [PSCustomObject]@{ Type = 'TeamProvisioned' ID = $response.id } } }
$licenseData = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/subscribedSkus" \ -Headers @{ Authorization = "Bearer $($token.AccessToken)" } $managementReport.LicenseDetails = $licenseData.value | Group-Object skuPartNumber -AsHashTable | ForEach-Object { @{$_.Key = $_.Value.consumedUnits} }
$managementReport.SuccessRate = ($managementReport.Operations.Count / 1) * 100 } catch { Write-Error "资源管理失败: $_" }
$managementReport | Export-Clixml -Path "$env:TEMP/GraphReport_$(Get-Date -Format yyyyMMdd).xml" return $managementReport }
|