Our use of cookies

We use cookies to tailor your experience, gather analytics, and provide you with live assitance. By clicking "Accept" or continuing to browse our site you agree to the use of cookies. For more details please read our Cookie Policy.

Script: Create a hierarchy of empty sites and lists in SharePoint site using PowerShell

Disclaimer: this script is given as is, we do not support it nor take responsibility for any use you make of it.


The script below creates a hierarchy of empty sites and lists in a SharePoint site using random names.

To execute it, open a PowerShell prompt, register the script and run it as show below.

. .\CreateHierarchy.ps1

CreateHierarchy -spVersion SPOnline -siteUrl "https://yoursite.sharepoint.com/sites/TestHierarchy" -username "username" -password "password" -domain "yourdomain.onmicrosoft.com" -sitePrefix "dummy" -minNoOfSites 1 -maxNoOfSites 5 -noOfLevels 5 -minNoOfLists 10 -maxNoOfLists 1000


enum SPVersion { SP2010 SP2013 SP2016 SP2019 SPOnline } Function LoadAssemblies { Param( [Parameter(Mandatory=$true)] [SPVersion]$spVersion ) $SP2010ClientDllPath = "C:\Program Files\Common Files\microsoft shared\SharePoint Client" $SP2013ClientDllPath = "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI" $SP2016ClientDllPath = "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI" $SP2019ClientDllPath = "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI" $SPOnlineClientDllPath = "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI" $clientDllPath = "Microsoft.SharePoint.Client.dll" $clientRuntimeDllPath = "Microsoft.SharePoint.Client.Runtime.dll" switch ($spVersion) { SP2010 { $clientDllPath = $SP2010ClientDllPath + "\" + $clientDllPath $clientRuntimeDllPath = $SP2010ClientDllPath + "\" + $clientRuntimeDllPath break; } SP2013 { $clientDllPath = $SP2013ClientDllPath + "\" + $clientDllPath $clientRuntimeDllPath = $SP2013ClientDllPath + "\" + $clientRuntimeDllPath break; } SP2016 { $clientDllPath = $SP2016ClientDllPath + "\" + $clientDllPath $clientRuntimeDllPath = $SP2016ClientDllPath + "\" + $clientRuntimeDllPath break; } SP2019 { $clientDllPath = $SP2019ClientDllPath + "\" + $clientDllPath $clientRuntimeDllPath = $SP2019ClientDllPath + "\" + $clientRuntimeDllPath break; } SPOnline { $clientDllPath = $SPOnlineClientDllPath + "\" + $clientDllPath $clientRuntimeDllPath = $SPOnlineClientDllPath + "\" + $clientRuntimeDllPath break; } } $client = [System.Reflection.Assembly]::LoadFile($clientDllPath) $clientRuntime = [System.Reflection.Assembly]::LoadFile($clientRuntimeDllPath) if( !$client -or !$clientRuntime ){ throw "Could not load Microsoft.SharePoint.Client.dll or Microsoft.SharePoint.Client.Runtime.dll" } } Function CreateSite { Param( [Microsoft.SharePoint.Client.Web][Parameter(Mandatory=$true)]$parentWeb, [string][Parameter(Mandatory=$true)]$sitePrefix, [int][Parameter(Mandatory=$true)]$siteId, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$minNoOfSites, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$maxNoOfSites, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$level, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$noOfLevels, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$minNoOfLists, [int][ValidateRange(1, 1000)][Parameter(Mandatory=$true)]$maxNoOfLists ) $sitePrefix = "$($words[$siteId])_$($level)" $wci = New-Object Microsoft.SharePoint.Client.WebCreationInformation $wci.Url = "$($sitePrefix)_$($siteId)" $wci.Title = "Test site $($sitePrefix), no. $($siteId)" $wci.Webtemplate = "STS#0" $wci.Language = 1033 $wci.UseSamePermissionsAsParentSite = $true $createWeb = $parentWeb.Webs.Add($wci) $parentWeb.Context.Load($createWeb) $parentWeb.Context.ExecuteQuery() Write-Host "Site with url $($createWeb.Url) created" $miliseconds = (Get-Date).Millisecond $noOfLists = Get-Random -Minimum $minNoOfLists -Maximum $maxNoOfLists -SetSeed $miliseconds Write-Host " Number of lists to create on site $($createWeb.Url): $noOfLists" for ($l = 1; $l -le $noOfLists; $l++) { $listTitle = $words[$l] $lci = New-Object Microsoft.SharePoint.Client.ListCreationInformation $lci.Title = $listTitle $lci.TemplateType = "100" $list = $createWeb.Lists.Add($lci) $list.Update() $createWeb.Context.ExecuteQuery() Write-Host " - List $($l) of $($noOfLists) with title $($listTitle) created in site $($createWeb.Url)" } if ($level -lt $noOfLevels) { $miliseconds = (Get-Date).Millisecond $noOfSites = Get-Random -Minimum $minNoOfSites -Maximum $maxNoOfSites -SetSeed $miliseconds Write-Host "Number of subsites to create on site $($createWeb.Url): $noOfSites" for($i = 1; $i -le $noOfSites; $i++) { $level = $level + 1 CreateSite -sitePrefix $sitePrefix -siteId $i -parentWeb $createWeb -minNoOfSites $minNoOfSites -maxNoOfSites $maxNoOfSites -level $level -noOfLevels $noOfLevels -minNoOfLists $minNoOfLists -maxNoOfLists $maxNoOfLists } } } Function CreateHierarchy { Param( [SPVersion][Parameter(Mandatory=$true)]$spVersion, [string][Parameter(Mandatory=$true)]$siteUrl, [string][Parameter(Mandatory=$true)]$username, [string][Parameter(Mandatory=$true)]$password, [string][Parameter(Mandatory=$true)]$domain, [string][Parameter(Mandatory=$true)]$sitePrefix, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$minNoOfSites, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$maxNoOfSites, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$noOfLevels, [int][ValidateRange(1, 10)][Parameter(Mandatory=$true)]$minNoOfLists, [int][ValidateRange(1, 10000)][Parameter(Mandatory=$true)]$maxNoOfLists) if ($minNoOfSites -gt $maxNoOfSites) { throw "minNoOfSites cannot be larger than maxNoOfSites" return } if ($minNoOfLists -gt $maxNoOfLists) { throw "minNoOfLists cannot be larger than maxNoOfLists" return } LoadAssemblies $spVersion $creds = $null; $secPass = ConvertTo-SecureString $password -AsPlainText -Force $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) if ($spVersion -ne [SPVersion]::SPOnline) { $creds = New-Object System.Net.NetworkCredential($userName,$secPass,$domain) $ctx.AuthenticationMode = [Microsoft.SharePoint.Client.ClientAuthenticationMode]::Default } else { $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials("$($username)@$($domain)", $secPass) } $ctx.Credentials = $creds $ctx.Load($ctx.Web) try { $ctx.ExecuteQuery() } catch { throw $_.Exception return } $miliseconds = (Get-Date).Millisecond $noOfSites = Get-Random -Minimum $minNoOfSites -Maximum $maxNoOfSites -SetSeed $miliseconds $level = 1 Write-Host "Number of sites to created for site $($ctx.Web.Url): $noOfSites" for($i = 1; $i -le $noOfSites; $i++) { CreateSite -sitePrefix $sitePrefix -siteId $i -parentWeb $ctx.Web -minNoOfSites $minNoOfSites -maxNoOfSites $maxNoOfSites -level $level -noOfLevels $noOfLevels -minNoOfLists $minNoOfLists -maxNoOfLists $maxNoOfLists } } $words = @('Ants','Areas','Armys','Aunts','Babys','Backs','Balloons','Bands','Banks','Bases','Baths','Beads','Beams','Bears','Beds','Beefs','Beers','Bells','Bikes','Birds','Boats','Bodys','Bombs','Bones','Books','Boots','Boss','Bowls','Boys','Bulbs','Burns','Camps','Cards','Cars','Carts','Caves','Cells','Cents','Citys','Coals','Coils','Combs','Cooks','Cords','Corks','Cribs','Crows','Datas','Debts','Deers','Desks','Dirts','Disks','Docks','Dogs','Dolls','Drops','Drums','Dungs','Dusts','Ears','Edges','Eggs','Exams','Eyes','Faces','Facts','Falls','Fangs','Fears','Films','Fires','Folds','Foods','Foots','Forks','Forms','Frogs','Games','Gates','Genes','Girls','Glues','Goals','Goats','Golds','Hairs','Halls','Hands','Heads','Heats','Hills','Hopes','Hoses','Ideas','Irons','Jails','Jokes','Junks','Kicks','Kings','Knots','Ladys','Lakes','Leads','Lines','Lists','Loafs','Locks','Looks','Loss','Loves','Maids','Malls','Marks','Mass','Maths','Mazes','Meals','Meats','Menus','Mices','Milks','Mines','Mints','Mists','Modes','Moods','Moons','Nails','Navys','Necks','Nests','News','Noses','Notes','Ovens','Pails','Parks','Parts','Pears','Pests','Pets','Poems','Poets','Pushs','Rails','Rains','Rates','Rests','Rices','Rings','Roads','Rocks','Roles','Roofs','Rooms','Roots','Ropes','Roses','Rules','Sails','Salts','Sands','Seats','Ships','Shops','Shows','Sides','Signs','Silks','Sinks','Sizes','Soaps','Socks','Sofas','Songs','Soups','Spots','Stars','Stops','Swims','Tails','Tales','Talks','Tents','Times','Towns','Toys','Trays','Trips','Turns','Units','Users','Veins','Vests','Views','Walks','Washs','Waves','Weeks','Whips','Wifes','Wines','Wings','Wires','Woods','Wools','Works','Worms','Yards','Yarns','Years','Yokes','Zincs','Actors','Adults','Alarms','Albums','Alleys','Angers','Apples','Badges','Basis','Beasts','Bells','Berrys','Bibles','Bikes','Birds','Births','Blades','Bloods','Boards','Bonus','Brains','Brass','Breads','Bricks','Brushs','Bursts','Buyers','Chains','Chairs','Chalks','Cheeks','Chess','Chests','Chiefs','Childs','Class','Clocks','Clowns','Coachs','Coasts','Colors','Comets','Coughs','Covers','Cracks','Crates','Creams','Crimes','Crushs','Curves','Cycles','Deaths','Depths','Drains','Dramas','Dress','Drills','Drinks','Earths','Entrys','Errors','Events','Feasts','Fifths','Flames','Fleshs','Flocks','Floors','Forces','Frogs','Fruits','Geeses','Gloves','Gooses','Grades','Grapes','Guests','Hands','Hearts','Honeys','Horses','Hotels','Houses','Humors','Jellys','Jewels','Judges','Juices','Kittys','Knifes','Laughs','Levels','Lights','Limits','Linens','Lunchs','Magics','Matchs','Medias','Moneys','Months','Mouths','Movies','Musics','Nerves','Nights','Noises','Norths','Offers','Onions','Orders','Owners','Paints','Pants','Papers','Partys','Pastes','Peaces','Phones','Photos','Pianos','Pizzas','Planes','Points','Powers','Prices','Prints','Proses','Queens','Quiets','Quills','Quilts','Radars','Ratios','Rifles','Rings','Rivers','Robins','Robots','Salads','Scales','Scenes','Scents','Screws','Senses','Shades','Shakes','Shames','Shapes','Sheeps','Shelfs','Shirts','Shocks','Shoes','Skates','Skills','Skirts','Slaves','Sleets','Slopes','Smashs','Smells','Smiles','Snails','Solids','Songs','Spaces','Spades','Sparks','Spices','Spoons','Starts','Steaks','Steels','Sticks','Stones','Storys','Stoves','Straws','Swings','Swords','Tables','Tastes','Teeths','Things','Tigers','Titles','Tooths','Topics','Torchs','Touchs','Trains','Trees','Tricks','Truths','Twists','Uncles','Unions','Values','Verses','Videos','Virus','Voices','Watchs','Waters','Waves','Womans','Womens','Worlds','Youths','Actions','Advices','Affairs','Agencys','Amounts','Animals','Apples','Aspects','Attacks','Bananas','Baskets','Beggars','Beliefs','Bottles','Breaths','Bridges','Bubbles','Buckets','Buttons','Cameras','Cancers','Canvas','Carpets','Carrots','Cellars','Chairs','Chances','Cheeses','Cherrys','Chisels','Churchs','Circles','Circus','Clients','Coffees','Collars','Cookies','Coppers','Countys','Cousins','Crayons','Dealers','Degrees','Desires','Details','Devices','Dinners','Doctors','Donkeys','Drawers','Drivers','Editors','Effects','Efforts','Eggnogs','Energys','Engines','Erasers','Estates','Extents','Familys','Farmers','Fathers','Faucets','Fingers','Flights','Flowers','Fungus','Gardens','Gloves','Grapes','Growths','Guitars','Hammers','Harbors','Healths','Heights','Horses','Houses','Icicles','Incomes','Injurys','Insects','Kettles','Kittens','Ladders','Lawyers','Leaders','Lengths','Liquids','Lockets','Lumbers','Magnets','Marbles','Members','Memorys','Meteors','Methods','Middles','Minutes','Moments','Monkeys','Mothers','Nations','Natures','Needles','Numbers','Offices','Oranges','Parcels','Parents','Pebbles','Peoples','Peppers','Persons','Pillows','Planets','Players','Ploughs','Pockets','Poetrys','Polices','Policys','Porters','Potatos','Prisons','Profits','Quinces','Quivers','Rabbits','Reasons','Recess','Recipes','Records','Regions','Rockets','Saddles','Safetys','Samples','Schools','Sectors','Series','Showers','Singers','Sisters','Snails','Snakes','Sneezes','Speechs','Spheres','Spirals','Sponges','Springs','Squares','Sticks','Stitchs','Streams','Streets','Strings','Studios','Systems','Tempers','Tennis','Thanks','Theorys','Threads','Thrills','Throats','Tickets','Toilets','Tongues','Tunnels','Vacuums','Vessels','Volumes','Wealths','Weapons','Windows','Winners','Winters','Workers','Writers','Zephyrs','Zippers','Abilitys','Accounts','Airports','Alcohols','Analysts','Anxietys','Arrivals','Articles','Artisans','Attempts','Balances','Balloons','Bathtubs','Bedrooms','Believes','Cabbages','Cabinets','Captions','Chapters','Charitys','Chickens','Climates','Clothes','Colleges','Compass','Concepts','Contexts','Controls','Countrys','Courages','Crackers','Creators','Crystals','Currents','Diamonds','Diseases','Disgusts','Drawings','Drivings','Emotions','Examples','Failures','Fairies','Feathers','Feelings','Findings','Firemans','Fishings','Fortunes','Freedoms','Freeways','Funerals','Garbages','Grocerys','Haircuts','Harmonys','Hearings','Highways','Historys','Housings','Hydrants','Journeys','Kitchens','Kittens','Ladybugs','Lettuces','Librarys','Lizards','Mailboxs','Managers','Meanings','Measures','Messages','Mixtures','Monsters','Mornings','Opinions','Oranges','Outcomes','Pancakes','Partners','Passions','Payments','Penaltys','Perfumes','Physics','Popcorns','Printers','Problems','Process','Products','Pyramids','Qualitys','Quarters','Rainbows','Readings','Realitys','Revenues','Sciences','Servants','Sessions','Settings','Sisters','Societys','Speakers','Stomachs','Storages','Students','Success','Supports','Surgerys','Sweaters','Teachers','Tensions','Textures','Thoughts','Torpedos','Trainers','Troubles','Vampires','Varietys','Vehicles','Versions','Villages','Visitors','Volcanos','Vultures','Warnings','Weathers','Weddings','Whistles','Writings','Accidents','Achievers','Activitys','Additions','Airforces','Alphabets','Ambitions','Analysis','Arguments','Attitudes','Audiences','Backpacks','Barbecues','Baseballs','Bathrooms','Behaviors','Birthdays','Boundarys','Business','Calendars','Car-Races','Carriages','Categorys','Cemeterys','Cherries','Chickens','Childrens','Computers','Contracts','Creatures','Currencys','Customers','Databases','Decisions','Deliverys','Directors','Disasters','Distances','Divisions','Downtowns','Elections','Elephants','Elevators','Emphasis','Employees','Employers','Exchanges','Feedbacks','Festivals','Footballs','Frictions','Gemstones','Good-Byes','Governors','Guidances','Homeworks','Hospitals','Increases','Industrys','Instances','Internets','Judgments','Languages','Learnings','Locations','Magazines','Marriages','Medicines','Midnights','Ministers','Mosquitos','Mountains','Necklaces','Notebooks','Ornaments','Paintings','Passports','Patiences','Pendulums','Platforms','Pleasures','Politics','Positions','Presences','Prioritys','Propertys','Proposals','Quantitys','Questions','Reactions','Relations','Republics','Resources','Responses','Sandwichs','Seashores','Securitys','Shoppings','Sidewalks','Skeletons','Softwares','Solutions','Spectrums','Squirrels','Stockings','Strangers','Strategys','Surprises','Surveyors','Sympathys','Tapestrys','Teachings','Triangles','Trousers','Umbrellas','Vacations','Weakness','Aeroplanes','Aftermaths','Afternoons','Agreements','Amusements','Apartments','Apparatus','Appliances','Assistants','Attentions','Authoritys','Awareness','Boyfriends','Butterflys','Candidates','Chemistrys','Childhoods','Chocolates','Cigarettes','Classrooms','Committees','Communitys','Complaints','Conditions','Confusions','Criticisms','Data Bases','Departures','Digestions','Directions','Discoverys','Economics','Educations','Equipments','Expansions','Explosives','Historians','Horoscopes','Ice-Creams','Inflations','Inspectors','Insurances','Intentions','Jellyfishs','Knowledges','Lunchrooms','Marketings','Milkshakes','Newspapers','Operations','Parachutes','Passengers','Pollutions','Presidents','Procedures','Professors','Promotions','Quicksands','Receptions','Recordings','Sandpapers','Satellites','Secretarys','Selections','Signatures','Situations','Staircases','Statements','Structures','Substances','Telescopes','Territorys','Traditions','Treadmills','Variations','Vegetables','Videotapes','Appearances','Arithmetics','Assignments','Assistances','Assumptions','Atmospheres','Basketballs','Cappuccinos','Chocolates','Collections','Comparisons','Conclusions','Connections','Definitions','Departments','Depressions','Differences','Difficultys','Discussions','Earthquakes','Efficiencys','Employments','Enthusiasms','Excitements','Expressions','Floodlights','Foundations','Friendships','Girlfriends','Governments','Hieroglyphs','Importances','Impressions','Indications','Initiatives','Inspections','Instruments','Investments','Leaderships','Literatures','Managements','Memberships','Microscopes','Money $$$$s','Obligations','Paintbrushs','Percentages','Perceptions','Permissions','Philosophys','Populations','Possessions','Preferences','Professions','Protections','Psychologys','Punishments','Reflections','Reputations','Resolutions','Restaurants','Revolutions','Sports-Cars','Spot Lights','Suggestions')