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.
Go to the SharePoint site and check the CustomList.
An item is added successfully to the list.
erver'>
Comments