Removing Users from MSOL Groups - powershell

I am trying to remove all disabled users from my MSOL groups within the company. There are roughly 50 users and I have already removed them from all the DLs an Shared Mailboxes, but I still need to have them taken off of the MSOL groups. I have written something fairly simple to do so;
$import = Import-Csv "C:\Users\Person\Desktop\DisabledMSOL.csv"
foreach($user in $import) {
$DisabledUserParams = #{
PersonID = $user.GroupID
ObjectId = $user.ObjectId
}
Remove-MsolGroupMember -GroupObjectId $DisabledUserParams.ObjectId -GroupMemberType User -GroupmemberObjectId $DisabledUserParams.PersonID}
Problem is when I run this, it gives this error:
Remove-MsolGroupMember : Cannot bind parameter 'GroupMemberObjectId'. Cannot convert value "" to type "System.Guid"
Error: "Unrecognized Guid format."
At line:11 char:111
+ ... oupMemberType User -GroupmemberObjectId $DisabledUserParams.PersonID}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Remove-MsolGroupMember],
ParameterBindingException
+ FullyQualifiedErrorId :CannotConvertArgumentNoMessage,Microsoft.Online.Administration.Automation.RemoveGroupMember
Please let me know what you think.
*Also, How do you make the yellow outline at this site? I have never really found out how to do so.
Thank you.

If you have about 50 records in the csv file and you get about 50 errors when you try to run your script, I'd double check those column/property names
If you try to access a property that doesn't exist, Powershell will silently continue.
If you get a partial success (some records work others don't), I'd check the values in the csv for the failures. You may think you have a ObjectId but may not.
Lastly, check your delimiter. If the csv file is tab or pipe delimited, you'll need to specify that delimiter in the Import-Csv call.
Good Luck!

The reason why it did not work was because there was an issue of misunderstanding the cmndlets in Exchange online and the syntax that is tied with it. I do not have an on Prem server and we do all Exchange online. Despite it correctly grabbing the GUIDs from the CSV, it was the wrong syntax:
Remove-MsolGroupMember -GroupObjectId $DisabledUserParams.ObjectId -GroupMemberType User -GroupmemberObjectId $DisabledUserParams.PersonID}
The correct Syntax was:
Remove-RecipientPermission $DisabledUserParams.ObjectId -Trustee $DisabledUserParams.PersonID -AccessRights SendAs
For some reason the MSOL group came up as a mail group with only send as access; furthermore, it will only remove/add users using that syntax
Remove-RecipientPermission
Thank you for all your help though. I appreciate all the advice I get from this site.

Related

MS Graph API - Group & membership info

I'm trying to pull out a listing of all groups in our Azure Active Directory org along with all the associated members (be them users, groups, contacts, etc).
Since I was unable to locate a method to do this through the various Microsoft portals with a simple export button I began the process of obtaining access to the Microsoft Graph API/SDK via Powershell.
I'm by no means a PowerShell expert as it's not one of my go-to scripts; however, from what I can tell the ability to pull group info in this fashion is fairly limited.
The following is what I've been able to accomplish thus far:
Pull in a list of the groups using Get-MgGroup -All
Use Get-MgGroupMembers to pull back a list of Directory Objects.
This is where I get stuck. From what I've read it looks like a Directory Object by default only returns the ID and the Deleted Date. I'd like to get a display Name for these objects; I can obviously do this by running the appropriate 'Get' cmdlet for the type of directory object (i.e. Get-MgUser); From what I can tell the type of directory object can't be gleaned via PowerShell with out 'trial-and-error'... This seems highly inefficient to simply get a displayName.
Is there a more effective way to determine either the displayName of a Directory Object via a PowerShell cmdlet or at the very least a type so I can write a case statement to run the right cmdlet on the first try?
For the record this is going to be incorporated in to a Powershell Script, the current iteration of which looks like this and sorta works okay... assuming the Id passed in $member.Id belongs to a User type directory object.
Connect-MgGraph
$groups=Get-mgGroup -All
ForEach ($group in $groups){
$members = #{}
$members = Get-MgGroupMember -GroupId $group.Id -All
ForEach ($member in $members){
$user = Get-MgUser $member.Id
Write-Output $object.ODataType
Write-output $group.DisplayName "," $member.Id "," $user.UserType"," $user.DisplayName "," $user.UserPrincipalName "," $user.Mail >> C:scripts\Azure_Groups.txt
}
}
Would appreciate any direction/assistance on this. Thanks in advance!
Not sure why its not returning all the details on the PowerShell query:
This is working fine in MS Graph Explorer with the results showing all the details of the members:
For more details:https://learn.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0&tabs=http#example-1-get-the-direct-membership-in-a-group

Get-Msoluser accepts a hardcoded string but not a variable for parameter UserPrincipalName

I'm going a little batty because I can't think of anything I'm doing wrong with this code snippet. I'm literally just trying to get a single user using Get-MsolUser using the parameter -UserPrincipalName in the following line:
$usr = Get-MsolUser -UserPrincipalName $wantedUser
I'm calling this code from within a function that originally had the $wantedUser variable as a parameter, but due to the issues I'm experiencing, I've tried to add it as a script variable, I've tried reassigning the parameter variable to a local function variable, but nothing works. I can put the raw user principal name in there like below:
$usr = Get-MsolUser -UserPrincipalName "james#contoso.com"
And it works... no problem. Queries and assigns the user information to the $usr variable as expected where the rest of my code logic works fine. I know I'm just probably stupidly looking over something simple, but for the life of me I can't figure it out. Can someone please shed some light on what I might be doing wrong? I know it's passing the value in there to some extent because I get an exception saying the following:
Get-MsolUser : User Not Found. User: "james#contoso.com".
At C:\locationWhereMyScriptIsLocated.ps1:19 char:12
+ $usr = Get-MsolUser -UserPrincipalName $wantedUser
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [Get-MsolUser], MicrosoftOnlineException
+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.UserNotFoundException,Microsoft.Online.Administration.Automation.GetUser
I don't have access to Get-MsolUser, but from what I can tell, the error message
Get-MsolUser : User Not Found. User: "james#contoso.com". suggests that the user name mistakenly contains embedded " chars. - that is, the verbatim value of $wantedUser may be "james#contoso.com" rather than the expected james#contoso.com.
Thus, as a quick fix, try:
$usr = Get-MsolUser -UserPrincipalName ($wantedUser -replace '"')
But it's worth investigating why these embedded " characters ended up in $wantedUser to begin with, and perhaps eliminate the problem at the source.

Get AD user by providing fullName and manager full name

It might look silly but I'm struggling with finding user with Powershell by providing his full name and his manager full name. Purpose of script is to get SamAccountName and Email Address by using mentioned values which are provided by other team (these are the only unique values I get - getting user by Full Name is not any kind of problem, but it's possible that it'll return multiple results, and that's why Manager Full Name would determine appropriate result).
First I was using simple command
Get-ADUser -server $gc -Filter { (CN -eq $uFullName) -and (extensionAttribute4 -eq $mFullName) }
It worked great, but unfortunately I noticed that not all accounts use extensionAttribute4 to hold manager full name. I thought of using Filter on manager property but when I tried to use (Manager -like "*value*") it returned that like operator isn't supported by this attribute.
I'm still trying to find solution for this but maybe someone will have some solution to this situation.
Thank you in advance.

Querying AD group membership through powershell results in error: Get-ADGroupMember : One or more properties are invalid

I am trying to get a groups membership to verify the existence of a user so that I can remove the user from the group. I am trying to use the Get-ADGroupMember command, but it only works with certain accounts. unfortunately one of the accounts it does not work with is our service account. Ruining the command results in the error below.
$members = Get-ADGroupMember -Identity MyGroup
results in:
Get-ADGroupMember : One or more properties are invalid.
Parameter name: index
At line:1 char:12
+ $members = Get-ADGroupMember -Identity MyGroup
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (MyGroup:ADGroup) [Get-ADGroupMember], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
I am not sure how to proceed from here or why this is occurring only on some accounts. any help is much appreciated.
Get-ADGroupMember outputs a list of type ADPrincipal, which means it is looking up each member too. So it's possible that it's choking on one of the members.
See if you get different results with this:
(Get-ADGroup MyGroup -Properties member).member
That will just spit out the raw member attribute of the group, which contains the distinguished name of each member (a list of strings), without actually trying to look up each member.
If that works, then there are other ways to find the info you need (like loop through those members and ignore members that you can't access).
This is because the account you are running under likely does not have read access to that group. In my organization we purposely remove add a deny right to all other users for the "Domain Admins" group so that people can't query what users have admin access. When I run your code on my system I get the exact same error. When I run it as an administrator it works because the administrator account has rights to read that group membership.

POWERSHELL - The member's SID could not be resolved

Hello im working with Active Directory Group and Users and i wanna check and set proper Users/Groups from AD to machines. Problem is when i iterate over Local Users/Groups on some machine and there is old Users/Group that no longer exists in AD POWERSHELL will stop working and will throw exception.
An error (1332) occurred while enumerating the group membership. The member's SID could not be resolved.
I know what causes this problem but i dont know how to work around it. The main issue here is that its not even possible to iterate over whole array of users if one is no longer valid. Only solution to this is manualy delete those invalid users.
I even saw some reports to Microsoft that this behaviour is wrong and should be fixed but nothing was done about it.
Anyone here encountered this issue?
Thank you for your help.
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$computer = "PC name"
$groupName = "Administrators"
$context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, $computer
$idtype = [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName
$groupData = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($context, $idtype, $groupName)
$groupData.Members | select #{N='Server'; E={$computer}}, #{N='Domain'; E={$_.Context.Name}},#{N='Group'; E={$groupName}} , #{N='Account Name/Group'; E={$_.SamAccountName}}
Here is example of code that im using for iterating over Local users/groups on some PC.
Can You post the code that you are using, and the full error. Im guessing there is a workaround, but without seeing your code I can't see what could be wrong. If a terminating error is thrown it will stop the script or function from running further (with some gotchas, and exceptions), there are many ways of working around this
Also could you post the full error.
You will probably need to set the $erroractionpreference to silentlycontinue. And then review the $error variable to check the errors, but again I am only speculating.