SIGN UP MEMBER LOGIN:    
ARTICLE

How to add C# code in PowerShell script for adding a SharePoint list item

Posted by Vijai Anand Articles | SharePoint December 24, 2010
In this article we will be seeing how to add C# code in powershell script for adding a new SharePoint list item.
Reader Level:

In this article we will be creating C# code to add an item in the SharePoint list. Then we will make the C# code as a powershell script.

C# Code:

using
System;
using Microsoft.SharePoint;

namespace Vijai.Script
{
    public static class AddanItem
    {
        public static void Add()
        {
            using (SPSite site = new SPSite("http://ServerName:12345/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list=web.Lists["CustomList"];
                    SPListItem item = list.Items.Add();
                    item["Title"] = "Test";
                    item.Update();
                }
            }
        }
    }
}


Adding C# code in PowerShell script:

CSharpScript.ps1
$assembly = ("Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
$code = @"
using System;
using Microsoft.SharePoint;
namespace Vijai.Script
{
    public static class AddanItem
    {
        public static void Add()
        {
            using (SPSite site = new SPSite("http://ServerName:12345/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list=web.Lists["CustomList"];
                    SPListItem item = list.Items.Add();
                    item["Title"] = "Test";
                    item.Update();
                }
            }
        }
    }
}
"@

Add-Type -ReferencedAssemblies $assembly -TypeDefinition $code -Language CSharp

[Vijai.Script.AddanItem]::Add()

write-host -foreground "green" "An item added successfully to the SharePoint List"

Testing:

  • Open the SharePoint 2010 Management Shell as an Administrator.

  • Run the CSharpScript.ps1 file as shown in the following.

    4.gif

  • Go to the SharePoint site and check the CustomList.

  • An item is added successfully to the list.

    3.gif

erver'>
Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Become a Sponsor