Monday, 4 July 2016

Site Collection Backup and Restore

Backup Site Collection 


######################### Add SharePoint PowerShell Snapin ###############################################
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
 {
 
 Add-PSSnapin Microsoft.SharePoint.Powershell
 
 }
 


 ########################### End of Add SharePoint PowerShell Snapin ##################################

  ######################## Set Execution Path ################################################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 
 Set-Location $scriptBase
 
 ################################# End of Set Execution Path #################################



############################ Functions Starts Here #########################################

function SiteBackUp([string]$SiteURL, [string]$DestinationPath)
{
 try
  {

    Backup-SPSite -identity $SiteURL -path $DestinationPath -nositelock -Force

    Write-Host $SiteURL "Backup Successfully Completed and Placed in the" $DestinationPath

  }
  catch
  {
  }
}

######################### Function Ends Here ################################################



Write-Host "Site BackUp Process Started!!!"

$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"


######################## Data fetching from CSV #############################################

 $SiteBackupCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $SiteBackupCSV | where {

 
    SiteBackUp $_.SiteURL $_.DestinationPath
 

 }




Sample CSV file:







SiteURL DestinationPath
http://sp2013devvm/sites/Pub2016  D:\Backupfolder\first.bak

Restore Site Collection


######################### Add SharePoint PowerShell Snapin ###############################################
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
 {
 
 Add-PSSnapin Microsoft.SharePoint.Powershell
 
 }
 


 ########################### End of Add SharePoint PowerShell Snapin ##################################

  ######################## Set Execution Path ################################################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 
 Set-Location $scriptBase
 
 ################################# End of Set Execution Path #################################



############################ Functions Starts Here #########################################

function SiteRestore([string]$SiteURL, [string]$SourcePath, [string]$DatabaseName)
{
 try
  {

    Restore-SPSite -identity $SiteURL -path $SourcePath -databasename $DatabaseName -force

    Write-Host $SiteURL "Restore Successfully"

  }
  catch
  {
  }
}

######################### Function Ends Here ################################################



Write-Host "Site Restore Process Started!!!"

$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"


######################## Data fetching from CSV #############################################

 $SiteBackupCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $SiteBackupCSV | where {

 
    SiteRestore $_.SiteURL $_.SourcePath $_.DatabaseName
 

 }


Sample CSV file:



SiteURL SourcePath DatabaseName
http://sp2013devvm/sites/Pub2016  D:\Backupfolder\first.bak Wss_content

























Insert item to the List from CSV file

<#

Purpose of this script:
-----------------------
To insert as an item to the List from CSV file . Insert process done for both On-Premises and also for Office365 environment.

Run Process
-----------
Open this InsertMasterData_List.ps1 file --> Hit f5 button --> Ask On-Premises (or) Office365 --> Answer the following questions

--> AtLast it shows "Data Added Successfully" else if no data in CSV file it shows "No Data Found" in the output screen.

Important Notes
---------------
Sharepoint List Column names and CSV file Header names should be same.


#>





######################### Add SharePoint PowerShell Snapin ###############################################
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
 {
 
 Add-PSSnapin Microsoft.SharePoint.Powershell
 
 }
 
########################### End of Add SharePoint PowerShell Snapin ##################################

$question = Read-Host "Are you proceed with On-Premises or Office365? If On-Premises Type ON Else Type OFF for Office365"


 If (($question -eq "ON") -or ($question -eq "on") -or ($question -eq "On") -or ($question -eq "oN"))
{



$SiteURL=Read-Host -Prompt "Please enter the Site URL"

$ListNM=Read-Host -Prompt "Please enter the List Name"

$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Path (forEx:  C:\Users\spadmin\Desktop\CreateItemsToList\MaterData.csv)"

Write-Host "Connected to SharePoint On-Premises site: '$SiteUrl'" -ForegroundColor Green

try
{

$web = Get-SPWeb $SiteURL

 $Lists = $web.Lists[$ListNM]


#Get the CSV file and connect to the SharePoint list

$csvData = import-csv $CSVFileName 



foreach($items in $csvData)
{
$properties = $items | Get-Member -MemberType Properties

     $listContext = $Lists.AddItem()

    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
       
        $colName=$column.Name
              
        #Write-Host $colName
     
        $listContext[$colName] = $items.$colName
    }
     $listContext.Update()
   } 


if($csvData -ne $null)
{
Write-Host "Data Added Successfully !!!"
}
else
{
Write-Host "No Data Found in CSV !!!" -BackgroundColor White -ForegroundColor Red
}
}
catch
{}

}
Elseif (($question -eq "OFF") -or ($question -eq "off") -or ($question -eq "Off") -or ($question -eq "oFF"))
{


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"

$SiteURL=Read-Host -Prompt "Please enter the Site URL"

$User = Read-Host -Prompt "Please enter your Login Name"

$Password = Read-Host -Prompt "Please enter your password" -AsSecureString

$ListName=Read-Host -Prompt "Please enter the List Name"

$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Path (forEx:  C:\Users\spadmin\Desktop\CreateItemsToList\MaterData.csv)"

try
{

$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)


$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$SiteUrl'" -ForegroundColor Green
   
    $web = $Context.Web  
    $Context.Load($web)
    $Context.ExecuteQuery()  
    $Lists = $Context.Web.Lists.GetByTitle($ListName)
    $Context.Load($Lists)

    $Context.ExecuteQuery()
 
}

#Get the CSV file and connect to the SharePoint list

$csvData = import-csv $CSVFileName



foreach($items in $csvData)
{
$properties = $items | Get-Member -MemberType Properties

    $ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
   
    $listContext = $Lists.AddItem($ListItemInfo)


    # $ni = $Lists.AddItem()

    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
       
        $colName=$column.Name
              
        #Write-Host $colName
     
        $listContext[$colName] = $items.$colName
    }
     $listContext.Update()
     $Context.ExecuteQuery()

}
if($csvData -ne $null)
{
Write-Host "Data Added Successfully !!!"
}
else
{
Write-Host "No Data Found in CSV !!!" -BackgroundColor White -ForegroundColor Red
}
}
catch
{}

}
Else
{
    Write-Host -BackgroundColor White -ForegroundColor Red "INVALID ENTRY! Please try again."
    Break
    #Exit
}

Sample CSV file:













File Upload from Local Drive to Sharepoint Document Library

<#
Purpose of this script:
-----------------------
To upload documents from local drive to the sharepoint document library. Upload process done for On-Premises and also for Office365 environment.

Run Process
-----------
Open this FileUpload.ps1 file --> Hit f5 button --> Ask On-Premises (or) Office365 --> Answer the following questions --> AtLast it shows uploaded file names in the output screen.

No Need of CSV file.

#>


######################### Add SharePoint PowerShell Snapin ###############################################
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
 {
 
 Add-PSSnapin Microsoft.SharePoint.Powershell
 
 }
 
########################### End of Add SharePoint PowerShell Snapin ##################################
 
 $question = Read-Host "Are you proceed with On-Premises or Office365? If On-Premises Type ON Else Type OFF for Office365"


 If (($question -eq "ON") -or ($question -eq "on") -or ($question -eq "On") -or ($question -eq "oN"))
{
#Script for On-Premises

$webUrl = Read-Host -Prompt "Please enter the Site URL"

$docLibraryName = Read-Host -Prompt "Please enter the Document Library Name"

$docLibraryUrlName = Read-Host -Prompt "Please enter the Document Library URL Name"

$localFolderPath = Read-Host -Prompt "Please enter the Folder Path"
 try
 {

#Open web and library

$web = Get-SPWeb $webUrl

$docLibrary = $web.Lists[$docLibraryName]


$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()

ForEach($file in $files)
{

    #Open file
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

    #Add file
    $folder =  $web.getfolder($docLibraryUrlName)

    Write-Host "Uploading file.." -ForegroundColor Green

    $spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)

    Write-Host $file "Uploaded Successfully" -ForegroundColor Green

    #Close file stream
    $fileStream.Close();
}

#Dispose web

$web.Dispose()
}
catch
{
}

 }

 Elseif (($question -eq "OFF") -or ($question -eq "off") -or ($question -eq "Off") -or ($question -eq "oFF"))
{

#Specify tenant admin and site URL
$User = Read-Host -Prompt "Please enter your Login Name"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$Folder=Read-Host -Prompt "Please enter the Folder Path"
$DocLibName = Read-Host -Prompt "Please enter the Document Library Name"

#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
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"

try
{
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List)
$Context.ExecuteQuery()
}
catch
{
}
try
{
#Upload file
Foreach ($File in (dir $Folder -File))
{

 Write-Host "Uploading file.." -ForegroundColor Green
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
 Write-Host $File "Uploaded Successfully" -ForegroundColor Green
}

$FileStream.Close();
}
catch
{
}
}
Else
{
    Write-Host -BackgroundColor White -ForegroundColor Red "INVALID ENTRY! Please try again."
    Break
    #Exit
}

Create Managed Meta data Column in Powershell Script

Add-PSSnapin Microsoft.SharePoint.PowerShell

Start-SPAssignment -Global

#The name for your new MMS column
$fieldName = "MMS Column"

#The site in which your new MMS column is available
$siteUrl = "http://sp2013vm:2015/sites/SharepointPub2015/"

#The name of the MMS Service Application where the Term Set lives
$mmsServiceName = "ManagedMetadata Service"

#The name of the Group where the Term Set lives
$mmsGroupName = "S-D"

#The name of the Term Set which your new MMS column will reference
$mmsTermSetName = "Check"

#Open the Site + Web
$site = Get-SPSite $siteUrl
$web = $site.RootWeb

#Gets a TaxonomySession object
$taxonomy = Get-SPTaxonomySession -Site $site

#Gets the GUID of the MMS Application
$sspId = $taxonomy.TermStores |
    Where-Object {$_.Name -eq $mmsServiceName} |
    Select-Object -ExpandProperty Id |
    Select-Object -ExpandProperty Guid

#Gets the GUID of the Term Set
$termSetId = $taxonomy.TermStores.Groups |
    Where-Object {$_.Name -eq $mmsGroupName} |
    Select-Object -ExpandProperty TermSets |
    Where-Object {$_.Name -eq $mmsTermSetName} |
    Select-Object -ExpandProperty Id |
    Select-Object -ExpandProperty Guid


#Creates a Field
$field = $web.Fields.CreateNewField("TaxonomyFieldType",$fieldName)
$web.fields.add($field)

#Updates with Term Set + SspId
$field = $web.fields.GetField($fieldName)
$field.TermSetId = $termSetId
$field.SspId =  $sspId
$field.Update()

Stop-SPAssignment -Global

Creating List and List Columns from CSV file

######################### Add SharePoint PowerShell Snapin ###############################################
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
 
 {
 
 Add-PSSnapin Microsoft.SharePoint.Powershell
 
 }

######################## Set Execution Path ################################################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 
 Set-Location $scriptBase
 
 ################################# End of Set Execution Path #################################
 $Lists=$null
#Function for Creating List
function CreatingList([string] $ListName)
{
try
{
#Create list with "custom" list template
$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $ListName
$ListInfo.TemplateType = "100"
$List = $Context.Web.Lists.Add($ListInfo)
$List.Description = $ListName
$List.Update()
$Context.ExecuteQuery()
Write-Host "List Name:" $ListName "created successfully"
}
catch{

Write-Host $_.Exception.Message -ForegroundColor Red
}

}




#Function for Creating Columns based on condition
function CreateField([string] $ListName,[string] $ColumnName,[string] $ColumnInternalName,[string] $DataTypes,[string] $DatatypeOptions,[string] $LookupListNM,[string] $LookupColumnNM)
{
 #Retrieve lists
$Lists = $Context.Web.Lists.GetByTitle($ListName)
$Context.Load($Lists)
$Context.ExecuteQuery()
$lisfield=$Lists.Fields
$Context.Load($lisfield)
$Context.ExecuteQuery()

 try
            {
          
  $Lfield = $lisfield.GetByInternalNameOrTitle($ColumnName)
  $Context.Load($Lfield)
  $Context.ExecuteQuery()

  Write-Host "Exception calling "ExecuteQuery" with "0" argument(s): "A duplicate field name "$ColumnName" was found."so create site column in different name" -ForegroundColor Red

  }
 catch
   {



#Write-Host $Lists.Title
try{

if($DataTypes-eq "singleline")
{

#SingleLine
$Lists.Fields.AddFieldAsXml("<Field Type='Text' DisplayName='$ColumnName' Required='True' MaxLength='255' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: SingleLine of Text field created successfully"
}
if($DataTypes-eq "multipleline")
{

#MulipleLine
if($DatatypeOptions -eq "plaintext")
{
#PlainText
$Lists.Fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE' NumLines='6' RichText='FALSE'
Sortable='FALSE' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of Plain Text field created successfully"
}
if($DatatypeOptions -eq "richtext")
{
#RichText
$Lists.Fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE'   NumLines='6'
RichText='TRUE' RichTextMode='Compatible' Sortable='FALSE' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of Rich Text field created successfully"
}
if($DatatypeOptions -eq "enhancedrichtext")
{
#EnhancedRichText
$Lists.Fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE'  NumLines='6' RichText='TRUE'
RichTextMode='FullHtml' IsolateStyles='TRUE' Sortable='FALSE'  Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of EnhancedRich Text field created successfully"
}

}

#Choice
if($DataTypes -eq "choice")
{
if($DatatypeOptions -eq "Dropdown")
{
#echo dropdown
#Dropdown
$Lists.Fields.AddFieldAsXml("<Field Type='Choice' DisplayName='$ColumnName' Required='FALSE' Format='Dropdown'
FillInChoice='FALSE' Name='$ColumnInternalName'>
            <Default>MyChoice1</Default>
            <CHOICES>
                <CHOICE>MyChoice1</CHOICE>
                <CHOICE>MyChoice2</CHOICE>
            </CHOICES>
           </Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in Dropdown created successfully"
}
if($DatatypeOptions -eq "Radiobutton")
{
#echo "radio"
#Radiobutton
$Lists.Fields.AddFieldAsXml("<Field Name='$ColumnInternalName' Type='Choice' DisplayName='$ColumnName' Format='RadioButtons'
        FillInChoice='FALSE' >
            <Default>MyChoice1</Default>
            <CHOICES>
                <CHOICE>MyChoice1</CHOICE>
                <CHOICE>MyChoice2</CHOICE>
            </CHOICES>
        </Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in RadioButton created successfully"
}
if($DatatypeOptions -eq "Checkboxes")
{
#echo "Check"
#Checkboxes(allow multiple selection)
$Lists.Fields.AddFieldAsXml("<Field Name='$ColumnInternalName' Type='MultiChoice' DisplayName='$ColumnName' FillInChoice='FALSE'>
                    <Default>MyChoice1</Default>
                    <CHOICES>
                        <CHOICE>MyChoice1</CHOICE>
                        <CHOICE>MyChoice2</CHOICE>
                    </CHOICES>
                </Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in Checkbox created successfully"
}

}
if($DataTypes -eq "number")
{
#Number Field
$Lists.Fields.AddFieldAsXml("<Field Type='Number' DisplayName='$ColumnName' Required='FALSE' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Number field created successfully"
}
#Date&Time
if($DataTypes -eq "datetime")
{
if($DatatypeOptions -eq "Dateonly")
{
#DateOnly
$Lists.Fields.AddFieldAsXml("<Field Type='DateTime' DisplayName='$ColumnName' Format='DateOnly'   Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Date Only field created successfully"
}
if($DatatypeOptions -eq "Date&Time")
{
#DateandTime
$Lists.Fields.AddFieldAsXml("<Field Type='DateTime' DisplayName='$ColumnName' Format='DateTime'   Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Date and Time field created successfully"
}

}
if($DataTypes -eq "yesrno")
{
#Yes r No
$Lists.Fields.AddFieldAsXml("<Field Type='Boolean' DisplayName='$ColumnName' Name='$ColumnInternalName'>
           <Default>1</Default>
           </Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Yes or No field created successfully"
}
if($DataTypes -eq "peoplergroup")
{
#People or Group
if($DatatypeOptions -eq "PeopleOnly")
{
#PeopleOnly
$Lists.Fields.AddFieldAsXml("<Field Type='User' DisplayName='$ColumnName' List='UserInfo' ShowField='ImnName'
UserSelectionMode='PeopleOnly' UserSelectionScope='0' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: People Only field created successfully"
}
if($DatatypeOptions -eq "People&Group")
{
#People&Group
$Lists.Fields.AddFieldAsXml("<Field Type='User' DisplayName='$ColumnName' List='UserInfo' ShowField='ImnName'
UserSelectionMode='PeopleAndGroups' UserSelectionScope='0' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: People and Group field created successfully"
}

}
if($DataTypes -eq "hyperlinkRpicture")
{
if($DatatypeOptions -eq "Hyperlink")
{
#Hyperlink
$Lists.Fields.AddFieldAsXml("<Field Type='URL' DisplayName='$ColumnName' Format='Hyperlink' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Hyperlink field created successfully"
}
if($DatatypeOptions -eq "Picture")
{
#Picture
$Lists.Fields.AddFieldAsXml("<Field Type='URL' DisplayName='$ColumnName' Format='Image' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Lists.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Picture field created successfully"
}


}
if($LookupListNM -ne $null)
{
try{
$LookupLisNamecon = $Context.Web.Lists.GetByTitle($LookupListNM)
$Context.Load($LookupLisNamecon)
$Context.ExecuteQuery()
}
catch
{}

if($DataTypes -eq "lookup")
{
 try
            {
          
  $Lfield = $lisfield.GetByInternalNameOrTitle($ColumnName)
  $Context.Load($Lfield)
  $Context.ExecuteQuery()

  Write-Host "Exception calling "ExecuteQuery" with "0" argument(s): "A duplicate field name "$ColumnName" was found."so create site column in different name" -ForegroundColor Red

  }
 catch
   {
#Lookup
$castToMethodGeneric = [Microsoft.SharePoint.Client.ClientContext].GetMethod("CastTo")
$castToMethodLookup = $castToMethodGeneric.MakeGenericMethod([Microsoft.SharePoint.Client.FieldLookup])



#$internalName = "LookupWithStaticName"
$displayName = $ColumnName
$displayFieldForLookup = $LookupColumnNM

$lookupFieldXML = "<Field DisplayName='$ColumnInternalName' Type='Lookup' Mult='TRUE' />"
$option = [Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView

$newLookupField = $Lists.Fields.AddFieldAsXml($lookupFieldXML, $true, $option)
$Context.Load($newLookupField)
$lookupField = $castToMethodLookup.Invoke($Context, $newLookupField)
$lookupField.Title = $displayName
$lookupField.LookupList = $LookupLisNamecon.Id
$lookupField.LookupField = $displayFieldForLookup

$lookupField.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Lookup field created successfully"
return
}
}
}

}
catch{

Write-Host ($_.Exception.Message + "so create column in different name") -ForegroundColor Red
}
}
}


#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
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"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

 $question = Read-Host "Are you proceed with On-Premises or Office365? If On-Premises Type ON Else Type OFF for Office365"


 If (($question -eq "ON") -or ($question -eq "on") -or ($question -eq "On") -or ($question -eq "oN"))
{

$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)


if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint On-Premises site: '$siteUrl'" -ForegroundColor Green
   
    $web = $Context.Web  
    $Context.Load($web)  
    $Context.ExecuteQuery()
 
}
# retrieve all site columns (fields)
$web = $Context.Web   
$fields = $web.Fields        
$Context.Load($web)       
$Context.Load($fields)
$Context.ExecuteQuery()

}


Elseif (($question -eq "OFF") -or ($question -eq "off") -or ($question -eq "Off") -or ($question -eq "oFF"))
{
$User = Read-Host -Prompt "Please enter your Login Name"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"


#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$siteUrl'" -ForegroundColor Green
   
    $web = $Context.Web  
    $Context.Load($web)  
    $Context.ExecuteQuery()
 
}
# retrieve all columns (fields)
$web = $Context.Web   
$fields = $web.Fields        
$Context.Load($web)       
$Context.Load($fields)
$Context.ExecuteQuery()



}
Else
{
    Write-Host -BackgroundColor White -ForegroundColor Red "INVALID ENTRY! Please try again."
    Break
    #Exit
}

###################Creating List##################################

 $creatinglistCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $creatinglistCSV |select -first 1 | where {
 
 CreatingList $_.ListName
 
 }


 #################Creating Site columns##########################################################
 
 $SiteColumnCreationDetailsCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $SiteColumnCreationDetailsCSV | where {
 
 CreateField $_.ListName $_.ColumnName $_.ColumnInternalName $_.DataTypes $_.DatatypeOptions $_.LookupListNM $_.LookupColumnNM

 }

 Sample CSV file:

Creating Site Column add to Contenttype(Creation) add to list(Creation) from CSV file

######################### Add SharePoint PowerShell Snapin ###############################################
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
 
 {
 
 Add-PSSnapin Microsoft.SharePoint.Powershell
 
 }
 


 ########################### End of Add SharePoint PowerShell Snapin ##################################
 
 ######################## Set Execution Path ################################################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 
 Set-Location $scriptBase
 
 ################################# End of Set Execution Path #################################
 
 ################################# Functions #####################################################
 
  #$myCType = $null


 function CreateField([string]$ColumnName, [string] $ColumnInternalName, [string] $DataTypes, [string] $DatatypeOptions, [string] $LookupListNM, [string] $LookupColumnNM)
 
 {

 try{




 if($DataTypes-eq "singleline")
{

#SingleLine
$singleline=$fields.AddFieldAsXml("<Field Type='Text' DisplayName='$ColumnName' Required='False' MaxLength='255' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($singleline)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: SingleLine of Text field created successfully"

}
if($DataTypes-eq "multipleline")
{

#MulipleLine
if($DatatypeOptions -eq "plaintext")
{
#PlainText
$plaintxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE' NumLines='6' RichText='FALSE'
Sortable='FALSE' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($plaintxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of Plain Text field created successfully"

}
if($DatatypeOptions -eq "richtext")
{
#RichText
$richtxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE'   NumLines='6'
RichText='TRUE' RichTextMode='Compatible' Sortable='FALSE' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($richtxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of Rich Text field created successfully"

}
if($DatatypeOptions -eq "enhancedrichtext")
{
#EnhancedRichText
$enhancetxt=$fields.AddFieldAsXml("<Field Type='Note' DisplayName='$ColumnName' Required='FALSE'  NumLines='6' RichText='TRUE'
RichTextMode='FullHtml' IsolateStyles='TRUE' Sortable='FALSE' Name='$ColumnInternalName' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($enhancetxt)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: MultiLine of EnhancedRich Text field created successfully"

}

}

#Choice
if($DataTypes -eq "choice")
{
if($DatatypeOptions -eq "Dropdown")
{
#echo dropdown
#Dropdown
$dropdownfld=$fields.AddFieldAsXml("<Field Type='Choice' DisplayName='$ColumnName' Required='FALSE' Format='Dropdown'
FillInChoice='FALSE' Name='$ColumnInternalName'>
            <Default>MyChoice1</Default>
            <CHOICES>
                <CHOICE>MyChoice1</CHOICE>
                <CHOICE>MyChoice2</CHOICE>
            </CHOICES>
           </Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($dropdownfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in Dropdown created successfully"

}
if($DatatypeOptions -eq "Radiobutton")
{
#echo "radio"
#Radiobutton
$radiobut=$fields.AddFieldAsXml("<Field Name='$ColumnInternalName' Type='Choice' DisplayName='$ColumnName' Format='RadioButtons'
        FillInChoice='FALSE' >
            <Default>MyChoice1</Default>
            <CHOICES>
                <CHOICE>MyChoice1</CHOICE>
                <CHOICE>MyChoice2</CHOICE>
            </CHOICES>
        </Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($radiobut)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in RadioButton created successfully"

}
if($DatatypeOptions -eq "Checkboxes")
{
#echo "Check"
#Checkboxes(allow multiple selection)
$checkbxfld=$fields.AddFieldAsXml("<Field Name='$ColumnInternalName' Type='MultiChoice' DisplayName='$ColumnName' FillInChoice='FALSE'>
                    <Default>MyChoice1</Default>
                    <CHOICES>
                        <CHOICE>MyChoice1</CHOICE>
                        <CHOICE>MyChoice2</CHOICE>
                    </CHOICES>
                </Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($checkbxfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Choice field in Checkbox created successfully"

}

}
if($DataTypes -eq "number")
{
#Number Field
$numfld=$fields.AddFieldAsXml("<Field Type='Number' DisplayName='$ColumnName' Required='FALSE' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($numfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Number field created successfully"

}
#Date&Time
if($DataTypes -eq "datetime")
{
if($DatatypeOptions -eq "Dateonly")
{
#DateOnly
$dateoly=$fields.AddFieldAsXml("<Field Type='DateTime' DisplayName='$ColumnName' Format='DateOnly'   Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($dateoly)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Date Only field created successfully"

}
if($DatatypeOptions -eq "Date&Time")
{
#DateandTime
$datetime=$fields.AddFieldAsXml("<Field Type='DateTime' DisplayName='$ColumnName' Format='DateTime'   Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($datetime)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Date and Time field created successfully"
}

}
if($DataTypes -eq "yesrno")
{
#Yes r No
$yrnfld=$fields.AddFieldAsXml("<Field Type='Boolean' DisplayName='$ColumnName' Name='$ColumnInternalName'>
           <Default>1</Default>
           </Field>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($yrnfld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Yes or No field created successfully"

}
if($DataTypes -eq "peoplergroup")
{
#People or Group
if($DatatypeOptions -eq "PeopleOnly")
{
#PeopleOnly
$peoponly=$fields.AddFieldAsXml("<Field Type='User' DisplayName='$ColumnName' List='UserInfo' ShowField='ImnName'
UserSelectionMode='PeopleOnly' UserSelectionScope='0' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($peoponly)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: People Only field created successfully"

}
if($DatatypeOptions -eq "People&Group")
{
#People&Group
$peopgrp=$fields.AddFieldAsXml("<Field Type='User' DisplayName='$ColumnName' List='UserInfo' ShowField='ImnName'
UserSelectionMode='PeopleAndGroups' UserSelectionScope='0' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($peopgrp)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: People and Group field created successfully"

}

}
if($DataTypes -eq "hyperlinkRpicture")
{
if($DatatypeOptions -eq "Hyperlink")
{
#Hyperlink
$hyperlnk=$fields.AddFieldAsXml("<Field Type='URL' DisplayName='$ColumnName' Format='Hyperlink' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($hyperlnk)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Hyperlink field created successfully"

}
if($DatatypeOptions -eq "Picture")
{
#Picture
$picturefld=$fields.AddFieldAsXml("<Field Type='URL' DisplayName='$ColumnName' Format='Image' Name='$ColumnInternalName'/>",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($picturefld)
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Picture field created successfully"

}

}
if($LookupListNM -ne $null)
{

try{
$LookupLisNamecon = $Context.Web.Lists.GetByTitle($LookupListNM)
$Context.Load($LookupLisNamecon)
$Context.ExecuteQuery()
}
catch
{

}

if($DataTypes -eq "lookup")
{

 try
            {
          
  $field = $fields.GetByInternalNameOrTitle($ColumnName)
  $Context.Load($field)
  $Context.ExecuteQuery()

  Write-Host "Exception calling "ExecuteQuery" with "0" argument(s): "A duplicate field name "$ColumnName" was found."so create site column in different name" -ForegroundColor Red

  }
 catch
   {
#Lookup
$castToMethodGeneric = [Microsoft.SharePoint.Client.ClientContext].GetMethod("CastTo")
$castToMethodLookup = $castToMethodGeneric.MakeGenericMethod([Microsoft.SharePoint.Client.FieldLookup])

#$internalName = "LookupWithStaticName"
$displayName = $ColumnName
$displayFieldForLookup = $LookupColumnNM

$newLookupField = $fields.AddFieldAsXml("<Field DisplayName='$ColumnInternalName' Type='Lookup' Mult='FALSE' />",$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldToDefaultView)
$Context.Load($fields)
$Context.Load($newLookupField)
$lookupField = $castToMethodLookup.Invoke($Context, $newLookupField)
$lookupField.Title = $displayName
$lookupField.LookupList = $LookupLisNamecon.Id
$lookupField.LookupField = $displayFieldForLookup

$lookupField.Update()
$Context.ExecuteQuery()
Write-Host "ColumnName:" $ColumnName "Type: Lookup field created successfully"
        return
   }
}

}


}
catch
{
Write-Host ($_.Exception.Message + "so create site column in different name") -ForegroundColor Red

}
}






 function contenttypecreation([string]$ContentTypeNM, [string]$ContentGroupNM )
 {
 try{



 # add a new content type - first, let's get all current ctypes
$web = $Context.Web     
$contentTypes = $web.ContentTypes     
$Context.Load($web)    
$Context.Load($contentTypes)
$Context.ExecuteQuery()
          
# create a new content type object
$cType = New-Object Microsoft.SharePoint.Client.ContentTypeCreationInformation      
$cType.Name = $ContentTypeNM
$cType.ParentContentType = $Context.Web.ContentTypes.GetById("0x01")

$cType.Group = $ContentGroupNM
$myCType = $contentTypes.Add($cType)
#$Context.ExecuteQuery()

$Context.Load($myCType)
$Context.ExecuteQuery()
Write-Host "Content Type " $ContentTypeNM " has been added to " $SiteURL

}
catch
{
 Write-Host $_.Exception.Message "try to create the content type in different name" -ForegroundColor Red
}

 }

 
 function AddSiteColumnsToContentTypes([string]$ColumnName, [string]$ContentTypeNM)
 
 {

   try
        {

  #Check whether site column exists in site collection columns

  try
            {
          
  $field = $fields.GetByInternalNameOrTitle($ColumnName)
  $Context.Load($field)
  $Context.ExecuteQuery()
  #Write-Host "Site column" $ColumnName "exist" -ForegroundColor Cyan
 
 
   }
 catch
   {
        return
   }
   #Getting content types from the root site
  $contentTypes = $Context.Site.RootWeb.ContentTypes
  $Context.Load($contentTypes)
  $Context.ExecuteQuery()

   #Getting specified content type in which we need to add a column
   $contentType = $contentTypes | Where {$_.Name -eq $ContentTypeNM}

   #Get Fields from the content type
   $fieldCollection = $contentType.Fields
   $Context.Load($fieldCollection);
   $Context.ExecuteQuery();

   #Check if field already exists in content type or not
   $IsFieldExists = $false
            foreach($fld in $fieldCollection)
            {
               # Write-Host $fld.get_InternalName()
                if($fld.get_InternalName() -eq $ColumnName){
                    $IsFieldExists = $true
                }
            }
    if($IsFieldExists -eq $false)
            {
                #Get all the columns associated with content type
   
                $fieldRefCollection = $contentType.FieldLinks;
                $Context.Load($fieldRefCollection);
                $Context.ExecuteQuery();
               
                #Add a new column to the content type

                Write-Host "Adding site column " $ColumnName "to the content type" -ForegroundColor Cyan
                $fieldReferenceLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation
                $fieldReferenceLink.Field = $field;
                $contentType.FieldLinks.Add($fieldReferenceLink);
               
               
                $contentType.Update($true)
                $Context.Load($contentType)
                $Context.ExecuteQuery()
               
                Write-Host "Field added successfully" -ForegroundColor Green
            }
            else
            {
                Write-Host "Site Column " $ColumnName " already exists in content type" -ForegroundColor Red
            }
          }
        catch
        {
            Write-Host ("Error while adding field in contet type. Error -->> " + $_.Exception.Message ) -ForegroundColor Red
        }
 
 }

 function CreatingList([string] $ListName)
 {
 try{
 $ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $ListName
$ListInfo.TemplateType = "100"
$List = $Context.Web.Lists.Add($ListInfo)
$List.Description = $ListName
$List.Update()
$Context.ExecuteQuery()
Write-Host "List Name:" $ListName "created successfully"
}
catch{

Write-Host $_.Exception.Message -ForegroundColor Red
}

 }
 function AddingCTtoList([string] $ListName, [string] $ContentTypeNM)
 {

 try
     {
 #Getting content types from the root site
  $contentTypes = $Context.Site.RootWeb.ContentTypes
  $Context.Load($contentTypes)
  $Context.ExecuteQuery()

   #Getting specified content type in which we need to add a column
   $contentType = $contentTypes | Where {$_.Name -eq $ContentTypeNM}
   $CTID=$contentType.Id

   #Load List

  $Context.Load($Context.Web.Lists)
  $Context.ExecuteQuery()

 $contentType=$Context.Web.ContentTypes.GetById($CTID)

  $Context.Load($contentType)

  $contentType.Id

 $ll=$Context.Web.Lists.GetByTitle($ListName)
 $Context.load($ll)
 $Context.load($ll.ContentTypes)
 $Context.ExecuteQuery()
  $ll.ContentTypesEnabled=$true
 $AddedContentType=$ll.ContentTypes.AddExistingContentType($contentType)
 $ll.Update()
 
      
         $Context.ExecuteQuery()
         Write-Host "Adding content type " $contentType.Name " to " $ll.Title
     }
     catch
     {
        Write-Host "This content type already exists, "$_.Exception.Message "so choose another content type" -ForegroundColor Red
     }

 }

 function ReorderContentTypesInList()
{
    param(
       
        [Parameter(Mandatory=$true)][string]$listName,
        [Parameter(Mandatory=$true)][string]$ContentTypeNM
    )

    begin{
        try
        {

        $ContentTypeNamesInOrder= $ContentTypeNM
      
            #Retrieve List
            #
            $list = $Context.Web.Lists.GetByTitle($listName)
            $Context.Load($list)
            $Context.ExecuteQuery()


            #Get Content Types from a list
            #
            $contentTypes = $list.ContentTypes
            $Context.Load($contentTypes)
            $Context.ExecuteQuery()

           # Write-Host $contentTypes.Name
        }
        catch{
            Write-Host "Error while getting context. Error -->> "  + $_.Exception.Message -ForegroundColor Red
        }
    }
    process{
        try
        {

            #Making generic list of content type ids in passed order
            #
            $ctList = New-Object System.Collections.Generic.List[Microsoft.SharePoint.Client.ContentTypeId]
            Foreach($ct in $ContentTypeNamesInOrder){
                $ctToInclude = $contentTypes | Where {$_.Name -eq $ct}
                $ctList.Add($ctToInclude.Id)
            }


            #Updating content type order
            #
            $list.RootFolder.UniqueContentTypeOrder = $ctList
            $list.Update()
            $Context.Load($list)
            $Context.ExecuteQuery()

            Write-Host "Content Type is set to default successfully!!!" -ForegroundColor Green

        }
        catch
        {
            Write-Host ("Error while reordering content types in a list. Error -->> " + $_.Exception.Message) -ForegroundColor Red
        }
    }
    end{
        $Context.Dispose()
    }
}



 ################### End of Functions ###############################################


 #Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
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"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll"

 $question = Read-Host "Are you proceed with On-Premises or Office365? If On-Premises Type ON Else Type OFF for Office365"


 If (($question -eq "ON") -or ($question -eq "on") -or ($question -eq "On") -or ($question -eq "oN"))
{

$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)


if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint On-Premises site: '$siteUrl'" -ForegroundColor Green
   
    $web = $Context.Web  
    $Context.Load($web)  
    $Context.ExecuteQuery()
 
}
# retrieve all site columns (fields)
$web = $Context.Web   
$fields = $web.Fields        
$Context.Load($web)       
$Context.Load($fields)
$Context.ExecuteQuery()

}



Elseif (($question -eq "OFF") -or ($question -eq "off") -or ($question -eq "Off") -or ($question -eq "oFF"))
{


$User = Read-Host -Prompt "Please enter your Login Name"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$SiteURL = Read-Host -Prompt "Please enter the Site URL"
$CSVFileName=Read-Host -Prompt "Please enter Your CSV file Name"

#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

if (!$Context.ServerObjectIsNull.Value)
{
    Write-Host "Connected to SharePoint Online site: '$siteUrl'" -ForegroundColor Green
   
    $web = $Context.Web  
    $Context.Load($web)  
    $Context.ExecuteQuery()
 
}
# retrieve all site columns (fields)
$web = $Context.Web   
$fields = $web.Fields        
$Context.Load($web)       
$Context.Load($fields)
$Context.ExecuteQuery()

}
Else
{
    Write-Host -BackgroundColor White -ForegroundColor Red "INVALID ENTRY! Please try again."
    Break
    #Exit
}


 #################Creating Site columns##########################################################
 
 $SiteColumnCreationDetailsCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $SiteColumnCreationDetailsCSV | where {
 
 CreateField $_.ColumnName $_.ColumnInternalName $_.DataTypes $_.DatatypeOptions $_.LookupListNM $_.LookupColumnNM

 }


 #################Creating Content Type#########################################################

 $contenttypeCreationCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $contenttypeCreationCSV |select -first 1 | where {
  if(($_.ContentTypeNM -ne $null) -and ($_.ContentGroupNM -ne $null))
  {
 contenttypecreation $_.ContentTypeNM $_.ContentGroupNM
 }
 }


 #################Adding site column to content type#############################################
 
 $SiteColumnReferencedContentTypesCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $SiteColumnReferencedContentTypesCSV | where {
 
 AddSiteColumnsToContentTypes $_.ColumnName  $_.ContentTypeNM
 
 }
 

###################Creating List##################################

 $creatinglistCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $creatinglistCSV |select -first 1 | where {
 
 CreatingList $_.ListName
 
 }


 #################Adding Content Type to List#####################

$addingCTtolistCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $addingCTtolistCSV |select -first 1 | where {
 
 AddingCTtoList $_.ListName $_.ContentTypeNM
 
 }


 #################Reordering Content Type in the List#####################

$reorderingCTinlistCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $reorderingCTinlistCSV |select -first 1 | where {
 
 ReorderContentTypesInList $_.ListName $_.ContentTypeNM
 
 }

Sample CSV:


Friday, 1 July 2016

Prepopulate Data in the fields using REST service in Hosted App



function readSponsor(sponsorItemID) {
  
    HostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    AppWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    try{
        var executor = new SP.RequestExecutor(AppWebUrl);
        var qualifiedUrl = AppWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + sponsorListName + "')/items?$filter=SponsorCode eq '" + sponsorItemID + "'&@target='" + HostUrl + "'";
        executor.executeAsync(
           {
               url: qualifiedUrl,
               method: "GET",

               headers: {
                   "accept": "application/json;odata=verbose",
                   "content-type": "application/json;odata=verbose",
                   "X-RequestDigest": $("#__REQUESTDIGEST").val()
               },
               success: function (data) {
                   var jsonObject = JSON.parse(data.body);
                   var sponsorData = jsonObject.d.results;
                 
                 
                   if (sponsorData.length == "1")
                       {
                   //   for (var i = 0; i < sponsorData.length; i++) {
                   var activePara = sponsorData[0].IsActive;
                   $('#sponsorCode').val(sponsorData[0].SponsorCode);
                   $('#sponsorName').val(sponsorData[0].SponsorName);
                   $('#sponsorAddress').val(sponsorData[0].SponsorAddress);
                   $('#sponsorActive').attr('checked', activePara);
                   $('#checkboxID').iCheck({ checkboxClass: 'icheckbox_flat-green', radioClass: 'iradio_flat-green' });
                   $('#primarySponsorContactName').val(sponsorData[0].PrimarySponsorContactName);
                   $('#primarySponsorContactNumber').val(sponsorData[0].PrimarySponsorContactNumber);
                   $('#primarySponsorEmail').val(sponsorData[0].PrimarySponsorEmail);
                   $('#secondarySponsorContactName').val(sponsorData[0].SecondarySponsorContactName);
                   $('#secondarySponsorContactNumber').val(sponsorData[0].SecondarySponsorContactNumber);
                   $('#secondarySponsorEmail').val(sponsorData[0].SecondarySponsorEmail);
                   var noneditableChoice = true;
                   if (sponsorItemID) {
                       ActiveAndInActive(noneditableChoice);
                   }
                   }
               },
               error: errorHandlerRead
           }
       );
    }
    catch (errorMsg) {
        console.log(errorMsg.message);
    }
    function errorHandlerRead(err)
    {
        console.log(err.data);
      
    }
}