Búsqueda de sitios web

SharePoint Online: compruebe si existe una colección de sitios o un subsitio mediante PowerShell


Requisito: Compruebe si existe un sitio o una colección de sitios en SharePoint Online mediante PowerShell.

¿Cómo comprobar si existe un sitio en SharePoint Online?

¿Alguna vez ha necesitado comprobar si existe un sitio en SharePoint Online? Tal vez le acaban de proporcionar la URL de un posible sitio nuevo y desea asegurarse de que ya se haya creado antes de comenzar a crearlo, o está escribiendo un script de PowerShell y necesita verificar que el sitio exista antes de continuar. tu codigo. En cualquier caso, existen algunas formas de comprobar si un sitio existe. ¡Echemos un vistazo a ellos!

Para confirmar si existe una colección de sitios en SharePoint Online, puede dirigirse rápidamente a:

  1. Centro de administración de SharePoint en https://-admin.sharepoint. com >> Expandir Sitios >> Sitios activos.
  2. Ingrese el nombre del sitio o la URL en "Buscar sitios" para verificar si la colección de sitios existe o no.

Muy bien, ahora te mostraré cómo usar PowerShell para comprobar si existe un sitio de SharePoint Online.

SharePoint Online PowerShell CSOM para comprobar si existe un sitio en la URL proporcionada:

¿Cómo puede saber si un sitio ya existe sin tener que buscar en todos sus sitios desde el centro de administración? ¡PowerShell al rescate! Este script de PowerShell comprueba si existe una colección de sitios en la URL proporcionada:


#Set Parameters
$AdminCenterURL="https://crescent-admin.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com/sites/suppliers"
 
#Connect to SharePoint Online
Connect-SPOService -Url $AdminCenterURL -Credential (Get-Credential)

#Get all site collections
$Sites = Get-SPOSite -Limit All | Select -ExpandProperty URL

#Check if any site with the URL exists already
If($Sites -notcontains $SiteURL)
{
    Write-Host "Site Collection URL '$SiteURL' is available!" -f Green
}
Else
{
    Write-Host "Site URL '$SiteURL' is not available!" -f Yellow
}

Este es un script conveniente cuando intenta automatizar su proceso y necesita asegurarse de que el sitio exista antes de tomar más medidas. ¿Qué tal comprobar si existe un sitio o una colección de sitios a través de CSOM?


#Load SharePoint Online Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Custom Function to Check if Site Collection Exists in Given URL
Function Check-SiteExists($SiteURL, $Credentials)
{
    #Setup context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials
    $Web = $Ctx.Web
    $Ctx.Load($web)
    
    Try {
            $Ctx.ExecuteQuery()
            Return $True
        }
    Catch [Exception] {
      Write-host $_.Exception.Message -f Red
      Return $False
     }        
}

#Variable for Site collection URL
$URL= "https://crescent.sharepoint.com/sites/sales/"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
  
$SiteExists = Check-SiteExists -SiteURL $URL -Credentials $Cred

#Call the function to check site exists
if($SiteExists -eq $True)
 {
    write-host "Given Site Collection Exists!" -f Green
    #Proceed with your script
 }
 else
 {
    write-host "Site Collection doesn't Exists on given URL!" -f Red
 }

Tenga en cuenta que la función Check-SiteExists puede devolver falso en caso de cualquier problema relacionado con la red o fallas de autenticación.

PnP PowerShell para comprobar si el sitio existe en SharePoint Online

PowerShell es un potente lenguaje de secuencias de comandos que puede utilizar para automatizar tareas en Microsoft SharePoint Online. Permítame mostrarle cómo usar PnP PowerShell para comprobar si existe un sitio en SharePoint Online:


#Parameters
$AdminCenterURL = "https://crescent-admin.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com/sites/procurement"

Try
{
    #Connect to Tenant Admin
    Connect-PnPOnline -URL $AdminCenterURL -Interactive
     
    #Check if site exists
    $Site = Get-PnPTenantSite | Where {$_.Url -eq $SiteURL}
    If ($Site -eq $null)
    {
        Write-host "Site Collection $($SiteURL) doesn't exists!" -foregroundcolor Yellow
    }
    Else
    {
        Write-host "Site $($SiteURL) exists already!" -foregroundcolor Green
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

PnP PowerShell para comprobar si existe un subsitio en una colección de sitios


#Parameters
$SiteCollURL = "https://crescent.sharepoint.com/sites/Retail"
$SubSiteURL = "/sites/Retail/archived/2010" #ServerRelativeUrl

Try
{
    #Connect to Tenant Admin
    Connect-PnPOnline -URL $SiteCollURL -Interactive
     
    #Get All Webs from the site
    $Webs = Get-PnPSubWeb -Recurse -IncludeRootWeb

    #Check if site exists
    $Subsite = ($Webs | Select -ExpandProperty ServerRelativeUrl) -contains $SubSiteURL
    If ($Subsite -eq $false)
    {
        Write-host "SubSite $($SubSiteURL) doesn't exists!" -foregroundcolor Yellow
    }
    Else
    {
        Write-host "Site $($SubSiteURL) exists!" -foregroundcolor Green
    }
}
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Esto puede resultar útil para fines de automatización o para verificar si un sitio está activo (¡o si ha sido eliminado!). Mi otro script del lado del servidor para comprobar si existe una colección de sitios o un subsitio en SharePoint usando PowerShell en SharePoint local.

Artículos relacionados