How to delete webparts from the main page in sharepoint using powershell - powershell

I have the following code which adds a webpart, but i need some way to delete all the webparts before this runs. Anybody know how to do this? I have tried multiple ways, but am brand new to powershell and sharepoint and have no idea what i am doing.
$wpm = $file.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared)
$sortedNodes = $pageXml.Module.File.AllUsersWebPart | sort { $_.WebPartZoneID, [int] $_.WebPartOrder }
write-host $sortedNodes
write-host $sortedNodes.Count
foreach ($webPartXml in $sortedNodes)
{
$zoneId = $webPartXml.WebPartZoneID
$zoneIndex = $webPartXml.WebPartOrder
$xml = $webPartXml.InnerText
$wpd = $wpm.ImportWebPart($xml)
$wpd = $wpm.AddWebPart($wpd.WebPart, $zoneId, $zoneIndex)
"Adding a web part to the [$zoneId] zone, [$zoneIndex] position..."
try
{
Submit-ExecuteQuery $context
}
catch
{
Write-Host "The following error occurred while trying to add the web part: $($_.Exception.Message)" -ForegroundColor Red
}
}

Please try the following:
$wpm = $file.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared)
<# Remove All Webparts - Begin #>
foreach ($webPart in $wpm.WebParts)
{
$wpdD = New-Object Microsoft.SharePoint.Client.WebParts.WebPartDefinition
$context.Load($webPart)
$wpdD = $webPart
$wpdD.DeleteWebPart();
try
{
Submit-ExecuteQuery $context
}
catch
{
Write-Host "The following error occurred while trying to add the web part: $($_.Exception.Message)" -ForegroundColor Red
}
}
<# Remove All Webparts - End #>
$sortedNodes = $pageXml.Module.File.AllUsersWebPart | sort { $_.WebPartZoneID, [int] $_.WebPartOrder }
write-host $sortedNodes
write-host $sortedNodes.Count
foreach ($webPartXml in $sortedNodes)
{
$zoneId = $webPartXml.WebPartZoneID
$zoneIndex = $webPartXml.WebPartOrder
$xml = $webPartXml.InnerText
$wpd = $wpm.ImportWebPart($xml)
$wpd = $wpm.AddWebPart($wpd.WebPart, $zoneId, $zoneIndex)
"Adding a web part to the [$zoneId] zone, [$zoneIndex] position..."
try
{
Submit-ExecuteQuery $context
}
catch
{
Write-Host "The following error occurred while trying to add the web part: $($_.Exception.Message)" -ForegroundColor Red
}
}

Related

PowerShell script to sync a specific folder within a SharePoint Document Library

I am trying to adapt a script that syncs an entire document library.
What I want to achieve is syncing just a specific folder within a document library.
IE: User 1 has no permissions to the site or root folder of the document library, but has contribute permission to \site\documents\Folder1\Folder2
Is there a way to script it to sync just folder 2?
When I use the attached script, I get "We can't sync this folder right now" as User1 does not have access to the site or root of the document library.
#region Functions
function Sync-SharepointLocation {
param (
[guid]$siteId,
[guid]$webId,
[guid]$listId,
[mailaddress]$userEmail,
[string]$webUrl,
[string]$webTitle,
[string]$listTitle,
[string]$syncPath
)
try {
Add-Type -AssemblyName System.Web
#Encode site, web, list, url & email
[string]$siteId = [System.Web.HttpUtility]::UrlEncode($siteId)
[string]$webId = [System.Web.HttpUtility]::UrlEncode($webId)
[string]$listId = [System.Web.HttpUtility]::UrlEncode($listId)
[string]$userEmail = [System.Web.HttpUtility]::UrlEncode($userEmail)
[string]$webUrl = [System.Web.HttpUtility]::UrlEncode($webUrl)
#build the URI
$uri = New-Object System.UriBuilder
$uri.Scheme = "odopen"
$uri.Host = "sync"
$uri.Query = "siteId=$siteId&webId=$webId&listId=$listId&userEmail=$userEmail&webUrl=$webUrl&listTitle=$listTitle&webTitle=$webTitle"
#launch the process from URI
Write-Host $uri.ToString()
start-process -filepath $($uri.ToString())
}
catch {
$errorMsg = $_.Exception.Message
}
if ($errorMsg) {
Write-Warning "Sync failed."
Write-Warning $errorMsg
}
else {
Write-Host "Sync completed."
Exit
while (!(Get-ChildItem -Path $syncPath -ErrorAction SilentlyContinue)) {
Start-Sleep -Seconds 2
}
return $true
}
}
#endregion
#region Main Process
try {
#region Sharepoint Sync
[mailaddress]$userUpn = cmd /c "whoami/upn"
$params = #{
#replace with data captured from your sharepoint site.
siteId = ""
webId = ""
listId = ""
userEmail = $userUpn
webUrl = ""
webTitle = ""
listTitle = ""
}
$params.syncPath = "$(split-path $env:onedrive)\$($userUpn.Host)\$($params.webTitle) - $($Params.listTitle)"
Write-Host "SharePoint params:"
$params | Format-Table
if (!(Test-Path $($params.syncPath))) {
Write-Host "Sharepoint folder not found locally, will now sync.." -ForegroundColor Yellow
$sp = Sync-SharepointLocation #params
if (!($sp)) {
Throw "Sharepoint sync failed."
}
}
else {
Write-Host "Location already syncronized: $($params.syncPath)" -ForegroundColor Yellow
Exit
}
#endregion
}
catch {
$errorMsg = $_.Exception.Message
}
finally {
if ($errorMsg) {
Write-Warning $errorMsg
Throw $errorMsg
}
else {
Write-Host "Completed successfully.."
Exit
}
}
#endregion

How do I make this PowerShell script 'loop' tru multiple arrays?

This PowerShell script works (not mine, I found it - data has been changed to dummy data here) - it Syncs Documents from a SharePoint Site to the users OneDrive:
#region Functions
function Sync-SharepointLocation {
param (
[guid]$siteId,
[guid]$webId,
[guid]$listId,
[mailaddress]$userEmail,
[string]$webUrl,
[string]$webTitle,
[string]$listTitle,
[string]$syncPath
)
try {
Add-Type -AssemblyName System.Web
#Encode site, web, list, url & email
[string]$siteId = [System.Web.HttpUtility]::UrlEncode($siteId)
[string]$webId = [System.Web.HttpUtility]::UrlEncode($webId)
[string]$listId = [System.Web.HttpUtility]::UrlEncode($listId)
[string]$userEmail = [System.Web.HttpUtility]::UrlEncode($userEmail)
[string]$webUrl = [System.Web.HttpUtility]::UrlEncode($webUrl)
#build the URI
$uri = New-Object System.UriBuilder
$uri.Scheme = "odopen"
$uri.Host = "sync"
$uri.Query = "siteId=$siteId&webId=$webId&listId=$listId&userEmail=$userEmail&webUrl=$webUrl&listTitle=$listTitle&webTitle=$webTitle"
#launch the process from URI
Write-Host $uri.ToString()
start-process -filepath $($uri.ToString())
}
catch {
$errorMsg = $_.Exception.Message
}
if ($errorMsg) {
Write-Warning "Sync failed."
Write-Warning $errorMsg
}
else {
Write-Host "Sync completed."
while (!(Get-ChildItem -Path $syncPath -ErrorAction SilentlyContinue)) {
Start-Sleep -Seconds 2
}
return $true
}
}
#endregion
#region Main Process
try {
#region Sharepoint Sync
[mailaddress]$userUpn = cmd /c "whoami/upn"
$params = #{
#replace with data captured from your sharepoint site.
siteId = "{11111111-1111-1111-11111111111111111}"
webId = "{22222222-2222-2222-22222222222222222}"
listId = "{33333333-3333-3333-33333333333333333}"
userEmail = $userUpn
webUrl = "https://somecompany.sharepoint.com/sites/graphics"
webTitle = "graphics"
listTitle = "Documents"
}
$params.syncPath = "$(split-path $env:onedrive)\$($userUpn.Host)\$($params.webTitle) - $($Params.listTitle)"
Write-Host "SharePoint params:"
$params | Format-Table
if (!(Test-Path $($params.syncPath))) {
Write-Host "Sharepoint folder not found locally, will now sync.." -ForegroundColor Yellow
$sp = Sync-SharepointLocation #params
if (!($sp)) {
Throw "Sharepoint sync failed."
}
}
else {
Write-Host "Location already syncronized: $($params.syncPath)" -ForegroundColor Yellow
}
#endregion
}
catch {
$errorMsg = $_.Exception.Message
}
finally {
if ($errorMsg) {
Write-Warning $errorMsg
Throw $errorMsg
}
else {
Write-Host "Completed successfully.."
}
}
#endregion
But I need do this for several SharePoint Sites, but I'd like to avoid having to run 10 different PowerPoint Scripts, if possible.
What I've tried:
I've made an array where I've defined the variables for all the sites, like this (with the correct data):
$params = #(
[pscustomobject]#{
siteId = "SiteID";
webId = "webId";
listId = "listId";
userEmail = $userUpn;
webUrl = "webUrl";
webTitle = "webTitle";
listTitle = ""Documents"
}
[Repeated for each Site]
)
I've then altered this part of the original code, to do a ForEach loop:
#region Main Process
try {
#region Sharepoint Sync
[mailaddress]$userUpn = cmd /c "whoami/upn"
$params | ForEach-Object {
$params.syncPath = "$(split-path $env:onedrive)\$($userUpn.Host)\$($params.webTitle) - $($Params.listTitle)"
Write-Host "SharePoint params:"
$params | Format-Table
if (!(Test-Path $($params.syncPath))) {
Write-Host "Sharepoint folder not found locally, will now sync.." -ForegroundColor Yellow
$sp = Sync-SharepointLocation #params
if (!($sp)) {
Throw "Sharepoint sync failed."
}
}
else {
Write-Host "Location already syncronized: $($params.syncPath)" -ForegroundColor Yellow
}
}
#endregion
}
But it's not working as expected: Only the first Site in my Array is synced.
I'm a PowerShell beginner, so please help me: What am I doing wrong?
Thanks!
When looping through all the objects inside the $params array using a ForEach-Object, the object that you want to reference will be $_ .. not $params. So, where you are referencing $params.webTitle, etc., you should be referencing $_.webTitle, $_.listTitle, etc.
If you're new to Powershell, I would recommend you setting a variable like $paramObj for each instance using foreach ($parmObj in $params) {...} to make it clear what you are referencing, making the code look like:
# replaces the ForEach-Object
ForEach ($paramObj in $params) {
Write-Host "SharePoint params:"
$paramObj | Format-Table
# i didn't see a syncPath in your $params custom object.. better if you set a local variable
$syncPath = "$(split-path $env:onedrive)\$($userUpn.Host)\$($paramObj.webTitle) - $($paramObj.listTitle)"
if (!(Test-Path $($syncPath))) {
Write-Host "Sharepoint folder not found locally, will now sync.." -ForegroundColor Yellow
$sp = Sync-SharepointLocation #paramObj
if (!($sp)) {
Throw "Sharepoint sync failed."
}
}
else {
Write-Host "Location already syncronized: $syncPath" -ForegroundColor Yellow
}
}

Adding SP group to a newly created Person or Group Column via Powershell

I am creating a new column called "TEST123" which is a Person Or Group and wanted to also update "Choose from" option from All users to SP group called TESTAccounts.
I have got the following script to create the column but not sure how to make the above changes :
Function Add-FieldToList($SiteURL,$ListName, $FieldName, $FieldType, $IsRequired){
$ErrorActionPreference = "Stop"
Try{
$List = (Get-SPWeb $SiteURL).Lists.TryGetList($ListName)
if($List -ne $null)
{
if(!$List.Fields.ContainsField($FieldName))
{
$List.Fields.Add($FieldName,$FieldType,$IsRequired)
$List.Update()
$View = $List.DefaultView # OR $List.Views["All Items"]
$View.ViewFields.Add($FieldName)
$View.Update()
write-host "New Column '$FieldName' Added to the List!" -ForegroundColor Green
}
else
{
write-host "Field '$FieldName' Already Exists in the List" -ForegroundColor Red
}
}
else
{
write-host "List '$ListName' doesn't exists!" -ForegroundColor Red
}
}
catch {
Write-Host $_.Exception.Message -ForegroundColor Red
}
finally {
$ErrorActionPreference = "Continue"
}
}
$SiteURL="http://TESTURL"
$ListName = "NEWList"
$FieldType = [Microsoft.SharePoint.SPFieldType]::User
$FieldName="TEST123"
$IsRequired = $False
Add-FieldToList $SiteURL $ListName $FieldName $FieldType $IsRequired
You could use the follow powershell set people column choose from certain group:
$SPSite = Get-SPSite 'http://sp'
#Open you web
$OpenWeb = $SpSite.OpenWeb();
#Open Your List
$List = $OpenWeb.Lists["test2"];
$column = $list.Fields["user"]#change to your column name
$column.SelectionGroup=15 #group id you want
$column.Update()

Removing an element from a library

I have a library in a list which contains a document I want to delete. This has to be done for site collections, so I decided to make a script do it.
#Set the Error Action
$ErrorActionPreference = "Stop"
Try{
$customers = $SiteURL.GetFolder
foreach ($customer in $customers){
#customer is a list that contains the library sitepages
$customerlists = $customer.List.TryGetList("Site Pages")
#correctitem is the document item that I want to remove
$correctitem = $customerlists.List.TryGetList("123")
if ($correctitem){
#delete it (havent gotten here yet)
}
}
}
catch {
Write-Host $_.Exception.Message -ForegroundColor Red
}
finally {
#Reset the Error Action to Default
$ErrorActionPreference = "Continue"
}
However, I cant get it to work. The URL works, but the customers variable, when I try to Write-Host it does not display anything.
Any ideas?
If you want to delete a document from a document library, the PowerShell script below for your reference:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$site = new-object Microsoft.SharePoint.SPSite("http://sharepoint-site-url")
$web = $site.openweb()
$list=$web.Lists["Site Pages"]
$listItems = $list.Items
$listItemsTotal = $listItems.Count
Write-Host $listItemsTotal
for ($x=$listItemsTotal-1;$x -ge 0; $x--)
{
if($listItems[$x].name.Contains("123")) # file refers to the name of the document
{
Write-Host("DELETED: " + $listItems[$x].name)
$listItems[$x].Delete()
}
}

adding file to document library

Here is my document library looks like. I have 2 content types with my document library. 1 content type is based on Document and the other content type is based on "Link to a document" type.
I am trying to upload some files using powershell script. I am using a csv file to read line by line and upload files to document library. I am getting error on $i.fileNameASPX. Powershell tells me that Missing expression after , . So what to do.
if($i.ContentType = "LegalLink2Document")
{
$itemType = $docLibrary.ContentTypes[$i.ContentType]
$newFile = $docLibrary.RootFolder.Files.Add($i.fileNameASPX, UTF8Encoding.UTF8.GetBytes(builder.ToString()), $true)
$theItem = $newFile.Item
$theItem["ContentTypeId"] = $itemType.Id
$itemUrl = ew-object Microsoft.SharePoint.SPFieldUrlValue()
$itemUrl.Url = $i.fileLinkUrl
$itemUrl.Descrition = $i.URLDESC
$theItem["URL"] = $itemUrl
}
Here is the Simple PowerShell script to upload files to a document library in SharePoint2013
http://soreddymanjunath.blogspot.in/2014/07/add-file-to-document-library-using.html
cls
asnp "*sh*"
$url=Read-Host "Enter Site Url"
$web=Get-SPWeb -Identity $url
if($web)
{
try
{
$list = $web.Lists.TryGetList("Documents")
$files = Get-ChildItem -Path "D:\M" -Force -Recurse
foreach ($file in $files)
{
$stream = $file.OpenRead()
$done= $list.RootFolder.Files.Add($file.Name, $stream, $true)
Write-Host $done.Name "Uploaded into the Site" -BackgroundColor Green
}
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage
}
}
else
{
Write-Host "Site Doesn't exist"
}
$list.Update();