Home > front end >  Get-SPOSite find existing sites
Get-SPOSite find existing sites

Time:09-21

This is the code that will check if any of the sites listed already exists.

 $sites = get-content -Path C:\code\CheckSPSites.txt

foreach($site in $sites){
$url = (Get-SPOSite -Filter{url -like $site} -ErrorAction SilentlyContinue) -ne $null


        if ($url -eq $true){
            Write-Host "$site already created" -BackgroundColor Red
        }else{
            Write-Host "$site not created" -BackgroundColor Green
        }
}

It doesn't find the sites when I use the variable $site to filter the search.

I've tried putting the variable in quotes (Get-SPOSite -Filter{url -like "$site") and it doesn't work either.

Any help would be appreciated.

Many thanks

CodePudding user response:

Thank you Theo and UBK. Posting your suggestion as an answer to help other community members.

You can use -Identity parameter along with the site collection URL to find out the existence.

For example: Get-SPOSite -Identity https://contoso.sharepoint.com

# Verify if site of same name already exists in SharePoint Online
$siteAlreadyExists = Get-SPOSite -Identity $url

# If it does, stop the script
if ($null -ne $siteAlreadyExists) {
    Write-Host "Site already exists" -ForegroundColor Red
    ...
}

If your code fails when site is not present, then you can try following try-catch block:

try {
    $siteAlreadyExists = Get-SPOSite -Identity $url

    if ($null -ne $siteAlreadyExists) {
        Write-Host "Site already exists" -ForegroundColor Red
    }
}
catch {
    Write-Host "Site already exists" -ForegroundColor Red
} 

You can refer to Number of SPO sites causing issue with Get-SPOSite

  • Related