如何用If Else修改PowerShell计算属性处理Azure AD用户SMTP地址
Alright, let's adjust your PowerShell script to fulfill those three requirements perfectly. Below is the updated script with detailed breakdowns of the key changes:
#Import Module If (!(Get-Module "*MSOnline*")) {Import-Module MSOnline} If (!(Get-Module "*Exchange*")) {Import-Module $((Get-ChildItem -Path $($env:LOCALAPPDATA + "\Apps\2.0\") -Filter Microsoft.Exchange.Management.ExoPowershellModule.dll -Recurse).FullName | ?{ $_ -notmatch "_none_" } | select -First 1)} #Set admin UPN $UPN = 'Global.Admin@domain.com' #This connects to Azure Active Directory & Exchange Online Connect-MsolService $EXOSession = New-ExoPSSession -UserPrincipalName $UPN Import-PSSession $EXOSession -DisableNameChecking -AllowClobber $startsWith = @( 'Test' 'Sync_' ) $endsWith = @( '365' '\$' 'svc' 'Sync' 'user' ) $pattern = '^({0})|({1})$' -f $($startsWith -join '|'), $($endsWith -join '|') # Member Outputs for Microsoft.Online.Administration.User $allUsers = Get-MsolUser -All -EnabledFilter EnabledOnly | Where-Object { ($_.UserPrincipalName -notmatch $pattern) -and ($_.UserPrincipalName -notlike '*#EXT#*') -and ($_.DisplayName -notmatch 'Admin|Calendar|Room|Prod|Account|Fax|Team|Office|Test|User') } | Select-Object FirstName, LastName, UserPrincipalName, @{Label = 'SMTP Address'; Expression = { if ($_.UserPrincipalName -match 'Company1.onmicrosoft.com') { # Keep all SMTP addresses for users with matching UPN domain ($_.proxyAddresses | Where-Object { $_ -like "*smtp*" }) -replace 'smtp:' -join ';' } else { # Filter out the two internal domains for other users ($_.proxyAddresses | Where-Object { $_ -like "*smtp*" -and $_ -notlike "*@Company1.mail.onmicrosoft.com" -and $_ -notlike "*@Company1.onmicrosoft.com" }) -replace 'smtp:' -join ';' } }}, AlternateEmailAddresses, UsageLocation, isLicensed, @{Label = 'Licenses'; Expression = { # Strip the Company1: prefix from license SKUs ($_.Licenses.AccountSkuId -replace 'Company1:', '') -join ';' }}, PasswordNeverExpires, BlockCredential $allUsers | Out-GridView
Key Changes Explained
SMTP Address Column Logic:
We added a conditional check tied to the user'sUserPrincipalName:- If the UPN includes
Company1.onmicrosoft.com, we retain the original behavior of listing all SMTP addresses. - For users without that UPN domain, we add extra filters to exclude addresses ending with
@Company1.mail.onmicrosoft.comor@Company1.onmicrosoft.com, leaving only regular external SMTP addresses.
- If the UPN includes
Licenses Column Cleanup:
The Licenses column now extracts theAccountSkuIdfrom each license object, then removes theCompany1:prefix using-replace. This leaves only the plan name (likeEnterpriseE1) for clean readability.
内容的提问来源于stack exchange,提问作者Senior Systems Engineer
相关产品推荐
相关产品推荐

