Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Specifying credentials and connecting to Office 365 module
- $Credential = Get-Credential
- $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
- Connect-MsolService -Credential $Credential
- # Getting a list of tenant IDs (clients) used to connect to their environment
- $Tenants = (Get-MsolPartnerContract)
- $JobsInProgress = $null
- $TenantsRemaining = 0 # Tickets every time a new tenant is being processed
- # Running command against all tenants
- # Keeping track of how long each tenant takes
- $StopWatch = [System.Diagnostics.StopWatch]::StartNew()
- ForEach ($Tenant in $Tenants) {
- # Get primary domain for the tenant
- $Domain = (Get-MsolDomain -TenantId $Tenant.TenantId.Guid `
- | Where-Object { `
- $_.Name -NotLike "*onmicrosoft.com" -and `
- $_.Name -NotLike "*microsoftonline.com" })[0].Name
- Start-Job -Name $Tenant.Name -ScriptBlock {
- $Domain = $args[1]
- $Credential = $args[2]
- # Authenticating to Exchange Online for the tenant
- $Session = New-PSSession `
- -ConfigurationName Microsoft.Exchange `
- -ConnectionUri https://outlook.office365.com/powershell-liveid?DelegatedOrg=$Domain `
- -Credential $Credential `
- -Authentication Basic `
- -AllowRedirection
- try {
- Import-PSSession $Session `
- -ErrorAction 'silentlycontinue' `
- -DisableNameChecking `
- | Out-Null
- $ExistingRule = Get-TransportRule | Where-Object { $_.Name -eq 'Block Microsoft License Verification' }
- # Remove existing rule
- if ($ExistingRule) {
- Remove-TransportRule $ExistingRule.Name -Confirm:$False
- }
- else {
- New-TransportRule `
- -Name 'Block Microsoft License Verification' `
- -SubjectContainsWords 'Microsoft License Verification' `
- -DeleteMessage $True `
- | Out-Null
- }
- Remove-PSSession $Session
- }
- catch {
- Write-Error $_.Exception.Message
- }
- } -ArgumentList @($Domain, $Credential)
- }
- # Waiting for jobs to finish
- do {
- Get-Job | Where-Object State -eq 'Completed' | Remove-Job -Force
- $JobsInProgress = Get-Job
- $ElapsedSeconds = [math]::Round($StopWatch.Elapsed.TotalSeconds, 2)
- $TenantsRemaining = $JobsInProgress.Length
- Write-Output "Jobs have been running for $ElapsedSeconds seconds... $TenantsRemaining tenants remaining."
- Get-Job | Receive-Job # Check for errors
- # Removing failed jobs
- Get-Job | Where-Object State -ne 'Running' | Remove-Job -Force
- Start-Sleep -Seconds 10
- } until ($JobsInProgress.Length -eq 0)
- Get-PSSession | Remove-PSSession
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement