Thursday, February 9, 2012

PowerShell script to Enumerate Sites, Sub-sites and print them in a .csv file

The Powershell script below enumerates/iterates through all Site Collections and Sub-sites for a Web Application and prints the output in a .csv file.

1. Copy the code below and modify the variables highlighted in yellow below, save the following as IterateAllSitesSubsites.ps1 file:


Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$webApplicationURL = "http://dev-sp-2010:1000"
set-variable -option constant -name out -value "C:\PrintAllSitesSubsites.csv"

$webApp = Get-SPWebApplication $webApplicationURL

if($webApp -ne $null)
{
"Web Application : " + $webApp.Name | Out-File $out -Append

foreach($siteColl in $webApp.Sites)
{
   if($siteColl -ne $null)
   {
"Site Collection : " + $siteColl.Url | Out-File $out -Append

foreach($subWeb in $siteColl.AllWebs)
{
if($subWeb -ne $null)
{
#Print each Subsite
#Write-Host $subWeb.Url
"Subsite : " + $subWeb.Name + " - " + $subWeb.Url | Out-File $out -append
                 
$subWeb.Dispose()
}
else
{
Echo $subWeb "does not exist"
}
}
$siteColl.Dispose()
}
else
{
Echo $siteColl "does not exist"
}
}
}
else
{
Echo $webApplicationURL "does not exist, check the WebApplication name"
}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

Echo Finish

2. To automatically run the above .ps1 script as a batch utility, Copy and paste the code below and save it with a .bat file extension

cd /d %~dp0
powershell -noexit -file ".\IterateAllSitesSubsites.ps1" "%CD%"
pause

Run the above .bat file, on the receipt of success message, traverse to the configured path and find the .csv file with all the sites/sub-sites printed.

Here is an alterante way of doing the same thing in a quick way using Powershell CMD:

Get-SPWebApplication "http://SPFix/" | Get-SPSite -Limit All | Get-SPWeb -Limit All | Select Title, URL, ID | Export-CSV C:\IterateAllSitesSubsites.ps1.csv -NoTypeInformation

2 comments:

  1. I received this error whenI ran the script?

    Unexpected token 'C:\PrintAllSitesSubsites.csv"
    $webApp = Get-SPWebApplication $webApplicationURL
    if($webApp -ne $null)
    {
    "Web' in expression or statement.
    At C:\IterateAllSitesSubsites.ps1:14 char:6
    + set-v <<<< ariable -option constant -name out -
    s.csv"
    + CategoryInfo : ParserError: (C:\Pr
    {
    "Web:String) [], ParentContainsErrorRecordExcept
    + FullyQualifiedErrorId : UnexpectedToken

    ReplyDelete
  2. Hi I need to Enumerate Lists, Libraries etc also. any solution

    ReplyDelete