Showing posts with label Powershell Script For Sharepoint. Show all posts
Showing posts with label Powershell Script For Sharepoint. Show all posts

Monday, 4 July 2016

Log Creation Script

$msg="Everything is allrite"
Write-Log -Message $msg -WarningAction Ignore


function Write-Log
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNullOrEmpty()]
        [Alias("LogContent")]
        [string]$Message,

        [Parameter(Mandatory=$false)]
        [Alias('LogPath')]
        [string]$Path='C:\Logs\PowerShellLog.log',
       
        [Parameter(Mandatory=$false)]
        [ValidateSet("Error","Warn","Info")]
        [string]$Level="Info",
       
        [Parameter(Mandatory=$false)]
        [switch]$NoClobber
    )

    Begin
    {
        # Set VerbosePreference to Continue so that verbose messages are displayed.
        $VerbosePreference = 'Continue'
    }
    Process
    {
       
        # If the file already exists and NoClobber was specified, do not write to the log.
        if ((Test-Path $Path) -AND $NoClobber) {
            Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name."
            Return
            }

        # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path.
        elseif (!(Test-Path $Path)) {
            Write-Verbose "Creating $Path."
            $NewLogFile = New-Item $Path -Force -ItemType File
            }

        else {
            # Nothing to see here yet.
            }

        # Format Date for our Log File
        $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

        # Write message to error, warning, or verbose pipeline and specify $LevelText
        switch ($Level) {
            'Error' {
                Write-Error $Message
                $LevelText = 'ERROR:'
                }
            'Warn' {
                Write-Warning $Message
                $LevelText = 'WARNING:'
                }
            'Info' {
                Write-Verbose $Message
                $LevelText = 'INFO:'
                }
            }
       
        # Write log entry to $Path
        "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append
    }
    End
    {
    }
}

Creating Group, Premission level, Assigning permission to the group and Users to the group


<#
NOTE:
-----

In this Powershell Script to achieve Group Creation, Permission Levels Creation, Permission Given to the created group and Add Users to the group.
--------------------------------------------------------------------------------------------------------------------------------------------------
All required data are fetching from CSV file such as GroupName, GroupDescription, PermissionLevelName, PermissionLevelDescription, PermissionLevelList and Users.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
We can use this script in On-Premises(Offline) and Office365(Online).
---------------------------------------------------------------------
When start to run the script it will ask On-Premises (or) Office365 after choose the environment.
-------------------------------------------------------------------------------------------------
If it is On-Premises then it will ask Site URL and CSV file name finally Hit Enter then progress message will display there.
----------------------------------------------------------------------------------------------------------------------------
If it is Office365 then it will ask UserName, Password, Site URL and CSV file name finally Hit Enter then progress message will display there.
----------------------------------------------------------------------------------------------------------------------------------------------

#>


######################### 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 PermissionLevelCreation([string]$PermissionLevelName, [string]$PermissionLevelDescription, [string]$PermissionLevelList)
{
 try
  {
    $web = $Context.Web  
    $Context.Load($web)  
    $permissionlevel = $PermissionLevelList;
    #"ManageLists, CancelCheckOut, AddListItems, EditListItems, DeleteListItems, ViewListItems, ApproveItems, OpenItems, ViewVersions, DeleteVersions, CreateAlerts, ViewFormPages, ManagePermissions, BrowseDirectories, ViewPages, EnumeratePermissions, BrowseUserInfo, UseRemoteAPIs, Open"
    $RoleDefinitionCol = $web.RoleDefinitions
    $Context.Load($RoleDefinitionCol)
    $Context.ExecuteQuery() 
   
    $permExists = $false
    $spRoleDef = New-Object Microsoft.SharePoint.Client.RoleDefinitionCreationInformation
    $spBasePerm = New-Object Microsoft.SharePoint.Client.BasePermissions
    $permissions = $permissionlevel.split(",");

    foreach($perm in $permissions)
    {
    $spBasePerm.Set($perm)
    }  
    try
    {

    #Create Permission Levels for group

    $spRoleDef.Name = $PermissionLevelName
    $spRoleDef.Description = $PermissionLevelDescription
    $spRoleDef.BasePermissions = $spBasePerm   
    $roleDefinition = $web.RoleDefinitions.Add($spRoleDef)
    $Context.ExecuteQuery()
    Write-Host $PermissionLevelName "Permission Levels created successfully!!!"  
    }
    catch
    {
    Write-Host "Permission Level Name is already created so try it in different Permission Level Name" -ForegroundColor Red
    }
   }
   catch
   {
  
   }
}


function CreateGrpNPermissionLevel([string]$GroupName, [string]$GroupDescription, [string]$PermissionLevelName)
 
 {
 try
 {  
    try
    {
    #Retrieve Groups

    $Groups = $Context.Web.SiteGroups
    $Context.Load($Groups)
    $Context.ExecuteQuery() 

    #Create Group

    $NewGroup = New-Object Microsoft.SharePoint.Client.GroupCreationInformation
    $NewGroup.Title = $GroupName
    $NewGroup.Description = $GroupDescription
    $custGroup = $Context.Web.SiteGroups.Add($NewGroup)
    $Context.Load($custGroup)
    $Context.ExecuteQuery()
    Write-Host $GroupName "Group created successfully!!!"
    }
    catch
    {
    Write-Host $GroupName "Group Name is already created so try it in different Group Name" -ForegroundColor Red

     }

    try
    {

     #Retrieve Permission Level by Name
   
     $grpPermissionLevel = $Context.Web.RoleDefinitions.GetByName($PermissionLevelName)   

     #Bind Permission Level to Group

      $currentGroupName = $Context.Web.SiteGroups.GetByName($GroupName)
      $RoleDefBind = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Context)
      $RoleDefBind.Add($grpPermissionLevel)
      $Assignments = $Context.Web.RoleAssignments
      $RoleAssignOneNote = $Assignments.Add($currentGroupName,$RoleDefBind)
      $Context.Load($currentGroupName)
      $Context.ExecuteQuery()
      Write-Host $PermissionLevelName "Group permission level activated successfully!!!"
    
    }
    catch
    {
    Write-Host $PermissionLevelName "Group Permission Level is already active only" -ForegroundColor Red
    }
 }
 catch
 {
 
 }
 }

 function addUsernGrp([string]$GroupName, [string]$Users)
 {
 try
 {
    $spoGName=$GroupName
    $currentGroup = $Web.SiteGroups.GetByName($spoGName)

    $userToAdd=$Users

    $userList = $userToAdd.split(",");
    foreach($NUsers in $userList)
    {
    #$spGrpUsers.Set($NUsers)
    $Member = $Context.Web.EnsureUser($NUsers)
    $Context.Load($Member)

    # Add Member (can be user or Security Group)
    $addMember=$currentGroup.Users.AddUser($Member)
    $Context.Load($addMember)
    $Context.ExecuteQuery()
    }

   
    Write-Host "Users Added Successfully to" $GroupName "!!!"
 }
 catch
 {

 }
 }


########################### Functions Ends Here ###########################################

 #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"


$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()
 
}

}



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 Office365 site: '$SiteURL'" -ForegroundColor Green

     
    $web = $Context.Web  
    $Context.Load($web)  
    $Context.ExecuteQuery()
    
 }


}
  


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


 #################Creating Group##########################################################

 
$permissionLevelsCSV = $scriptBase + "\" + $CSVFileName
 
 import-csv $permissionLevelsCSV |select -first 1 | where {
 
 PermissionLevelCreation $_.PermissionLevelName $_.PermissionLevelDescription $_.PermissionLevelList
 
 }



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

 
    CreateGrpNPermissionLevel $_.GroupName $_.GroupDescription $_.PermissionLevelName
 

 }



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

 
    addUsernGrp $_.GroupName $_.Users
 

 }


Sample CSV file:







To enable SideLoading feature in Non - Developer Site for App Deployment

Add-PSSnapin Microsoft.SharePoint.PowerShell

$programFiles = [environment]::getfolderpath("programfiles")

add-type -Path $programFiles'\SharePoint Online Management Shell\' + `
  'Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll'

Write-Host `
  'To enable SharePoint app sideLoading, ' + `
  'enter Site Url, username and password'

$siteurl = Read-Host 'Site Url'
$username = Read-Host "User Name"
$password = Read-Host -AsSecureString 'Password'

if ($siteurl -eq '') {
    $siteurl = 'https://vigtech.sharepoint.com/sites/MyTeamSite'
    $username = 'sivavicky@vigtech.onmicrosoft.com'
    $password = ConvertTo-SecureString -String 'mypassword!'`
                -AsPlainText -Force
}
$outfilepath = $siteurl -replace ':', '_' -replace '/', '_'

try
{
    [Microsoft.SharePoint.Client.ClientContext]$cc = `
      New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)

    [Microsoft.SharePoint.Client.SharePointOnlineCredentials]$spocreds = `
      New-Object `
      Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)

    $cc.Credentials = $spocreds
    $sideLoadingEnabled = `
    [Microsoft.SharePoint.Client.appcatalog]::IsAppSideloadingEnabled($cc);
   
    $cc.ExecuteQuery()
   
    if($sideLoadingEnabled.value -eq $false) {
        Write-Host -ForegroundColor Yellow `
          'SideLoading feature is not enabled on the site:' $siteurl
        $site = $cc.Site;
            $sideLoadingGuid = `
           new-object System.Guid "AE3A1339-61F5-4f8f-81A7-ABD2DA956A7D"
            $site.Features.Add($sideLoadingGuid, $false, `
            [Microsoft.SharePoint.Client.FeatureDefinitionScope]::None);
            $cc.ExecuteQuery();
           Write-Host -ForegroundColor Green `
          'SideLoading feature enabled on site' $siteurl
    }
   
    Else {
        Write-Host -ForegroundColor Green `
          'SideLoading feature is already enabled on site' $siteurl
    }
}

Catch {
    Write-Host -ForegroundColor Red `
      'Error encountered when trying to enable SideLoading feature' `
      $siteurl, ':' $Error[0].ToString();
}

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: