Create Site Columns in SharePoint Online (Office 365)
using CSOM
cls
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
# Create a context and return the context object.
function getContext()
{
$context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$context.Credentials = $credentials
return $context;
}
# Check if you are able to connect to SharePoint online.
function validateSPOnline()
{
try
{
$ctx = getContext;
$web = $ctx.Web;
$ctx.Load($web);
$ctx.ExecuteQuery();
return $true;
}
catch
{
Write-Host "Unable to connect with SharePoint online site. Error description: " $_.Exception.Message -ForegroundColor Yellow;
break;
}
}
# Create Site Columns by reading a xml file: sitecolumns.xml
function createAllSiteColumns()
{
$ctx = getContext;
$web = $ctx.Web;
# Read Fields from Xml Template
$siteColumnsXml = [xml](get-content $file_SiteColumns)
Write-Host "Creating site column(s)..." -f Cyan
foreach ($node in $siteColumnsXml.Template.Field)
{
$fieldName = $node| Select DisplayName
$web.Fields.AddFieldAsXml($node.OuterXml, $false, [Microsoft.SharePoint.Client.AddFieldOptions]::DefaultValue);
$ctx.ExecuteQuery();
}
$ctx.Dispose();
$ctx = $null;
}
function main()
{
if (validateSPOnline)
{
createAllSiteColumns;
}
}
#SharePoint Online Settings
#$siteUrl = Read-Host 'Please enter the SharePoint online site url'
#$username = Read-Host 'Please enter the username'
#$password = Read-Host "Enter password" -AsSecureString
$siteUrl = “https://spapps.sharepoint.com”
$username = "muhammadsalman@SPApps.onmicrosoft.com"
[string]$pwd = “Passwort123456“
$password = $pwd | ConvertTo-SecureString -AsPlainText -Force
# File Paths
$file_SiteColumns = "C:\Users\Projects\SPApp-Zeiterfassung\List Creation\SiteColumns.xml"
main
Site Columns XML file
Kunde Intern
Great! works like a charm :)
ReplyDelete