In this PowerShell tutorial, we will discuss various PowerShell SharePoint list operations. We will see how to work with the SharePoint list using PowerShell. In this article we will see below examples:
- How to create Lists & Libraries using PowerShell in SharePoint 2013?
- How to add various fields using PowerShell in SharePoint 2013?
- How to create lookup field using PowerShell in SharePoint 2013?
- How to add People picker field using PowerShell in SharePoint 2013?
- How to create Choice Field using PowerShell in SharePoint 2013?
- How to modify Views in a list using PowerShell in SharePoint 2013?
- How to add an item to a SharePoint list using PowerShell.
- How to delete sharepoint list item using PowerShell based on condition
- Add items from CSV file to SharePoint Online List using PowerShell
Below are a few PowerShell SharePoint 2013/2016 examples.
Create list and libraries in SharePoint using PowerShell
As part of any site/web created in SharePoint, we need to create a list/library to store the information. Below PowerShell script will explain how to create a list and library using PowerShell in SharePoint 2013.
function CreateCustomList($siteCollectionUrl, $listName, $objType) {
$spWeb = Get-SPWeb -Identity $siteCollectionUrl
$list = $spWeb.lists[$listName]
if ($list) {
#TO permanently delete a list, Use:
$List.Delete()
Write-Host "List: $($listName) deleted successfully from: $($siteCollectionUrl)"
}
$tempType = "Custom List"
if ($objType -eq "List") {
$tempType = "Custom List"
}
else {
$tempType = "Document Library"
}
Write-Host "Creating List" $listName "with the template:"$tempType
$spTemplate = $spWeb.ListTemplates[$tempType]
$spListCollection = $spWeb.Lists
$spListCollection.Add($listName, $listName, $spTemplate)
$spListCollection.Update()
$spWeb.close()
}
$siteCollectionUrl = "http://sharepoint13:12345/"
$listName = "Technology Details"
$docLibName = "Technology Repository"
CreateCustomList $siteCollectionUrl $listName "List"
CreateCustomList $siteCollectionUrl $docLibName "Library"
In the above script block, I am creating one custom list and one document library. Check out SharePoint list templates for more SharePoint list templates.
Delete SharePoint list using PowerShell
Let us see how to delete SharePoint list using PowerShell.
We can easily delete a SharePoint list from the browser itself in SharePoint. Go to the List Settings page and then click on “Delete this list” which is under Permissions and Management. This deletes the SharePoint list from the site.
But if the list got corrupted then, we may not able to delete the list through a browser, We can use PowerShell to delete the SharePoint list.
Recently we got one issue where whenever we are trying to go to the settings page of the list we got Sorry, something went wrong issue. So we use PowerShell to delete the corrupted list.
Delete SharePoint list using PowerShell
Below is the PowerShell command to delete a particular list in SharePoint 2013/2016.
We can write the PowerShell script inside Windows PowerShell ISE or in visual studio code.
$web = Get-SPWeb("https://SiteURL/")
$list = $web.lists["List Name"]
$list.AllowDeletion = $true
$list.Update()
$list.Delete()
Once you run the above PowerShell script, the SharePoint list will get deleted from the site.
You can also use the below code to delete SharePoint list using PowerShell.
$siteURL="http://Site URL"
$listName="ListName"
$web=Get-SPWeb $siteURL $list=$web.Lists[$listName]
if($list -ne $null)
{
$list.Delete();
}
This is how to delete a SharePoint list using PowerShell.
Read How to Change SharePoint Site Logo + PowerShell
Change SharePoint List Title using PowerShell
We can also use PowerShell to modify a list title and description in SharePoint 2010, SharePoint 2013/2016.
$site = new-object Microsoft.SharePoint.SPSite("http://site URL")
$web = $site.rootweb
$list = $web.GetList("/Lists/ListName")
$spList.Title = "Modified Title"
$spList.Description = "Modified Description"
$spList.Update()
This is how we can modify a SharePoint list using PowerShell.
Add Columns to SharePoint List using PowerShell
In a SharePoint list, we can create any number of fields in the below code block I am creating numbers, text, and multiline text fields. You can verify all other field types in msdn blog:
# Creating fields in List
$siteCollectionUrl = "http://sharepoint13:12345/"
$spWeb = Get-SPWeb -Identity $siteCollectionUrl
$listName = "Technology Details"
$spList = $spWeb.lists[$listName]
if ($spList) {
#adding the field type(Number) to the list
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Number
$spList.Fields.Add("Salary", $spFieldType, $false)
#adding the field type(Text) to the list
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
$spList.Fields.Add("First Name", $spFieldType, $true)
#adding the field type(Multilines text) to the list
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Note
$spList.Fields.Add("Address", $spFieldType, $true)
$spList.Update()
}
else {
Write-Host "List" $listName "not existed"
}
$spWeb.close()
This is how, we can add columns to SharePoint list using PowerShell.
Read Get sharepoint site template PowerShell
Create lookup column in SharePoint 2013 using PowerShell
Let us see, how to create lookup column in sharepoint 2013 using powershell.
Creating a lookup column in a list is a little tricky than creating any other column, here is the PowerShell script to create a lookup column in SharePoint 2013/2016.
$SiteUrl = "http://sharepoint13:12345/"
$web = Get-SPWeb -identity $SiteUrl
$ParentLstLookupclmnName = 'Title'
$chldListLookupclmnName = "Technology Name"
$ParentList = $web.Lists['Technology Details']
$ChildList = $web.Lists['Opportunities']
#Check if Field exists already
if (!$childList.Fields.ContainsField($chldListLookupclmnName)) {
#sharepoint powershell – create lookup field
$chldListLookupclmn = $ChildList.Fields.AddLookup($chldListLookupclmnName, $ParentList.id, $False)
$chldListLookupclmn = $ChildList.Fields[$chldListLookupclmnName]
#Setup lookup Field property
$chldListLookupclmn.LookupField = $ParentList.Fields[$ParentLstLookupclmnName]
$chldListLookupclmn.Required = $true
$chldListLookupclmn.AllowMultipleValues = $true
$chldListLookupclmn.update()
write-host "Lookup field added successfully!" -f green
}
else {
write-host "Field Exists already!" -f red
}
$web.close()
Add SharePoint People picker field using PowerShell
Below is the PowerShell script to add people picker field using PowerShell in SharePoint 2013/2016.
$webURL = "http://sharepoint13:12345/"
$web = Get-SPWeb $webURL
$mylistName = "Opportunities"
$mylist = $web.Lists[$mylistName]
$spFieldType = [Microsoft.SharePoint.SPFieldType]::User
Write-Host $spFieldType
$mylist.Fields.Add("Manager Name", $spFieldType, $true)
$mylist.Update()
$web.close()
If you want to update the field type of people picker using Powershell.
$site = Get-SPSite "http://sharepoint13:12345/"
$web=$site.OpenWeb()
$list = $web.Lists["Opportunities"]
$spFieldUser = [Microsoft.SharePoint.SPFieldUser]($list.Fields["Manager Name"])
$spFieldUser.LookupField = "EMail"
$spFieldUser.Update()
$web.close()
Below are the lists of various other lookupfield type values:
- Email –> EMail
- Title –> Title
- Account –> Name
- Name (with presence) –> ImnName
- ID –> ID
- Modified –> Modified
- Job Title –> JobTitle
- Name(With Picture And Details) –> NameWithPictureAndDetails
Create Choice Field using PowerShell in SharePoint 2013
Now, we will see how to create a choice column using PowerShell in SharePoint 2013/2016/2019.
$webURL = "http://sharepoint13:12345/"
$web = Get-SPWeb $webURL
$mylistName = "Opportunities"
$spList = $web.Lists[$mylistName]
$choices = New-Object System.Collections.Specialized.StringCollection
$choices.Add("First Choice")
$choices.Add("Second Choice")
$choices.Add("Third Choice")
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Choice
$spList.Fields.Add("ChoiceField",$spFieldType,$false,$false,$choices)
$spList.Update()
$web.close()
Modify Views in a list using PowerShell in SharePoint 2013/2016
Now that we have completed creating lists and fields, let us add the list to quick launch and add new fields to views.
Adding to the quick launch bar & modifying the view:
$spWeb = Get-SPWeb -Identity http://sharepoint13:12345/
$spList = $spWeb.GetList("/Lists/Opportunities")
$spList.OnQuickLaunch = $true
$spView = $spWeb.GetViewFromUrl("/Lists/Opportunities/AllItems.aspx")
$spField = $spList.Fields["Technology Name"]
$spView.ViewFields.Add($spField)
$spView.Update()
$spList.Update()
$spWeb.close()
If you want to add a field to a specific view:
$spWeb = Get-SPWeb -Identity http://sharepoint13:12345/
$spList = $spWeb.Lists["Opportunities"]
$spView = $spList.Views | ? { $_.Title -eq 'Technologies' }
$spField = $spList.Fields["Technology Name"]
$spView.ViewFields.Add($spField)
$spView.Update()
$spWeb.close()
Show/Hide a SharePoint 2013 List using PowerShell
Recently my team got a requirement to hide a SharePoint 2013 list. Here we will discuss how to show or hide a SharePoint 2013 list using PowerShell. The user should not see the list in Site content as well as in Quick Launch.
Here I have a list name as “MyTestList99” which I want to hide from the site content.
PowerShell script to hide a SharePoint 2013 List
Below is the PowerShell script to hide a SharePoint List, which you can write in Windows PowerShell ISE or you can use Visual studio code to write, debug and test PowerShell scripts.
Open SharePoint Management Shell
Add-PSSnapin Microsoft.SharePoint.Powershell
$web = Get-SPWeb "http://win-pfcp2dgt8di/sites/EnjoySharePoint/";
$list = $web.Lists["MyTestList99"];
$list.Hidden = 1; //hiding the list in Site Contents
$list.OnQuickLaunch = $false; // hiding the list in Quick Launch
$list.Update();
PowerShell script to Show a SharePoint 2013 List
Below is the PowerShell script to Show a SharePoint List:
Add-PSSnapin Microsoft.SharePoint.Powershell
$web = Get-SPWeb "http://win-pfcp2dgt8di/sites/EnjoySharePoint/";
$list = $web.Lists["MyTestList99"];
$list.Hidden = 0; //showing the list in Site Contents
$list.OnQuickLaunch = $true; // showing the list in Quick Launch
$list.Update();
Hope this will be useful to you to show or hide a SharePoint 2013 list or document library.
How to add an item to a SharePoint list using PowerShell
Let us see, how to add an item to a SharePoint list using PowerShell.
Below is the PowerShell code, which will add or insert an item to SharePoint list using PowerShell.
$site = new-object Microsoft.SharePoint.SPSite(“http://site URL”)
$web = $site.rootweb
$list = $web.Lists[“ListName”]
$newitem = $list.items.Add()
$newitem[“Column Name1”]= “Column value”;
$newitem[“Column Name2”]= “Column value”;
$newitem.update()
$web.Dispose()
$site.Dispose()
Example: Add item to SharePoint 2016 list using PowerShell
Now, we will see an example of how to add an item to a SharePoint 2013/2016/2016 list using PowerShell.
For this example, I have created a simple SharePoint custom list which has fields like:
- Title (Single line of text)
- Email ID (Single line of text)
- Contact Number (Single line of text)
- Courses (Choice Column)
- UserComments (Multiline text)
And the SharePoint list looks like below:
Below is the PowerShell command to insert an item to SharePoint list.
Here make sure you can use the internal column names while adding items to the list. Get SharePoint internal names of fields in SharePoint.
Just put the below code in PowerShell ISE and run the command.
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
$webURL = "http://mypc:29024/sites/SPTraining/"
$listName = "MyTrainingList"
$web = Get-SPWeb $webURL
$list = $web.Lists[$listName]
$newItem = $list.Items.Add()
$newItem["Title"] = "Bijay"
$newItem["Email_x0020_ID"] = "[email protected]"
$newItem["Contact_x0020_Number"] = "123455666"
$newItem["Courses"] = $newItem.Fields["Courses"].GetFieldValue("SharePoint Developer");
$newItem["UserComments"] = "I am interested for sharepoint training. please contact me."
$newItem.Update()
Once you execute the PowerShell command, the item will be added to the SharePoint list.
Delete SharePoint list item using PowerShell
Let us see, how to delete SharePoint list items created before one month using PowerShell.
Below the PowerShell commands to delete list items created before 1 month in SharePoint 2013/2016.
Add-PSSnapin Microsoft.SharePoint.PowerShell
$web = Get-SPWeb "http://win-pfcp2dgt8di/sites/EnjoySharePoint/"
$list = $web.Lists["MyTestList"]
$DeleteBeforeDate = [Microsoft.SharePoint.Utilities.SPUtility]::CreateISO8601DateTimeFromSystemDateTime([DateTime]::Now.AddDays(-1))
$caml='<Where> <Lt> <FieldRef Name="Created" /><Value Type="DateTime">{0}</Value> </Lt> </Where> ‘ -f $DeleteBeforeDate
$query=new-object Microsoft.SharePoint.SPQuery
$query.Query=$caml
$col=$list.GetItems($query)
Write-Host $col.Count
$col | % {$list.GetItemById($_.Id).Delete()}
$web.Dispose()
Also, you can write the below PowerShell command to delete items created before one month in the SharePoint list or library.
Add-PSSnapin Microsoft.SharePoint.PowerShell
$web = Get-SPWeb "http://win-pfcp2dgt8di/sites/EnjoySharePoint/"
$list = $web.Lists["MyProjectLists"];
$DeleteBeforeDate = [Microsoft.SharePoint.Utilities.SPUtility]::CreateISO8601DateTimeFromSystemDateTime([DateTime]::Now.AddDays(-1))
$caml='<Where> <Lt> <FieldRef Name="Created" /><Value Type="DateTime">{0}</Value> </Lt> </Where> ‘ -f $DeleteBeforeDate
$query=new-object Microsoft.SharePoint.SPQuery
$query.Query=$caml
$collListItems=$list.GetItems($query)
$count = $collListItems.Count – 1
for($intIndex = $count; $intIndex -gt -1; $intIndex–)
{
"Deleting record: " + $intIndex
$collListItems.Delete($intIndex);
}
This is how to delete list items or files with conditions using PowerShell in SharePoint 2013/2016. Here saw here, how to delete items created before 1 month using PowerShell in SharePoint 2013/2016/2019.
Add items from CSV file to SharePoint Online List using PowerShell
Below is the full PowerShell script to insert items to SharePoint Online list from CSV file.
If you are new to PowerShell, you can read an article on Working with PowerShell in SharePoint Online/2016/2013.
Below the script, you can execute using Windows PowerShell ISE.
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#next pass the credentials and connect to web
$siteURL = "https://hubto.sharepoint.com/sites/learnhub"
$Listname="sitecollections"
$userName = "User.onmicrosoft.com"
$PlainPassword = "Password"
$ImportFile ="D: \Powershell\LearnPowershell\Test.csv"
$password = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
# set SharePoint Online credentials
$SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
#Creating client context object
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$clientContext.credentials = $SPOCredentials
$web = $clientContext.Web
$clientContext.load($web)
#Get the List
$List = $clientContext.Web.Lists.GetByTitle($Listname)
$clientContext.Load($List)
$clientContext.executeQuery()
$csv = Import-CSV $ImportFile
foreach($row in $csv)
{
#Creat single list Items
$ListItenCreationInformation =New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$NewListItem = $List.AddItem($ListItenCreationInformation)
$NewListItem["Sourcesite"] = $row. Sourcesite
$NewListItem["TargetSite"] = $row. TargetSite
$NewListItem["WaveId"] = $row.WaveId
$NewListItem["Status"] = $row.Status
$NewListItem.Update()
$ClientContext.ExecuteQuery()
}
Write-Host "Items Added to List Sucessfully"
Let Us Walk Through the Code:
1- Importing all the Data in CSV file.
D: \Powershell\LearnPowershell\Test.csv”
2- In Test.csv file I have capture the input data as below:
3- The below line of code is set SharePoint Online credentials.
$SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
4- The below line for Creating client context object
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$clientContext.credentials = $SPOCredentials
5- Refer below screenshot of code used.
You can see the SharePoint list contains no item before executing the PowerShell script.
After running about PowerShell script, you can see the items from CSV file has been added to SharePoint Online list.
You may like the following PowerShell SharePoint tutorials:
- Bulk SharePoint Online Site Collection Creation using PowerShell
- PowerShell out gridview in SharePoint 2013/2016
- Upload documents to SharePoint document library using PowerShell Remotely
- PowerShell Script to deploy WSP Solution in SharePoint 2013/2016
- How to upload files to SharePoint using PowerShell
- PowerShell read all files from folder and subfolder
- Display warning message in SharePoint site using PowerShell
- How to Get SharePoint site template PowerShell
- How to get file modification time and date using PowerShell
In this PowerShell SharePoint list tutorial, we discussed how to create lists and libraries using PowerShell in SharePoint 2013/2016.
We also saw how to add various types of fields like lookup, people picker, a Choice column in SharePoint using PowerShell. We also saw, how to modify SharePoint list views using PowerShell.
I am Krishna.Vandanapu a SharePoint architect working in IT from last 13+ years, I worked in SharePoint 2007, 2010, 2013, 2016 and Office 365. I have extensive hands on experience in customizing SharePoint sites from end to end. Expertise in SharePoint migration tools like Sharegate, Doc Ave and Metalogix. Migrated SharePoint sites from SharePoint 2007 to 2010 and 2010 to 2013 several times seamlessly. Implementing CSOM with Microsoft best practices. Spent quality time in configuring SharePoint application services like User Profile, Search, Managed Meta data services etc. Now exploring SharePoint Framework and SharePoint 2019