Delete SharePoint Online site collections using powershell - powershell

I have been trying to delete site collections from a csv, I'm trying to use a powershell script to get the site URLs to be deleted.
I've tried everything, now that I've run out of ideas I'm opening this question. I'm accepting possibilities other than Powershell
PS: I'm trying to do this without creating anything in the tenant.
This site belongs to a Microsoft 365 group. To delete the site, you must delete the group.
enter image description here
Below are some attempts:
#Modules
Import-Module ExchangeOnlineManagement
Import-Module Microsoft.Online.SharePoint.PowerShell
Import-Module SharePointPnPPowerShellOnline
$site = "https://tenant.sharepoint.com/sites/site"
$mailGroup = "group#onmicrosoft.com"
#First
Remove-UnifiedGroup -Identity $mailGroup-Confirm:$false
Remove-SPOSite -Identity $site -NoWait -Confirm:$false
#Second
Remove-UnifiedGroup -Identity $mailGroup-Confirm:$false
Set-SPOSite -Identity $site -LockState "unlock"
Set-SPOSite -Identity $site -Owner $userCredential.UserName
Remove-SPOSite -Identity $site -NoWait -Confirm:$false
#Third
$SharepointSite = Get-SPOSite $site
Remove-PnPUnifiedGroup -Identity $SharepointSite .GroupID
Remove-PnPTenantSite $site
I also tried what is in the link: https://learn.microsoft.com/en-us/answers/questions/674248/batch-delete-site-collections-in-powershell-from-c.html

Please try to run the command Remove-UnifiedGroup -Identity "group name" to delete the Microsoft 365 group before run Remove-SPOSite -Identity $site -NoWait -Confirm:$false. Note: you may need to wait some time after deleting a group ,then the site can be successfully deleted.

Related

Remove AzureAD user from all groups -powershell

I've been trying to remove all of the groups(M365,DL,security etc.) from a user.
I was trying to use this script but I'm getting errors when removing DLs(reasonably).
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups.ObjectId){
Remove-AzureADGroupMember -ObjectId $Group -MemberId $userID
}
My problem is that I have no way to get the type of the group and treat it with the correct command accordingly. When trying to use MSOL to get the type I saw that M365 groups are also being shown as a distribution list, So I'm not able to use this method.
Any advice or luck with that?
Thanks!
Edit:
This is how the groups are showing up, identical but not actually as it requires different command to remove the group.
365 group and DL
Considering that Azure AD group memberships can be removed via Remove-AzureAdGroupMember while Exchange Online memberships via Remove-DistributionGroupMember, executing both commands via a try..catch is probably the most efficient way to meet the OP's requirements.
The code below does just that (remove the comment before the Confirm parameter to skip confirmation.)
Connect-AzureAD
Connect-ExchangeOnline
$userid = (Get-AzureADuser -objectid "test.user#testdomain.test").objectid
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups){
try {
Remove-AzureADGroupMember -ObjectId $Group.ObjectID -MemberId $userID -erroraction Stop
}
catch {
write-host "$($Group.displayname) membership cannot be removed via Azure cmdlets."
Remove-DistributionGroupMember -identity $group.mail -member $userid -BypassSecurityGroupManagerCheck # -Confirm:$false
}
}
Note: proper code formatting does help.
I have tried with same script in my environment to remove an user from the groups and it removed successfully .
Azure portal->Groups->Enter your Group name
In my Azure Active directory ,I have Microsoft group type with 5 users:
In my Security Group type I have 4 users:
I tried with particular user like imran khan to remove from these two groups.
First you need to connect with azureAD using this command :
Import-Module AzureAD
$Credential = Get-Credential
Connect-AzureAD -Credential $Credential
Now I tried with same commands:
$userID = 'user object ID'
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups.ObjectId){
Remove-AzureADGroupMember -ObjectId $Group -MemberId $userID
}
Response:
Which returned empty that means which I removed successfully a user from the group.
Reference:
Compare groups - Microsoft 365 admin | Microsoft Docs

New-mailbox script, with zipcode and P.O. Box values added to mailbox user account. possible?

I am using the following powershell code for creating new mailboxes in my organization.
$users = Import-CSV C:\mailboxes.csv
$users| foreach {
$Password = convertto-securestring $_.password -asplaintext -force
new-mailbox -name $_.name -alias $_.alias -FirstName $_.Firstname -LastName $_.Lastname -userPrincipalName $_.userPrincipalName -PrimarySmtpAddress $_.PrimarySmtpAddress -Database $_.database -RetentionPolicy "b3a83dc4-e471-4d05-b357-25535aa027af" -OrganizationalUnit $_.OrganizationalUnit -Password $Password –ResetPasswordOnNextLogon:$false
}
Is there a way to insert a static text/value to this "zip code" and "po box" boxes, on the new active directory user, created along with this mailboxes?
for example , zip code should contain: "0101010101" and P.O Box should contain "000"
Your assistance is most appreciated
One option is to use Set-ADUser from the ActiveDirectory module. At the beginning of your script (before any loops), you can run the following if you have the module available to your current session.
Import-Module ActiveDirectory
After your New-Mailbox command, you can add the Set-ADUser command:
Set-ADUser -Filter "UserPrincipalName -eq '$($_.userprincipalname)'" -PostalCode "01010101" -POBox "000"
Sometimes AD replication can cause inconsistencies with multiple commands against AD objects. To get around that, you would typically use the -Server parameter to consistently target a domain controller that will see all of your read and write operations. The alternative (a slower one) is to run the AD user modifications after all of the mailboxes have been created and data has replicated to the AD Site you would be targeting.
AdminOfThings - Thanks for your reply.
So tell me,
Considering your last comment about the AD User modification conflict that i might occur,
i`m thinking some sort of "time delay" code might resolve such issues.
would it be logical to add something like "Start-Sleep" command to add a delay between
the "new-mailbox" and "Set-ADUser" commands as you suggested?
if so can you...write down how my script should like exactly, adding all things together please?
Thanks.

PowerShell Script to Automate New AD Group Membership

Can anyone share ideas for a PowerShell script that will create a new AD global security group and then populate it with all user objects that share a specific attribute?
Use the ActiveDirectory module.
$group_name = 'dudez'
New-ADGroup -Name $group_name `
-GroupCategory Security `
-GroupScope Global `
-Path "CN=Users,DC=foo,DC=local" `
-Description "Members of this group have identified as men."
$dudes = (Get-ADUser -Filter "...").DistinguishedName
Add-ADGroupMember -Identity $group_name -Members $dudes
First line creates the group. Second builds the list of users you want in the group. Third line adds the users to the group.
You should be able to modify this to suit your needs.

Powershell get computer name and add to AD group

I am trying to utilize Powershell to get the computer name it’s currently running on and then add that computer to a security group and I’m stuck.
Forcing myself to learn Powershell better and got this from a co-worker but not sure how to edit it for my needs. This script will be used to run after a certain package has been installed to grant access. Here is what I have so far:
param(
[string[]]$mname,
[string[]]$gname
)
foreach($m in $mname.split(','))
{
$mobj = get-adcomputer $m
foreach($g in $gname.split(','))
{
Add-ADGroupMember "GROUP_NAME" -Members $mobj
}
}
ERROR:
You cannot call a method on a null-valued expression.
At C:\Scripts\Add-MachineToCollectionGroup.ps1:6 char:15
+ foreach($m in $mname.split(','))
Just add your groupname at the top, also if you aren't running Powershell 5 you may need to change Add-ADGroupMember $groupobj -Members $computerobj to be Add-ADGroupMember $groupobj -Member $computerobj I think they changed that.
Also add -whatif to the end of the last line to test it (It'll tell you what it would have done without the whatif).
Oh also you will need to run this from an account that has AD access to add the machine to the group and the computer must have the activedirectory module installed.
$Groupname = "ENTER GROUP NAME HERE"
$computerobj = Get-ADComputer $env:COMPUTERNAME
$groupobj = Get-ADGroup $Groupname
Add-ADGroupMember $groupobj -Members $computerobj -WhatIf

Log each Powershell process to text file through

Firstly, I'm by no means a PS expert, total newbie - admission done. I have scoured the internet for what I need in order to get the script to do what I want, but I've reached a point where I'm struggling and in need of help.
Basically, I've created a script using ISE that grabs the users in an AD OU, processes them by disabling the accounts, renaming them, stripping out the groups and moving them to another folder. In order to automate the deactivation process for users. But I now need to create a log file every time this runs, to show a) if it found any Users in the original OU (ToBeProcessed) and b) what processes were run and if they were successful. Here is the code.
$OUToBeProcessed = "OU=ToBeProcessed,OU=Users,OU=World,DC=local"
$OURetired = "OU=RetiredUsers,OU=Users,OU=World,DC=local"
$Users = Get-ADUser -SearchBase $OUToBeProcessed -Filter 'name -Like "*"' -Properties MemberOf
ForEach($User in $Users){
$SAN = $User.SamAccountName
#Disable user account
Disable-ADAccount -Identity $SAN
#Remove membership from groups for user
$User.Memberof | Remove-ADGroupMember -Member $User -Confirm:$False
$NewDN = "zzz_" + $User.Name
#Change display name
set-aduser $User -Displayname $newDN -ErrorAction SilentlyContinue
#Change distinguished name
Get-ADUser $SAN | Rename-ADObject -Newname $NewDN
Write-Host "$SAN may already exist."
#Move account to RetiredUsers
Get-Aduser $SAN | Move-ADObject -TargetPath $OURetired
}
I'm assuming I'll need to either use a Write-Output or Log-File cmdlet, though someone had also suggested Transcript, but I don't think that's what I need.
I've tried a number of ways to incorporate the Write-Output into the script, it runs without errors, but no text file is produced. But I'm placing it within the loop which may be the issue. I've placed it outside the loop but I think because it's not being passed anything it's creating the file with nothing in it. Would really appreciate some help as to where the Write-Output might need to go if that is the right cmdlet.
Personally I tend to add a Log function to my scripts. Something like this (where I output to the host and file):
Function Log {
Param (
[Parameter(Mandatory=$true)] [string] $String,
[Parameter(Mandatory=$true)] [string] $LogFilePath,
[Parameter(Mandatory=$false)][ValidateSet("ERROR","WARN","INFO","DEBUG")] [string] $Level = "INFO"
)
$LogString = ((Get-Date -Format "s") +" $Level $env:USERNAME $String")
Write-Host $LogString
Out-File -Append -FilePath $LogFilePath -InputObject $LogString
}
Then you could do logging:
Log "Something wrong!" "c:\mylog.log" "WARN"
Log "Updated stuff" "c:\mylog.log"
Or search the http://www.powershellgallery.com/ for logging modules.
Example (haven't tried this one myself):
https://www.powershellgallery.com/packages/PSLogging/2.5.2