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.
Related
(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)
I am trying to add an existing site column to the SharePoint list. I have tried the following code:
#Setup the context
$listTitle = "VersionCleanup2247"
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$clientContext.Load($clientContext.Web);
$clientContext.Load($clientContext.Web.Lists);
$clientContext.ExecuteQuery()
$list = $clientContext.Web.lists | where{$_.Title -eq $listTitle}
if($list)
{
Write-Host "list is already there. Loading the existing list."
$list = $clientContext.Web.lists.GetByTitle($listTitle)
$clientContext.Load($list);
$clientContext.ExecuteQuery()
Write-Host "Loaded" -ForegroundColor Green
}
Write-Host "Loading the default view of list"
$defaultView = $list.defaultView
$clientContext.Load($defaultView)
$clientContext.ExecuteQuery()
Write-Host "Loaded" -ForegroundColor Green
Write-Host "Loading the available field in the current site"
$siteColumns = $clientContext.Web.Fields
$clientContext.Load($siteColumns)
$clientContext.ExecuteQuery()
Write-Host "Loaded" -ForegroundColor Green
Write-host "adding comments fields from available site columns to the list"
$colName = $siteColumns | Where {$_.InternalName -eq "_Comments"}
$clientContext.Load($colName)
$clientContext.ExecuteQuery()
$list.Fields.Add($colName)
$list.Update()
$clientContext.ExecuteQuery()
$defaultView.ViewFields.Add("Comments")
$defaultView.Update()
$clientContext.ExecuteQuery()
Here I am trying to add a column whose internal name is _Commentsand Display name is Comments. But while adding it I am getting the following error:
Error info! Exception calling "ExecuteQuery" with "0" argument(s): "Field or property "DescriptionResource" does not exist."
Following dll files I am loading:
Add-Type -Path "c:\Microsoft.SharePoint.Client.dll"
Add-Type -Path "c:\Microsoft.SharePoint.Client.Runtime.dll"
And I have the full admin access on the site. Any suggestions would be appreciated. Thanks!
I'm attempting to come up with a powershell script that would allow me to export a list of sites and subsites and the permission groups there in to a CSV.
I'm familiar with using the cmdlts but not building whole scripts.
I'm able to use:
Get-SPOSiteGroup | Export-CSV C:\...
To export site groups to a CSV but it doesn't include the name of the sites they are in.
I also found a script online that would print out the sites and subsite in my site collection here:
https://sharepoint.stackexchange.com/questions/101176/powershell-to-list-all-sites-and-subsites-in-sharepoint-online
I'm not sure how to marry the information. I'm trying to export to a CSV a list of sites and subsites and the security groups there in.
I try to run:
get-sposite | Get-SPOSiteGroup **webdite**
And get this error message:
"Get-SPOSiteGroup : The input object cannot be bound to any parameters
for the command either because the command does not take pipeline
input or the input and its properties do not match any of the
parameters that take pipeline input"
I'm not sure how to get all of this to work together.
Get-SPOSiteGroup cmdlet accepts Site parameter, so site groups per every site collection within a tenant could be retrieved like this:
Connect-SPOService -Url $adminUrl
$sitesInfo = Get-SPOSite
#Retrieve and print all sites
foreach ($site in $sitesInfo) {
Write-Host 'Site collection:' $site.Url
Get-SPOSiteGroup -Site $site.Url
Write-Host '-----------------------------'
}
To retrieve in addition groups per every web site, the following script could be utilized:
$adminUrl = "https://<tenant>-admin.sharepoint.com"
$UserName = "<username>#<tenant>.onmicrosoft.com"
$Password = "--password goes here--"
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$pscreds = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $SecurePassword
Connect-SPOService -Url $adminUrl -Credential $pscreds
$sitesInfo = Get-SPOSite
foreach ($site in $sitesInfo) {
Write-Host 'Site collection:' $site.Url
#1. Retrieve and print site info
#Get-SPOSiteGroup -Site $site.Url
$AllWebs = Get-SPOWebs -Url $site.Url -Credential $creds
#2.Retrieve and print webs info (groups Title property in this case)
foreach ($web in $AllWebs) {
$web.Context.Load($web.RoleAssignments.Groups)
$web.Context.ExecuteQuery()
$web.RoleAssignments.Groups.GetEnumerator() | % { Write-Host $_.Title }
}
Write-Host '-----------------------------'
}
Key points:
to retrieve webs within a site collection Get-SPOWebs.ps1 is utilized
here
to get groups per web site Web.RoleAssignments.Groups is used
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()
}
I've used the following sites to help me get this far and to troubleshoot.
Download file from SharePoint
How to download newest file from SharePoint using PowerShell
Mike Smith's Tech Training Notes SharePoint, PowerShell and .Net!
Upload file to a SharePoint doc library via PowerShell
Download latest file from SharePoint Document Library
How to iterate each folders in each of the SharePoint websites using PowerShell
PowerShell's Get-ChildItem on SharePoint Library
I am trying to download random files from SharePoint folder, and I have it working for when I actually know the file name and extension.
Working code with name and extension:
$SharePoint = "https://Share.MyCompany.com/MyCustomer/WorkLoad.docx"
$Path = "$ScriptPath\$($CustomerName)_WorkLoad.docx"
#Get User Information
$user = Read-Host "Enter your username"
$username = "$user#MyCompany"
$password = Read-Host "Enter your password" -AsSecureString
#Download Files
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($UserName, $Password)
$WebClient.DownloadFile($SharePoint, $Path)
However, I don't seem to be able to figure out how to do it with multiple files of unknown names or extensions.
I have tried mapping a drive, only to end up with "drive mapping failed" & "The network path was not found." errors:
$SharePoint = Read-Host 'Enter the full path to Delivery Site'
$LocalDrive = 'P:'
$Credentials = Get-Credential
if (!(Test-Path $LocalDrive -PathType Container)) {
$retrycount = 0; $completed = $false
while (-not $completed) {
Try {
if (!(Test-Path $LocalDrive -PathType Container)) {
(New-Object -ComObject WScript.Network).MapNetworkDrive($LocalDrive,$SharePoint,$false,$($Credentials.username),$($Credentials.GetNetworkCredential().password))
}
$Completed = $true
}
Catch {
if ($retrycount -ge '5') {
Write-Verbose "Mapping SharePoint drive failed the maximum number of times"
throw "SharePoint drive mapping failed for '$($SharePoint)': $($Global:Error[0].Exception.Message)"
} else {
Write-Verbose "Mapping SharePoint drive failed, retrying in 5 seconds."
Start-Sleep '5'
$retrycount++
}
}
}
}
I've also used the following code with similar results or no results at all.
#Get User Information
$user = Read-Host "Enter your username"
$username = "$user#MyCompany"
$password = Read-Host "Enter your password" -AsSecureString
#Gathering the location of the Card Formats and Destination folder
$Customer = "$SharePoint\MyCustomer"
$Products = "$Path\$($CustomerName)\Products\"
#Get Documents from SharePoint
$credential = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-PSDrive -Credential $credential -Name "A" -PSProvider "FileSystem" -Root "$SharePoint"
net use $spPath #$password /USER:$user#corporate
#Get PMDeliverables file objects recursively
Get-ChildItem -Path "$Customer" | Where-Object { $_.name -like 'MS*' } | Copy-Item -Destination $Products -Force -Verbose
Without defined "input parameters", it's not exactly clear the full solution you need so I'll provide a few snippets of PowerShell that should be of use based on what you've described.
I'll spare you the basics of the various OOTB functions (i.e. Get-SPWeb, etc) though can provide those details as well if needed. I've also been overly explicit in the scripting, though know some of these lines could be chained, piped, etc to be made shorter & more efficient.
This example will iterate over the contents of a SharePoint Library and download them to your local machine:
$Destination = "C:\YourDestinationFolder\ForFilesFromSP"
$Web = Get-SPWeb "https://YourServerRoot/sites/YourSiteCollection/YourSPWebURL"
$DocLib = $Web.Lists["Your Doc Library Name"]
$DocLibItems = $DocLib.Items
foreach ($DocLibItem in $DocLibItems) {
if($DocLibItem.Url -Like "*.docx") {
$File = $Web.GetFile($DocLibItem.Url)
$Binary = $File.OpenBinary()
$Stream = New-Object System.IO.FileStream($Destination + "\" + $File.Name), Create
$Writer = New-Object System.IO.BinaryWriter($Stream)
$Writer.write($Binary)
$Writer.Close()
}
}
This is pretty basic; the variables up top are where on your local machine you wish to store the download files ($Destination), the URL of your SharePoint Site/Web ($Web) and the name of the Document Library (Your Doc Library Name).
The script then iterates through the items in the Library (foreach ($DocLibItem in $DocLibItems) {}), optionally filters for say items with a .docx file extension and downloads each to your local machine.
You could customize this further by targeting a specific sub-folder within the Doc Library, filter by metadata or properties of the Docs or even iterate over multiple Sites, Webs and/or Libraries in one script, optionally filtering those based on similar properties.