Delete (SP2019 on Prem) Site with SubSite(s) - powershell

(FIRST POST - I will do my best to summerize, forgive me ahead of time)
I have a SharePoint site with a list of sites to be deleted, problem is, some of the sites to be deleted have subsites that need to be deleted before the deletion can occure. I have a basic Powershell script that will delete the site as long as there are no subsites.
I am trying to come up with either a method to delete the subsites if the listed site to be deleted has subs or a way to catch the ones that have an error to enter data into a column on the same list or output a file AND to continue deleting the sites without subs.
Here is what I have so far:
#========================================================================#
# Delete confirmed sites #
#========================================================================#
function deleteSites_old ($url, $listName) {
$web = get-SPWeb $url
$list = $web.Lists[$listname]
$items = $list.items | Where-Object {($_['Status'] -eq 'Delete')}
Write-host "List $($list.title) has $($items.count) entries to be deleted"
foreach ($item in $items) {
$siteURL = $item["URL"]
$siteOwner = $itme["SiteOwner"]
write-host $siteURL $siteOwner
try {
write-host "Site deletion"
#Remove-SPWeb -Identity $siteURL -Recycle
}
catch [Microsoft.SharePoint.Powershell.SPCmdRemoveWeb] {
"There was a problem deleting web site $($siteURL)"
}
#Remove-SPWeb -Identity $siteURL -Recycle
#$ListItem["Status"] = "DELETED"
#$ListItem.update()
}
#DELETES THE INSTANCE
$web.Dispose()
}
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$Site = '[URL]'
$list = "[List Name]"
 
deleteSites_old $Site $List
I am still testing so I have commented out as I continue. Thanks ahead of time, I did search the forum first but only found questions related to SPOnline or SP13 (with $ChildSites but couldn't get it to work for my environment)

Related

How to get started on this?

if i provide a site name and a list name , the script should delete the items in the list and then delete the list? is this possible in powershell or javascript? can anyone help me?
This is for SharePoint online so how to make below code to work for SharePoint online?
## SP URL
Write-Host "Provide SharePoint URL:" -ForegroundColor Yellow
$webURL = Read-Host
$web = Get-SPweb $webURL
## LIST NAME
Write-Host "Enter name of the list:" -ForegroundColor Yellow
$listName = Read-Host
$list = $web.lists[$listName]
## SET QUERY
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = 1000
$query.ViewFields = "<FieldRef Name='ID'/>"
$query.ViewFieldsOnly = $true
## EXECUTE
do
{
$listItems = $list.GetItems($query)
$query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach ($item in $listItems)
{
Write-Host "Deleting Item - $($item.Id)" -ForegroundColor Yellow
$list.GetItemById($item.Id).delete()
}
#Reset the "Allow Deletion" Flag
$list.AllowDeletion = $true
$list.Update()
$list.Delete()
}
while ($null -eq $query.ListItemCollectionPosition)
Write-Host "Script finished." -ForegroundColor Green ``````````````
Deleting items from specified list or/and the list itself is possible both using PowerShell and javascript.
For the javascript you may either use REST API calls for that or JSOM. Here you may find examples how to use JSOM to perform basic CRUD operations -> How to: Create, Update, and Delete List Items Using JavaScript. Please be aware that in order for JSOM to work it needs a SP context which may be created only when the JS is executed in the context of SharePoint (so for example on a SharePoint page)
as for PowerShell you may use PnP PowerShell cmdlets for it. Here is the MSDN article how to get the PnP PowerShell for SharePoint Online and connect to a site and here are the commands you were asking for: the Remove-PnPListItem and Remove-PnPList
You could try to use pnp powershell:
Delete item:
Get-PnPList -Identity Lists/MyList | Get-PnPListItem -PageSize 100 -ScriptBlock { Param($items)
$items.Context.ExecuteQuery() } | % {$_.DeleteObject()}
Delete list:
Remove-PnPList -Identity "test5" -Force
Delete the entire list directly, the item will also be deleted.
Download pnp powershell here.

Problem with code in Sharepoint/Powershell

So here's my problem,
We want to automate the copy of notepad (Sharepoint) in my company,
We already have the power-automate script which allows us to copy links from sharepoint sites,
And here is the Power shell code which allows you to recover the site files and copy them to another:
$SiteURL = "https://******.sharepoint.com/sites/********"
$TargetFolderURL = "/sites/*********/*****"
$SitestoCopy = "copy"
Connect-PnPOnline -Url $SiteURL -UseWebLogin
$items = Get-PnPListItem -List $SitestoCopy
Write-Host "Nombre total d'éléments :" $items.Count
ForEach ($item in $items)
{
Write-Host $item["Title"]
#Copy All Files and Folders from one folder to another
Copy-PnPFile -SourceUrl $item["Title"] -TargetUrl $TargetFolderURL -SkipSourceFolderName -Force
}
I have an error : Copy-PnPFile : File not found.
i have no clue to resolve this problem,
Anyone could help me?
Thank you
I think the problem is in the -SourceUrl param. You pass the item Title. According to the spec this should be the relative url to the item. I am not sure now in what column it was stored I am guessing something like "ServerRelativeUrl" or "FileRef". Please try to check it out and change it to correct column to pass the url to the item not the title.
I hope it will be of any help :)
SourceUrl should be the file server relative url, use FileRef instead,
TargetUrl should be TargetFolderURL +filename
Modify the code snippet as below:
$SiteURL = "https://Tenant.sharepoint.com/sites/dev"
$TargetFolderURL = "/sites/dev/docs/"
$SitestoCopy = "copy"
Connect-PnPOnline -Url $SiteURL -UseWebLogin
$items = Get-PnPListItem -List $SitestoCopy
Write-Host "Nombre total d'éléments :" $items.Count
ForEach ($item in $items)
{
$TargetFileUrl=$TargetFolderURL+$item["FileLeafRef"]
#Copy All Files and Folders from one folder to another
Copy-PnPFile -SourceUrl $item["FileRef"] -TargetUrl $TargetFileUrl -SkipSourceFolderName -Force
}

Powershell HasUniqueRoleAssignments to check if subsites have unique permissions.

I am writing a script to check if each site/subsite has unique or inherited permissions. I am having an issue where HasUniqueRole is not doing what it is supposed to do, it just returns true or false but when I write it to host, nothing is printed. Any ideas why this isn't functioning properly or does it need to be loaded in first? If I put it into an if else statement, it prints that any website has inherited permissions.
$site = Read-Host -Prompt "Enter website URL"
Connect-PnPOnline -Url $site -UseWebLogin
$currentSubwebs = Get-PnPSubwebs -Recurse
foreach ($currentSubweb in $currentSubWebs) {
$subWebTitle = $currentSubWeb.Title
Write-Host $subWebTitle -ForegroundColor Red
$subSiteURL = $currentSubweb.Url
Write-Host $subSiteURL -ForegroundColor Green
Write-Host $currentSubweb.HasUniqueRoleAssignments
}
Change
$currentSubwebs = Get-PnPSubwebs -Recurse
to
$currentSubwebs = Get-PnpSubwebs -Recurse -Includes HasUniqueRoleAssignments

Can we update a sharepoint list page without sharepoint powershell snapin

I got a requirement to automate, update of sharepoint list page on weekly basis. Can I update the sharepoint list page with powershell? I donot have access to sharepoint power shell snapins.
You can update sharepoint web parts on a sitepage with powershell, yes. Not sure why you wouldnt have access to the snapins though? Here is a script that would do the job for you:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
Start-SPAssignment -Global
$Web = Get-SPWeb http://your/site/here
$Web.AllowUnsafeUpdates = $true
Try {
$CONTENT_TO_ADD_TO_PAGE = "New content"
#Get the sitepage
$file= $web.GetFile($web.Url +"/SitePages/YOURPAGE.aspx")
if($file.Exists) {
#Web Part Manager to get all web parts from the file
$WebPartManager = $web.GetLimitedWebPartManager( $file, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
#Iterate through each web part
foreach($webPart in $WebPartManager.WebParts | Where {$_.title -eq "WEB PART NAME"}) {
$XmlDoc = New-Object System.Xml.XmlDocument
$contentXml=$xmlDoc.CreateElement("content")
$contentXml.InnerText= $CONTENT_TO_ADD_TO_PAGE
#Set content and Save
$webpart.Content = $contentXml
$webPartManager.SaveChanges($webPart);
}
}
} Finally {
Remove-Variable file, $WebPartManager
$Web.AllowUnsafeUpdates = $false
$Web.Dispose()
Stop-SPAssignment -Global
[GC]::Collect()
}

Delete Navigation Node with Powershell from SharePoint Quicklaunch in all sites in a site collection

I'm trying to write a powershell script to go through all the sub sites in a site collection and remove a node that is no longer required.
I've placed my script below - but I'm getting an error on Get-SPWeb : The pipeline has been stopped - I'm thinking I may need to set a parameter to stop the pipe being closed? Any help is awesome!
$site = Get-SPSite http://sitecollurl
$site | get-spweb -limit all | foreach-object{
$webURL = $_.url
$web = Get-SPWeb $webURL
$navigationNodes = $web.Navigation.QuickLaunch
ForEach ($Node in $NavigationNodes)
{
if($node.Title -eq "My User Profile")
{
$node.Delete()
}
}
$web.Dispose()
}
I just came across this issue so thought I would share, note in my case it was to remove all QuickLaunch menu Items titled "Libraries" if it had no children:
Get-SPSite http://sitecollectionurl | get-spweb -limit all | foreach-object{
$webURL = $_.url
$web = Get-SPWeb $webURL
$pubWeb = [Microsoft.Sharepoint.Publishing.PublishingWeb]::GetPublishingWeb($Web)
$qlNav = $pubWeb.Navigation.CurrentNavigationNodes
$qlHeading = $qlNav | where { $_.Title -eq "Libraries" }
$qlLibraries = $qlHeading.Children
if($qlLibraries.Count -eq 0)
{
$qlHeading.delete()
}
else
{
$qlLibraries | Select Title,ID
$count = $qlLibraries.Count
write-host "Other Libraries are listed on $url. Count = $count"
}
$pubWeb.Update()
$web.Dispose
}
Obviously replace http://sitecollectionurl with your own site collection URL, and libraries with whatever title you are trying to remove.
Dan