Create Items in SharePoint List Programmatically with PowerShell

I am going to share with you how to create items in specified SP list that you may use for too many different purposes with PowerShell, in my scenario used this script for create SP Farm Inventory and keep it up to date like weekly with arranging as scheduled task. Thus the script has delete line at the first time to append current one otherwise it will create duplicated items at every time.

As you may realise from script it is going to retrieve necessary information like site URL, site content database, site administrators and content database size from Farm directly and assign those to variables that is used to create items within specified list.

You need create a document list first with belowmentioned columns  and set it within script parameter that is going create items into.

Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction silentlycontinue      

function CreateItems-InSpecifiedList {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$RootSite,
        [Parameter(Mandatory)]
        [string]$ListName
    )

$web = Get-SPWeb -Identity $RootSite
$list = $Web.Lists[$ListName]
foreach ($Item in $list.Items)
{
    $List.GetItemById($Item.Id).delete()
}
$spsites = Get-SPSite -Limit ALL | select *
$i=0

foreach($spsite in $spsites){
$siteadmins = $null
    ### Set variables..
    $list = $web.Lists[$ListName] 
    $i++
    $SiteURL = $spsite.URL
    $SiteDatabase = $spsite.ContentDatabase.Name
    $SiteAdministrators = $spsite.RootWeb.SiteAdministrators
    $SiteSize = $spsite.ContentDatabase.DiskSizeRequired/1GB

    ### Add site info to list as item..
    $newItem = $list.items.add()    
    $newitem["number"] = $i   
    $newitem["siteurl"] = $SiteURL   
    $newitem["contentdb"] = $SiteDatabase
    $newitem["sitesize"] = $SiteSize  
        foreach($siteadmin in $SiteAdministrators){
        $siteadmins += "<p>" + $siteadmin.DisplayName + "</p>"        
        }
 
    $newitem["siteadmins"] = $siteadmins  
    $newitem.update() 
}

}


CreateItems-InSpecifiedList -RootSite "http://portal.ayyildiz.local/" -ListName  "inventory" 

Hope it works for you, thanks for reading.
Erdem Ayyildiz

About the Author

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir