I am trying to create a new SharePoint site and then add an AD security group as an additional site collection admin to that newly created site.
The only way I found to make this work is to use import-csv to create the new site and then use set-spouser with the AD group (from a variable that is really the GUID of the AD security group). The first time I run the script below, the line with set-spouser gives me an error of "Set-SPOUser : File Not Found."
.
What is strange is when I run the script again on the same .csv
file to create new sites, it of course skips the new-sposite line because that site was already created the first time - but - it actually adds the AD security group as a site collection admin without any errors or issues.
Anyone have an idea of why I can't do this with one script execution?
#Change to your tenant
$adminUrl = "https://MYDOMAIN-admin.sharepoint.com"
$userName = "[email protected]"
# Let the user fill in their password in the PowerShell window
$password = Read-Host "Please enter the password for $($userName)" -AsSecureString
$ADGroupID = "6b6cbb5e-81bb-4e72-b806-709168823c20"
$LoginName = "c:0t`.c`|tenant`|$ADGroupID"
# Set credentials
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $password
# Connect to to Office 365
try{
Connect-SPOService -Url $adminUrl -Credential $credentials
write-host "Info: Connected succesfully to Office 365" -foregroundcolor green
}
catch{
write-host "Error: Could not connect to Office 365" -foregroundcolor red
Break new-SPOnlineSite
}
Import-Csv "C:\MyNewSiteCollections.csv" | ForEach-Object {
New-SPOSite -Owner $_.Owner -StorageQuota $_.StorageQuota -Url $_.Url -NoWait -Template $_.Template -TimeZoneID $_.TimeZoneID -Title $_.Name
Set-SPOUser -site $_.Url -LoginName $LoginName -IsSiteCollectionAdmin $True
}
-NoWait
parameter fromNew-SPOSite
OR try to get the site beforeSet-SPOUser
using Get-SPOSite. Let me know if this works.