Remove all users in bulk (foreach) - powershell

I need to remove all users from my Microsoft Team in one command. The get-teamuser (first row) is giving me all the members. But I can't figure out how to now remove all in a loop. Think this should be something like the second row. But not sure how to do this.
Hope someone can help me with this issue.
Get-TeamUser -GroupId a4f03b48-49ae-4f06-949f-81b4940e17b6 | where-object {$_.role -eq "member"}
#Get-content c:\list.txt |foreach{Remove-TeamUser -GroupId a4f03b48-49ae-4f06-949f-81b4940e17b6 -User $_}

$users = Get-TeamUser -GroupId a4f03b48-49ae-4f06-949f-81b4940e17b6 | where-object {$_.role -eq "member"}
Foreach ($user in $users)
{
$UPN = $user.userprinciplename
Remove-TeamUser -groupid "a4f03b48-49ae-4f06-949f-81b4940e17b6" -user "$UPN"
}
https://learn.microsoft.com/en-us/powershell/module/teams/remove-teamuser?view=teams-ps#:~:text=Remove%20an%20owner%20or%20member,hour%20before%20changes%20are%20reflected.

Thanks Kartheek R,
I've used the answer above but modified it a bit to get it to work for me.
Connect-MicrosoftTeams
$TeamGUID = "94865df5-97fd-1234-aaad-13555de4gt28"
$users = Get-TeamUser -GroupId $TeamGUID | where-object {$_.role -eq "member"}
Foreach ($user in $users) {
$UPN = $user.User
Remove-TeamUser -groupid $TeamGUID -user $UPN
Write-Host $UPN
}

Related

Powershell won't find equal for $var in csv file

I'm pretty new to powershell and I'm trying to assign Exchange-groups and shared mailboxes with an Powershell script. I have a .csv file with the job title, department and all the associated groups and mailboxes. I wrote the following script to achieve my goal but it doesn't work.
I have the feeling that the Where {$_.JobTitle -eq $JOBcsv -and $_.Department -eq $DEPcsv} part is making the script fail. If I put a text value like 'Accountmanager' instead of $JOBcsv all works fine. Thanks in advance!
Connect-ExchangeOnline -Credential $cred
Connect-AzureAD -Credential $cred
$User=Read-Host -Prompt 'Write UPN'
$DEPcsv=Get-AzureADUser -ObjectId $User | Select Department
$JOBcsv=Get-AzureADUser -ObjectId $User | Select JobTitle
$Groups = Import-CSV -Path "C:\PS Scripts\Groepen en Mailboxen.csv" -Delimiter ";" | Where {$_.JobTitle -eq $JOBcsv -and $_.Department -eq $DEPcsv} | Select Groepen
ForEach ($item in $Groups)
{Add-DistributiongroupMember $item -Member $User}
$Mailboxes = Import-CSV -Path "C:\PS Scripts\Groepen en Mailboxen.csv" -Delimiter ";" | Where {$_.JobTitle -eq $JOBcsv -and $_.Department -eq $DEPcsv} | Select Mailboxen
ForEach ($item in $Mailboxes)
{Add-MailboxPermission $item -user $User -AccessRights FullAccess -InheritanceType All}

Script needs converting to export to CSV

I put together the below, which does the job. However, the output isn't very workable. So I wanted to output this all to a CSV using Export-Csv. Im aware I can do this by moving to a ForEach-Object query, but im not entirely sure how to achieve that.
I have added an attempt to convert it in hopes of a little help. I'm not sure how to specify the variable for each object. For example the first section calls all domains in the forest. How do i use each response in the next piped query? and so on.
$domains = (Get-ADForest).Domains
$controllers = #()
$worked = $false
foreach ($domain in $domains) {
$controller = Get-ADDomainController -Discover -ForceDiscover -DomainName $domain |
Select-Object HostName
$controllers += $controller
}
while (-not $worked) {
try {
foreach ($item in $controllers) {
$value = $item.HostName.Value
Write-Host $value
Write-Host 'Domain Admins'
Get-ADGroupMember -Identity 'Domain Admins' -Server $value |
Get-ADUser -Properties name, samaccountname, Description, EmailAddress |
Where {$_.Enabled -eq $true} |
Format-Table Name, SamAccountName, Description, EmailAddress -AutoSize
}
$worked = $true
} catch {}
}
Conversion Attempt
ForEach-Object{
(Get-ADForest).domains | Get-ADDomainController -Discover -ForceDiscover -DomainName $domain |Select-Object HostName | Get-ADGroupMember -identity 'Domain Admins' -Server $value | Get-ADUser -Properties samaccountname, Description, EmailAddress | Where {$_.Enabled -eq $true}
}| Export-Csv -Path "$HOME/Desktop/DomainAdmins.csv" samaccountname, Description, EmailAddress -AutoSize
If you can get the values from your Get-ADUser call and put them in an object, you can then pipe to convertto-csv.
Here's an example:
$arr = #([pscustomobject]#{name="name"; sam="samaccountname"}, [pscustomobject]#{name="name2"; sam="samaccountname2"});
$arr | ConvertTo-Csv -NoTypeInformation
"name","sam"
"name","samaccountname"
"name2","samaccountname2"
You could get rid of the Format-Table call. The code I've shown in the example pipes and array of objects into the convertto-csv cmdlet. So if Get-ADUser returns objects, you should be able to pipe right into ConvertTo-CSV or Export-Csv -append
The objects are hashtables that are cast to pscustomobjects, it's a nice quick way to illustrate the technique.
The result, as shown, will be csv headers that match your hashtable keys, and the hastable values will be the CSV values.
This is working fine in my local environment and storing the result in D:\Test_File.csv
$domains = (Get-ADForest).Domains
$controllers = #()
$worked = $false
foreach ($domain in $domains) {
$controller = Get-ADDomainController -Discover -ForceDiscover -DomainName $domain | Select-Object HostName
$controllers += $controller
}
while (-not $worked) {
try
{
foreach ($item in $controllers)
{
$value = $item.HostName.Value
Write-Host $value
Write-Host 'Domain Admins'
Get-ADGroupMember -Identity 'Domain Admins' -Server $value |
Get-ADUser -Properties name, samaccountname, Description, EmailAddress |?{$_.Enabled -eq $true}|Export-Csv -Append "D:\Test_File.csv"
}
#$worked = $true
}
catch
{
$Error_Message=$_.Exception.Message
}
}

Assign 0365 licensing to a list of users

Trying to get a script to assign O365 license to a list of users. What am I missing here? I get the list of users to work, made based on SamAccountName length and the date the user is created. How can I get it to look at each of the users inside that list and assign it an O365 license if it is false? Is an IF statement ideal to use here?
Import-Module ActiveDirectory
$date = (Get-Date).ToString()
$month = (Get-Date).AddDays(-4)
$NewUser = Get-ADuser -Filter * -Properties * | Where { ($_.samaccountname.length -eq 3 -and $_.whencreated -ge $month) } | Select-Object SamAccountName, UserPrincipalName, whencreated
Import-Module MSOnline
Connect-Module -Cred $User
foreach ($item in $NewUser) {Get-MsolUser -UserprincipalName $NewUser | where {$_.isLicensed -eq $false}
Set-MsolUserLicense -UserPrincipalName $NewUser.UserPrincipalName -AddLicenses $NewUser.licensetype
}
Use if statement is right. Please refer to the following:
foreach($user in $NewUser){
$AccountInfo = Get-MsolUser -UserPrincipalName $user.UserPrincipalName -ErrorAction Stop
$CurrentAccountSku = $AccountInfo.Licenses.AccountSkuId
if($CurrentAccountSku -ne $null)
{
Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -AddLicenses 'contoso:ENTERPRISEPACK' -ErrorAction Stop
}
}
Here's a blog for adding different Skus to Office 365 user accounts.
http://blogs.technet.com/b/treycarlee/archive/2013/11/01/list-of-powershell-licensing-sku-s-for-office-365.aspx

Get recursive group membership of all AD users using Powershell

I'm trying to make a PS script which would list all Active Directory user group membership (recursive).
I already have working script:
import-module activedirectory
$users = get-aduser -Filter {Name -Like "*"} -Searchbase "ou=Users, dc=Domain" | Where-Object { $_.Enabled -eq 'True' }
$targetFile = "D:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"
foreach ($user in $users)
{
$groups = Get-ADPrincipalGroupMembership $user
foreach ($group in $groups)
{
$username = $user.samaccountname
$groupname = $group.name
$line = "$username;$groupname"
Add-Content $targetFile $line
}
}
But script doesn't list groups recursively, i.e., if group listed in the output file is part of another group.
Example:
Group1: User
Group2: Group3: User
Script shows only Group1 and 3 but not 2.
What should I add to the first script that it writes group membership recursively?
Sorry I am publishing an answer for a question from 3 years ago but if someone will see it, it can help.
Credit to:
How to get ALL AD user groups (recursively) with Powershell or other tools?
You can use the LDAP_MATCHING_RULE_IN_CHAIN:
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=CN=User,CN=USers,DC=x)"
You can use it anywahere that you can use an LDAP filter.
Example:
$username = 'myUsername'
$dn = (Get-ADUser $username).DistinguishedName
Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) | select -expand Name | sort Name
Fix in your script:
import-module activedirectory
$users = get-aduser -Filter {Name -Like "*"} -Searchbase "ou=Users, dc=Domain" | Where-Object { $_.Enabled -eq 'True' }
$targetFile = "D:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"
foreach ($user in $users)
{
$dn = $user.DistinguishedName
$groups = Get-ADGroup -LDAPFilter ("(member:1.2.840.113556.1.4.1941:={0})" -f $dn) | select -expand Name | sort Name
foreach ($group in $groups)
{
$username = $user.samaccountname
$groupname = $group.name
$line = "$username;$groupname"
Add-Content $targetFile $line
}
}
If you make it a function you can call it recursively. Check this out, I think you'll be pleased with the results:
Function Get-ADGroupsRecursive{
Param([String[]]$Groups)
Begin{
$Results = #()
}
Process{
ForEach($Group in $Groups){
$Results+=$Group
ForEach($Object in (Get-ADGroupMember $Group|?{$_.objectClass -eq "Group"})){
$Results += Get-ADGroupsRecursive $Object
}
}
}
End{
$Results | Select -Unique
}
}
Toss that at the top of your script, and then call it for each user. Something like:
import-module activedirectory
$users = get-aduser -Filter {Name -Like "*"} -Searchbase "ou=Users, dc=Domain" -Properties MemberOf | Where-Object { $_.Enabled -eq 'True' }
$targetFile = "D:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"
foreach ($user in $users)
{
$Groups = $User.MemberOf
$Groups += $Groups | %{Get-ADGroupsRecursive $_}
$Groups | %{New-Object PSObject -Property #{User=$User;Group=$_}}|Export-CSV $targetfile -notype -append
}
Now, depending on the size of your AD structure that may take quite a while, but it will get you what you were looking for.
It is very easy. Just use ActiveRoles Management Shell for Active Directory. Cmdlet Get-QADMemberOf with parameter Indirect is the one you are looking for. Example:
Get-QADMemberOf john.smith -Indirect
The Quest object returned already include All Recursive groupes (and first level users) in properties $_.AllMembers
Add-PSSnapin Quest.ActiveRoles.ADManagement
$UsersFirstLevel = ($Members | Get-QADObject -Type Group -DontUseDefaultIncludedProperties | Get-QADGroupMember -DontUseDefaultIncludedProperties | ?{$_.type -eq 'user'})
$UsersSubGroup = ($Members | Get-QADObject -Type Group -DontUseDefaultIncludedProperties | Get-QADGroupMember -DontUseDefaultIncludedProperties | ?{$_.type -eq 'group'}).Allmembers | Get-QADObject -DontUseDefaultIncludedProperties | ?{$_.type -eq 'user'}
$RecursiveUsers = $UsersFirstLevel
$RecursiveUsers += $UsersSubGroup
$RecursiveUsers = $RecursiveUsers | Sort-Object -Unique
Newer versions of PowerShell (AD Module) do have -Recursive switch. So you can easily use Get-ADGroupMember.
Example: Get-ADGroupMember -Identity My_Group -Recursive

Powershell, filters and combining properties

I have an AD group that has other AD groups as members. Some of these groups may have "sub-groups" as well. I want to recursively descend through this group and find answers to several questions about the users in that group. For example:
Is User-X "enabled" in the overall group?
Does the account of User-X have values in ANY of the properties: AccountExpirationDate, accountExpires and Deleted?
I would like a displayed result that contains the properties: DisplayName, SamAccountName, AccountExpirationDate, accountExpires, Deleted and enabled (from the group object)
I have tried doing an "Add-Member" to insert the "enabled" value from get-ADgroupMember but I get the error:
Add-Member : Cannot add a member with the name "enabled" because a member with that name already exists. If you want to over
write the member anyway, use the Force parameter to overwrite it.
... but there is no such element as far as I can tell. I have renamed the member in the Add-Member to several very unique things but I still get the same error.
my current attempt is:
Import-Module ActiveDirectory
get-adgroupmember -Identity "My big AD group of groups" -recursive |
Where-Object -FilterScript {($_.ObjectClass -eq 'user')} |
ForEach-Object {
$enabled = $_.enebled
Get-ADUser `
-Filter {(name -eq $_.name)} `
-Properties DisplayName,SamAccountName,AccountExpirationDate,accountExpires,Deleted |
Add-Member -Name "myITGGroupEnabled" -Value $enabled -MemberType NoteProperty |
Where-Object `
-FilterScript {
($_.AccountExpirationDate -lt [datetime]::now) `
-OR ($_.accountExpires -eq $true) `
-OR ($_.Deleted -eq $true) `
-OR ($_.myITGGroupEnabled -eq $false)
}
Select-Object DisplayName,SamAccountName,AccountExpirationDate,accountExpires,Deleted,GroupEnabled
break
}
I am lost. Ideas?
I think all you need is a new PSObject. Like this:
...
Get-AdUser -Filter {name -eq $_.name} -Properties .... | % {
If ( ($_.AccountExpirationDate -lt [datetime]::now) `
-OR ($_.accountExpires -eq $true) `
-OR ($_.Deleted -eq $true) `
-OR ($_.myITGGroupEnabled -eq $false)) {
New-Object PSObject -Property #{MyITGGRoupEnabled=$enabled}
}
}