Create a Document Library from a Template using SharePoint Online PowerShell - powershell

How do I create a new document library from an existing document library saved as template using SharePoint Online PowerShell?
I was trying the following:
New-PnPList -Title "Test" -Template DocLibTemplate.stp -Url Test
I had no luck on CSOM PowerShell... PnP seemd to be the best option available.

The following PowerShell for your reference.
$ListTemplateInternalName="DocLibTemplate.stp"
$ListName ="PnpDocument"
Connect-PnPOnline -Url https://xx.sharepoint.com/sites/lz -Credential (Get-credential)
$Context = Get-PnPContext
$Web = $Context.Site.RootWeb
$ListTemplates = $Context.Site.GetCustomListTemplates($Web)
$Context.Load($Web)
$Context.Load($ListTemplates)
Invoke-PnPQuery
$ListTemplate = $ListTemplates | where { $_.InternalName -eq $ListTemplateInternalName }
if ($ListTemplate -eq $null)
{
Throw [System.Exception] "Template not found"
}
$ListCreation = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListCreation.Title = $ListName
$ListCreation.ListTemplate = $ListTemplate
$Web.Lists.Add($ListCreation)
Invoke-PnPQuery
Disconnect-PnPOnline

Related

what is the PNP Power shell command equivalent to "New-Object Microsoft.SharePoint.SPFieldUserValue"

Inside SharePoint 2013 i use this command to get the username of the Created By field:-
$Approver = New-Object Microsoft.SharePoint.SPFieldUserValue($sourceweb,$ApprovalListItem["Created By"])
But in SharePoint online what is the equivalent command in PnP Power-Shell script?
Thanks
Per my test, you can try following script to retrieve username of Created By field
#Parameters
$SiteURL = "https://xxx.sharepoint.com/sites/xxx"
$ListName = "TestList"
#Connect to Source Site
Connect-PnPOnline -Url $SiteURL
$ListItems = Get-PnPListItem -List $ListName -PageSize 500 | Where {$_["FileLeafRef"] -like "*.*"}
foreach($ListItem in $ListItems){
Write-Host "Title:" $ListItem["Title"]
Write-Host "Author:" $ListItem["Author"].LookupValue
}

Update Sharepoint wiki page's aspx using powershell

I have been trying to take a manual step out of a process where I clone a wiki page in sharepoint (done via powershell) and then manually go to the aspx in sharepoint designer and update the textpart's default value:
EX:
<WpNs0:SPSlicerTextWebPart runat="server" MaximumCharacters="255" DefaultValue="REPLACETHISVALUE" RequireSelection="False" FilterMainControlWidthPixels="0" FilterName="Text Filter" Title="Text Filter" FrameType="BorderOnly" SuppressWebPartChrome="False" Description="Filters the contents of Web Parts by allowing users to enter a text value." ...
I'm using the following function for building the context for my copy, and I'm wondering if there is a way to pass the final ASPX site URL and manipulate the content:
function Get-SharepointContext
{
Param(
[Parameter(Mandatory=$true)]
$siteUrl,
[Parameter(Mandatory=$false)]
$cred)
If(!$cred){$cred = get-credential -UserName "$ENV:Username#$env:USERDNSDOMAIN" -Message "Login"}
[string]$username = $cred.UserName
$securePassword = $cred.Password
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$ctx.RequestTimeOut = 1000 * 60 * 10;
$ctx.AuthenticationMode =[Microsoft.SharePoint.Client.ClientAuthenticationMode]::Default
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$ctx.Credentials = $credentials
$ctx.Load($ctx.Web)
$ctx.Load($ctx.Site)
$ctx.ExecuteQuery()
Return $ctx
}
Has anyone attempted this before or know of how I can actually do this?
We can change the web part properties using PnP PowerShell or CSOM code.
PnP:
#Get Current Context Site (Root)
$siteurl = "https://abc.sharepoint.com"
Connect-SPOnline -Url $siteurl
$ctx = Get-SPOContext
#Get Web Part ID
webpart = Get-SPOWebPart -ServerRelativePageUrl "/Pages/PnPPage.aspx" -Identity "Text Filter"
$webpartId = $webpart.Id
# Update WebPart
Set-SPOWebPartProperty -ServerRelativePageUrl "/Pages/PnPPage.aspx" -Identity $webpartId -Key Height -Value 500
CSOM:
function Change-WebPart {
#variables that needs to be set before starting the script
$siteURL = "https://spfire.sharepoint.com"
$userName = "mpadmin#spfire.onmicrosoft.com"
$webURL = "https://spfire.sharepoint.com"
$relativePageUrl = "/SitePages/Home.aspx"
# Let the user fill in their password in the PowerShell window
$password = Read-Host "Please enter the password for $($userName)" -AsSecureString
# set SharePoint Online credentials
$SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
# Creating client context object
$context = New-Object Microsoft.SharePoint.Client.ClientContext($webURL)
$context.credentials = $SPOCredentials
#get Page file
$page = $context.web.getFileByServerRelativeUrl($relativePageUrl)
$context.load($page)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#use the WebPartManger to load the webparts on a certain page
$webPartManager = $page.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$context.load($webPartManager.webparts)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#loop through all WebParts to get the correct one and change its property
foreach($webPartDefinition in $webpartmanager.webparts){
$context.Load($webPartDefinition.WebPart.Properties)
#send the request containing all operations to the server
try{
$context.executeQuery()
}
catch{
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
#Only change the webpart with a certain title
if ($webPartDefinition.WebPart.Properties.FieldValues.Title -eq "Documents")
{
$webPartDefinition.webpart.properties["Title"] = "My Documents"
$webPartDefinition.SaveWebPartChanges()
}
}
}
Change-WebPart
Reference:
Update/Delete WebParts On SharePoint Pages Using PnP PowerShell
Editing Web Part properties with PowerShell CSOM in SharePoint

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()
}

Create Folder in DocLib of a Teamsite - Office 365 - Sharepoint Online

I want to create an example folder in a Document Library of a created Teamsite on Sharepoint Online using Powershell but am running into an error.
After I have created the Teamsite I use the following script:
#Retrieve list
$DocLibName = "Dokumente"
$FolderTitle = "Beispiel"
$List = $ctx.Web.Lists.GetByTitle($DocLibName)
$folder = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
$folder["Title"] = $FolderTitle
$folder.Update();
$ctx.Load($List)
$ctx.ExecuteQuery()
Error Message
The type [Microsoft.SharePoint.SPFileSystemObjectType] was not found : Make sure that the assembly that contains this type is loaded.
Line:79 Char:1
+ $ Folder = $ List.addItem ("" [Microsoft.SharePoint.SPFileSystemObjectType ] :: Folde ...
It is not possible to use an index to a null array.
Line:80 Char:1
+ $ Folder ["Title"] = $FolderTitle
It is not possible to call a method for an expression of the NULL .
Line:81 Char:1
+ $Folder.Update();
How can this be resolved?
You are getting this error since Microsoft.SharePoint.SPFileSystemObjectTypetype belongs to SharePoint Server Side API which is not compatible with Office 365.
Below is demonstrated how to create a folder in SharePoint Online site via PowerShell (utilizes SharePoint CSOM API)
Function Create-Folder()
{
Param(
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.Folder]$ParentFolder,
[Parameter(Mandatory=$True)]
[String]$FolderName
)
$folder = $ParentFolder.Folders.Add($folderName)
$ParentFolder.Context.Load($folder)
$ParentFolder.Context.ExecuteQuery()
return $folder
}
Function Get-Context($Url,$Username,$Password){
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$ctx.Credentials = $credentials
return $ctx
}
Usage
$Url = "https://contoso.sharepoint.com/"
$UserName = "jdoe#contoso.onmicrosoft.com"
$Password = ""
$TargetFolderName = "Archive2016"
$ctx = Get-Context -Url $Url -Username $Username -Password $Password
$parentFolder = $ctx.Web.Lists.GetByTitle("Documents").RootFolder
$folder = Create-Folder -ParentFolder $parentFolder -FolderName $TargetFolderName
Write-Host "Folder [$TargetFolderName] has been created succesfully. Url: $($folder.ServerRelativeUrl)"
For creating a folder hierarchy the following script could be utilized:
Function Create-FolderHierarchy()
{
Param(
[Parameter(Mandatory=$True)]
[Microsoft.SharePoint.Client.Folder]$ParentFolder,
[Parameter(Mandatory=$True)]
[String]$FolderUrl
)
$folderNames = $FolderUrl.Trim().Split("/",[System.StringSplitOptions]::RemoveEmptyEntries)
$folderName = $folderNames[0]
$curFolder = $ParentFolder.Folders.Add($folderName)
$ParentFolder.Context.Load($curFolder)
$ParentFolder.Context.ExecuteQuery()
if ($folderNames.Length -gt 1)
{
$curFolderUrl = [System.String]::Join("/", $folderNames, 1, $folderNames.Length - 1)
return Create-FolderHierarchy -ParentFolder $curFolder -FolderUrl $curFolderUrl
}
return $curFolder
}
If you are interested in scenario for uploading files while preserving a folder structure, take a look at How to: Upload files into Office 365 via PowerShell post, it contains ready made script for that purpose.

Powershell script to register SharePoint Online App with Azure

I need help finding a powershell script that would register my "Office365 SharePoint application" with Azure, i want to extract the Client ID from that script.
What I've tried (sorry for not mentioning the sources, i got these online):
try {
# Load the SharePoint snap in
$ver = $host | select version
if ($ver.Version.Major -gt 1) {
$host.Runspace.ThreadOptions = "ReuseThread"
}
if ((Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
[void][System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");
} catch {
throw "A problem occured while loading DLLs: $_.Exception.Message"
}
The above code threw an error saying Microsoft.SharePoint.PowerShell does not exist on my machine.
And later I wanted to try this code, but obviously i did not because of the above error
function Register-App($siteCollection, $appFile, $appTitle) {
try {
$clientID = [guid]::NewGuid().ToString()
$web = Get-SPWeb -Identity $siteCollection
$realm = Get-SPAuthenticationRealm -ServiceContext $web.Site
$appIdentifier = $clientID + '#' + $realm
#Register the App with given ClientId
Register-SPAppPrincipal -DisplayName $appTitle -NameIdentifier $appIdentifier -Site $web | Out-Null
$app = Import-SPAppPackage -Path $appFile -Site $siteCollection -Source ObjectModel -Confirm:$false
#Install the App
Install-SPApp -Web $siteCollection -Identity $app | Out-Null
} catch {
throw "A problem occured while trying to register the app... $_.Exception.Message"
}
}
Any help would be appreciated; For dislikers, help improve this question.
Thanks
"Microsoft.SharePoint.PowerShell" available after you install the SharePoint 2013.
After you install SharePoint 2013, applicable Windows PowerShell cmdlets are available in the SharePoint 2013 Management Shell.
More detail about SharePoint 2013 Management Shell, please refer to here.