O365 PowerShell: Find users that have specific product license services enabled - powershell

I'm using the following article View account license and service details with Office 365 PowerShell to try to obtain a report of all users in our tenant where the product license Office 365 Enterprise E3 is assigned but with only the the service Exchange Online (Plan 2) enabled.
The article suggests this can be done with a command similar to the following:
Get-MsolUser |
Where-Object {
$_.isLicensed -eq $true
-and $_.Licenses[0].ServiceStatus[16].ProvisioningStatus -eq "Enabled"
}
In my case [16] being the 17th service in the list for Office 365 Enterprise E3.
There are additional lines before to set the criteria for the rest of the services as "disabled" but hopefully you get the idea however, the article also states that the index number reflects the order that the product license and service plan appears when running either of the below script blocks:
Licenses:
Get-MsolUser -UserPrincipalName o365.test1#tenant.com | Format-List DisplayName,Licenses
Services:
Get-MsolUser -UserPrincipalName o365.test2#tenant.com).Licenses.ServiceStatus
The issue with the above is that many users have different combinations of plans enabled so for some, a license index of [0] would refer to a different service plan. e.g. user1 has Visio Online Plan 2 and Office 365 Enterprise E3 product licenses assigned but user2 only Office 365 Enterprise E3. Index [0] in this instance would be different making the initial script block useless in finding all users with a specific service enabled regardless of combination of product licenses assigned.
Am I missing something here?

Not really sure how I missed it on my searches but the following will provide the information I require without the need to script it: Office 365 License Reporting and Management Tool -Assign Remove Licenses in Bulk

I know it's a bit old but today I've had exactly same problem and managed to write a quick function which just does what you asked for.
[cmdletbinding()]
param (
#Provide service name e.g. SWAY
[Parameter(Mandatory)]
[string]$Service,
#Specifies if to search for enabled or disabled service. Success = enabled.
[Parameter(Mandatory)]
[ValidateSet("Success","Disabled")]
[string]$Status
)
foreach ($User in ($Users = Get-MsolUser -All) ) {
$ServiceStatus = $user.licenses.ServiceStatus
$ProvisionName = $ServiceStatus | Where {$_.ServicePlan.ServiceName -eq "$Service" }
$Data = [PSCustomObject]#{
"USER" = $User.UserPrincipalName
"Software" = $ProvisionName.ServicePlan.ServiceName
"Status" = $ProvisionName.ProvisioningStatus
}
$Data | Where {$_.Status -eq "$Status" }
}

Related

Using MgGraph PowerShell 1.0 - Update-MgGroup -AdditionalProperties how to update the resourceBehaviorOptions option?

The education institution, I am helping, uses the Moodle Plugin Microsoft 0365 Integration which I believe uses the latest MgGraph v1.0 to create Microsoft 365 Teams Groups.
The Moodle plugin creates Microsoft 365 Teams Groups but some Settings can not be updated on the Admin Exchange Center after its creation, It returns an Error.
The property to be set being
The error received is not really helping
This Microsoft 365 Teams Group uses the HiddenMembership Visibility since MS Teams Classes can also be used and for privacy reasons this visibility is used. Unfortunately, the PHP code created by the Moodle MS Plugin adds more security features that prevents the groups from sending emails to each other since the above property can not be updated.
To get more information about the error, I tried to use MgGraph to set the Setting programmatically
$params = #{
AutoSubscribeNewMembers = $true
}
Update-MgGroup -GroupId $groupid -BodyParameter $params
Than I go the below error:
AutoSubscribeNewMembers parameter can't be true when SubscriptionEnabled
is set to false on the group.
Looking all around, I finally found where the SubscriptionEnabled value is set.
((get-MgGroup -GroupId $groupid).AdditionalProperties).resourceBehaviorOptions
Outputs :
SubscriptionDisabled
SharePointMemberReadonly
CalendarMemberReadOnly
WelcomeEmailDisabled
SubscribeNewGroupMembers
HideGroupInOutlook
ConnectorsDisabled
AllowOnlyMembersToPost
I tried to remove that value from the Group's AdditionalProperties.resourceBehaviorOptions but get this error.
$resourceBehaviorOptionsParams = #{
"SubscriptionDisabled" = "false";
}
$additionalParams = #{
resourceBehaviorOptions = $resourceBehaviorOptionsParams
}
Update-MgGroup -GroupId $groupid -AdditionalProperties $additionalParams
Error
An unexpected 'StartObject' node was found for property named 'resourceBehaviorOptions' when
| reading from the JSON reader. A 'StartArray' node was expected.
How can I remove the SubscriptionDisabled Option from the resourceBehaviorOptions section ?
I tried to reproduce the same in my environment and got same error like below
The error usually occurs if you don't have proper license like
Exchange Online or the subscription is disabled on that teams group.
When I ran the same MgGraph commands as you to know more about error, I got same response like below:
Connect-MgGraph
$groupid = "f2210ee6-451a-496b-8b39-c2xxxxxxxf"
$params = #{
AutoSubscribeNewMembers = $true
}
Update-MgGroup -GroupId $groupid -BodyParameter $params
Response:
When I tried the same script as you to remove the SubscriptionDisabled Option, I got same error like below:
$groupid = "f2210ee6-451a-496b-8b39-c289xxxxxdaf"
$resourceBehaviorOptionsParams = #{
"SubscriptionDisabled" = "false";
}
$additionalParams = #{
resourceBehaviorOptions = $resourceBehaviorOptionsParams
}
Update-MgGroup -GroupId $groupid -AdditionalProperties $additionalParams
Response:
To resolve the error, you can enable subscription for that teams group using below Exchange Online commands:
Connect-ExchangeOnline
Set-UnifiedGroup -Identity "Devi Team" -SubscriptionEnabled:$true
Response:
After enabling the subscription, I ran below command to enable AutoSubscribeNewMembers like this:
Set-UnifiedGroup -Identity "Devi Team" -AutoSubscribeNewMembers:$true
Response:
When I checked the same in Exchange Admin Center, option enabled successfully like below:
You can also enable "Allow external senders to email this group" option if needed from Portal like this after enabling subscription:

Powershell Script to reinstall Microsoft teams, Not able to find teams install

Currently I am trying to write a power shell script that will uninstall then install Microsoft Teams.
I have never written a power shell script before and I am having trouble having the script get the initial teams installation so I can uninstall it.
This is what I have written so far, I saw two ways of finding the teams install online and neither is able to find it so I am kinda lost, any help would be much appreciated.
(I know both are commented out I just did it like this for formatting in this question.)
Write-Host "-------------------------------------`n"
# Prompt for credentials
$credential = Get-Credential
$username = $credential.Username
$password = $credential.GetNetworkCredential().Password
Write-Host "Finding teams`n"
# Find teams 1
#$teamsapp = Get-AppxPackage -Name Microsoft.Teams
# Find teams 2
#$teamsapp = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -eq "Microsoft Teams" }
# Check if installed
if ($teamsapp) {
Write-Host "Microsoft Teams is installed."
} else {
Write-Host "Microsoft Teams is not installed."
}
`
Teams is a bit tricky because it installs per user, not per computer. Assuming you're running the script under the user's account, you can check the following registry location using Get-ChildItem:
Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Teams
This code worked for me:
Get-ChildItem -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\' | Where-Object { $_.Name -like '*Teams' }
You should be able to use the "QuietUninstallString" property of the result to get the command needed to uninstall Teams.
As a side note, consider looking into the Teams Machine Wide Installer for deploying teams. It installs to the computer and runs at logon for each user to detect if Teams is installed to their AppData folder. If not, it installs it automatically. This lets you avoid having to run as the user or loop through all the users AppData folder to manipulate user apps.

Azure Active Directory B2C Role Template Display name is inconssitent

I have an automation script for creating applications/resources in a ADB2C Tenant. Recently I ran into a troubling issue with the AzureADPreview.
Basically I create an Application, I create it's service principal then I'm assigning roles to this application. One role in particular that is causing me the issues is: User Administrator, or better said User Administrator | User Account Administrator.
What I mean by this? Basically for one tenant, the cmdlet: Get-AzureADDirectoryRoleTemplate either returns User Administrator or User Account Administrator which is strange.
Here is the code:
# Grant needed Service Principals Permissions
foreach ($displayName in $_.ServicePrincipal.ApplicationRoles) {
$adDirectoryRole = Get-AzureADDirectoryRole | Where-Object { $_.displayName -eq $displayName }
if ($null -eq $adDirectoryRole) {
$adDirectoryRoleTemplate = Get-AzureADDirectoryRoleTemplate | Where-Object { $_.displayName -eq $displayName }
Enable-AzureADDirectoryRole -RoleTemplateId $adDirectoryRoleTemplate.ObjectId | Out-Null
$adDirectoryRole = Get-AzureADDirectoryRole | Where-Object { $_.displayName -eq $displayName }
}
Add-AzureADDirectoryRoleMember -ObjectId $adDirectoryRole.ObjectId -RefObjectId $servicePrincipal.ObjectId | Out-Null
}
The line Enable-AzureADDirectoryRole -RoleTemplateId $adDirectoryRoleTemplate.ObjectId | Out-Null throws an error SOMETIMES when the DisplayName is not User Account Administrator.
Please don't tell me the Azure's API code looks like this:
if (rand() > 0.5f) { role.DisplayName = 'User Administrator'; }
else { role.DisplayName = 'User Account Administrator'; }
What is going on? Why is this the case?
The error thrown
Enable-AzureADDirectoryRole : Error occurred while executing ActivateDirectoryRole
Code: Request_BadRequest
Message: Could not resolve request to a valid role template. A valid value must be specified for 'displayName' or 'roleTemplateId'.
RequestId: 6bc26cc3-ce6d-41d0-abe0-2635d9897b75
DateTimeStamp: Thu, 14 Jan 2021 14:50:19 GMT
Details: PropertyName - roleTemplateId, PropertyErrorCode - PropertyRequired
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed
PS module: 2.0.2.119 AzureADPreview
UPDATE
Since a lot of the comments are missing the point, I think I need to emphasize the issue.
Depending on the tenant when I do the queries mentioned above I get different results. That shouldn't be the case at all, it is a BUG. I don't know where is the bug, in the Azure API, in the PowerShell module, this started some days ago to occur. We didn't change nothing, so I'm blaming the Azure API.
I'm going to attach some photos so you can see clearly the results I'm getting on two different tenants. Please understand that I tested this with 5 or more tenants and this randomness occurs on for each of them.
Some return User Administrator and some return User Account Administrator. This value doesn't change for that particular tenant after it's deployed. But at the deployment time, that value varies.
Look over these photos:
These results are obtained from different tenants!!!
After a lot of back and forth with Azure Support, we reached the conclusion that this was indeed a bug. They made a blog post about renaming some user roles:
A 30-day notice announcing the proposed change was posted to the Message center in M365 Admin center in Message ID MC218295 as of July 2020 with information to customers to update their scripts by August 14, 2020.
The update was finalized in January 20 and today January 29 all my tenants have the same value for the User Administrator role.

Access log for Exchange Server 2016

I'm looking for best way to query Exchange server 2016 access logs through Powershell.
My goal is find certain IP address gained access to which mail account.
UPDATE-1:
I understood that AuditLog should be enabled for all users then wait for users to login to Exchange Server.
I found this Powershell code from Microsoft Technet that enables AuditLog for all mail accounts.
$UserMailboxes = Get-mailbox -Filter {(RecipientTypeDetails -eq 'UserMailbox')}
$UserMailboxes | ForEach {Set-Mailbox $_.Identity -AuditEnabled $true}

Check if user is a member of the local admins group on a remote server

The user is a member of the AD security group "Domain\Sql Admins", and the security group "Domain\Sql Admins" is a member of the local Administrators group on a Windows Server.
I have tried the following PowerShell script:
$u = "Username"; net localgroup administrators | Where {$_ -match $u}
This script will only return the user if it is added directly to the admin group. Do I have to cycle through all of the groups in the admin group until I find my user? Or is there another way?
Check out this article, by Boe Prox on the Microsoft Hey Scripting Guy blog. He describes how to check if the user is a local administrator or not.
http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/11/check-for-admin-credentials-in-a-powershell-script.aspx
This article points to a Test-IsAdmin function that was posted onto the TechNet Gallery.
http://gallery.technet.microsoft.com/scriptcenter/1b5df952-9e10-470f-ad7c-dc2bdc2ac946
The function contains the following code, which returns $true or $false.
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
PowerShell 5.1 (Windows Server 2016) contains Get-LocalGroupMember cmdlet.
$user = "$env:COMPUTERNAME\$env:USERNAME"
$group = 'Administrators'
$isInGroup = (Get-LocalGroupMember $group).Name -contains $user
Using the SID:
([Security.Principal.WindowsIdentity]::GetCurrent().Groups | Select-String 'S-1-5-32-544')
Or using a "Well-known" security identifier name:
([Security.Principal.WindowsIdentity]::GetCurrent().Groups.IsWellKnown('BuiltinAdministratorsSid') -eq $true)
if you want to get all the SIDs and their names, please check this page: https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems
If you happen to be using the PowerShell Community Extension you can use the Test-UserGroupMembership command e.g.:
Test-UserGroupMembership Administrators