Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

January 20, 2020

Hide Field in New and Edit Forms of SharePoint Online List using Powershell

Hello,

Just tried to hide SharePoint List fields from New and Edit Forms,  wrote a powershell script,

  1. Connect to SharePoint
  2. Load SharePoint List context,
  3. Get Field to hide from forms 
  4. Use functions to hide field from SharePoint forms.

#Load SharePoint CSOM Assemblies
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"
   
#Config Parameters
$SiteURL= "SharePoint Site URL"
$ListName="ListName"
$FieldName = "ColumnName" #Display Name

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred
   
    #Get the web, List and Field objects
    $Web=$Ctx.Web
    $Ctx.Load($Web);
    $Ctx.ExecuteQuery()

    $List=$web.Lists.GetByTitle($ListName)
    $Ctx.Load($List);
    $Ctx.ExecuteQuery()
    

    $Field = $List.Fields.GetByTitle($FieldName)

    $Ctx.Load($Field);
    $Ctx.ExecuteQuery()

    #Hide the column from New & Edit forms
    $Field.SetShowInEditForm($False)
    $Ctx.ExecuteQuery()
    $Field.SetShowInNewForm($False)
    $Ctx.ExecuteQuery()
    $Field.UpdateAndPushChanges($True)
    $Ctx.ExecuteQuery()
      
    Write-host -f Green "List Field hidden Successfully!"
}
Catch {
    write-host -f Red "Error hiding List Column: " $_.Exception.Message
}

May 3, 2016

How to do with SharePoint Library using Powershell

Hi,
 
I am working on PowerShell scripts to automate deployment for one of client,
 
Here is post :: How to do with SharePoint Library using Powershell,


# Create Document Library

# Add SharePoint Snapin to PowerShell          
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {          
  Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

function CreateLibrary
{
    param ($LibName)
    try
    {
        $spListCollection  = $OpenWeb.Lists 
        $spLibrary  = $spListCollection.TryGetList($LibName)

        if($spLibrary -ne $null) {
            Write-Host  -f Yellow "Library $LibraryName already exists in the site"
        }
        else
        {      
            $spListCollection.Add($LibName, "", $listTemplate)
            $spLibrary  = $OpenWeb.GetList($OpenWeb.ServerRelativeUrl+"/"+$LibName)
            Write-Host -f Green "Created Document Library $LibName"
        }
    }
    catch [System.Exception]
    {
 write-host -f red "Not set Likes Setting on " $_.Exception.ToString()
    }
}

$SiteURL = Read-Host -Prompt 'Enter Root Site URL and / @ end'
$OpenWeb = Get-SPWeb $SiteURL
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
CreateLibrary -LibName "Department"

#enable Content Types

$spLibrary.ContentTypesEnabled = $true
$spLibrary.Update()

#Add Content Type

$ctype = "Report Data Source"
$ctToAdd = $rootSite.ContentTypes[$ctype]
$ct = $spLibrary.ContentTypes.Add($ctToAdd)

#Enable Versioning

$spLibrary.EnableVersioning = $true
$spLibrary.EnableMinorVersions = $false
$spLibrary.Update();

# Enable Versioning with Limit

$spLibrary.EnableVersioning = $true
$spLibrary.EnableMinorVersions = $false
$spLibrary.MajorVersionLimit = 3
$spLibrary.Update();

#Order Columns

$FieldOrder = New-Object System.Collections.Specialized.StringCollection
$FieldOrder.Add("ContentType")
$FieldOrder.Add("FileLeafRef")
$FieldOrder.Add("Title")
$FieldOrder.Add("CategoryDescription")
foreach ($ctype in $spLibrary.ContentTypes)
{
      if($ctype.Name -ne "Folder")
      {
           $ctype.FieldLinks.Reorder($FieldOrder);
           $ctype.Update($false);
     }
}

#Enable Moderation and Draft Version

$spLibrary.EnableModeration = $true
$spLibrary.DraftVersionVisibility = 2
$spLibrary.Update();

# Enable Rating Settings

$assembly=[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
$reputationHelper =$assembly.GetType("Microsoft.SharePoint.Portal.ReputationHelper");
$bindings = @("EnableReputation", "NonPublic", "Static");
[System.Reflection.BindingFlags]$flags = [System.Reflection.BindingFlags]::Static -bor [System.Reflection.BindingFlags]::NonPublic;
$methodInfo = $reputationHelper.GetMethod("EnableReputation", $flags);
$values = @($spLibrary, "Likes", $false);
$methodInfo.Invoke($null, @($values));

# Create View

$viewTitle = "Dashboard_User" #Title property
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("DocIcon") > $null
$viewFields.Add("LinkFilename") > $null
$viewFields.Add("CategoryDescription") > $null
$viewFields.Add("BIKeywords") > $null
$viewFields.Add("LikesCount") > $null
$viewQuery = ""
$viewRowLimit = 5
$viewPaged = $true
$viewDefaultView = $false

$newview = $spLibrary.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
 

March 29, 2016

Create SharePoint Web Part Page using PowerShell

Hi,
 
I am working on PowerShell scripts to automate deployment for one of client,
 
Here is post :: Create SharePoint Web Part Page using PowerShell,


# Add SharePoint Snapin to PowerShell          
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {          
  Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}


#function to create web part page in Site Pages
function CreateBlankWebpartPage          
 
{
    Param($WebPartPageName)               
    try
    {    
        $pageLayout = 1  
        $spListCollection  = $OpenWeb.Lists 
        $spLibrary  = $spListCollection.TryGetList("Site Pages")       
        $xml = "" + $spLibrary.ID + "NewWebPageNewWebPartPage" + $pageLayout + "true" + $WebPartPageName + ""
        $OpenWeb.ProcessBatchData($xml)
        foreach($listItem in $spLibrary.Items)
        {
            if($($listitem.URL).Contains("$WebPartPageName" + ".aspx"))
            {
                $myListItem = $listItem
                break;
            }
        }
        $pageUrl =  $($myListItem.URL)
        Write-Host -f Green "New page is Created with Url - $pageUrl"
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}
 
 
$SiteURL = Read-Host -Prompt 'Enter Root Site URL and / @ end'
 
$OpenWeb = Get-SPWeb $SiteURL
 
CreateBlankWebpartPage -WebPartPageName "My Favorites"
CreateBlankWebpartPage -WebPartPageName "Pending Approval"
CreateBlankWebpartPage -WebPartPageName "My Tasks"
CreateBlankWebpartPage -WebPartPageName "My Reports"

SharePoint Left Navigation Using PowerShell

Hi,
 
I am working on PowerShell scripts to automate deployment for one of client,
 
Here is post :: Creating SharePoint Left Navigation using PowerShell,

 
First step will be creating XML File as below,
 
<?xml version="1.0" encoding="utf-8"?>
<Navigation>
  <Headings>
    <Heading Title="Heading1" Url="" Description=""  Permission="domain\UserGroup">
      <NavLink Title="HeadNav1" Url"/>
      <NavLink Title="HeadNav2" Url=""/> 
    </Heading>
    <Heading Title="Heading2" Url="" Description="" Permission="domain\UserGroup" >
      <NavLink Title="HeadNav3" Url=""/>
      <NavLink Title="HeadNav4" Url=""/>
    </Heading>
    <Heading Title="Heading3" Url="" Description="" Permission="domain\UserGroup" >
    </Heading>
  </Headings>
</Navigation>
 

Save the xml file, now time for PowerShell script to read the xml and build the left navigation.
 
PowerShell script will first clear the existing Left Navigation and then Create New left Navigation with
 
  1. Heading
  2. NavLink Under Heading
  3. Description for Heading
  4. URL link for Heading and NavLink
  5. Permission (Target Audience) for Heading

# Add SharePoint Snapin to PowerShell          
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {          
  Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

function LeftNavBar{
 
    $qlNav = $OpenWeb.Navigation.QuickLaunch
 
    #Get XML File
    $xmlFilePath = "$PSScriptRoot\.xml"
    $xmlFile = [xml](Get-Content($xmlFilePath))
    $oldWebUrl = $OpenWeb.Url
    $currentLinks = @()
 
    #Clear Quick Launch links
    $qlNav | ForEach-Object {
        $currentLinks = $currentLinks + $_.Id
    }
    $currentLinks | ForEach-Object {
        $currentNode = $OpenWeb.Navigation.GetNodeById($_)
        write-host -f Yellow "Deleting" $currentNode.Title "and all child navigation links..."
        $qlNav.Delete($currentNode)
    }
 
    #Create Quick Launch Links
    $xmlFile.Navigation.Headings.Heading | ForEach-Object {
        $headingNode = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode($_.Title, $_.Url)
        #$headingNode.Properties["Description"] = $_.Description
        #$headingNode.Update();
        write-host -f Green "Creating Heading:" $_.Title
        $heading = $qlNav.AddAsLast($headingNode)
        $heading.Properties["Audience"] = $_.Permission
        $heading.Update();
      
        $_.NavLink | ForEach-Object {
            if($_.Title -ne $null) {
            $linkNode = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode($_.Title, $_.Url)
            write-host -f Green "Creating Navigation Link:" $_.Title
            $link = $heading.Children.AddAsLast($linkNode)
            }
        }
    }
  
 
    $OpenWeb.Dispose()
}


$SiteURL = Read-Host -Prompt 'Enter Root Site URL and / @ end'
 
$OpenWeb = Get-SPWeb $SiteURL

LeftNavBar

SharePoint Site Column Using Powershell

Hi,
 
I am working on PowerShell scripts to automate deployment for one of client,
 
Here is first post :: Create Site Columns using PowerShell,
 

# Add SharePoint Snapin to PowerShell          
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {          
  Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
 
#Create Multi Select Lookup Column
function CreateCategory
{
    param ($sSiteCollectionUrl)  
    try
    {
        $web = Get-SPWeb $SiteURL
      
        #Configuration
        $lookupFieldWebGuid=$web.ID
        $lookupList = $web.Lists.TryGetList("CategoryMaster")
        $lookupListGuid = $lookupList.ID
        $fieldDisplayName="Category"
        $fieldInternalName="BICategory"
        $sitecolGroup = "OwnColumns"
        $showField = "Title"
        $fieldDescription = "'Defines content for users' search functionality. Select multiple options, if necessary.'"
        $fieldHidden="FALSE"
        $fieldReadonly = "FALSE"
        $fieldMulti = "TRUE"
        $fieldRequired = "TRUE"
        $unlimitedLength = "FALSE"
        #End of configuration
 
        $lookupXMLString = '
        Required="' + $fieldRequired + '" EnforceUniqueValues="FALSE" WebId="' + $lookupFieldWebGuid + '" ShowField="' + $showField + '" UnlimitedLengthInDocumentLibrary="' + $unlimitedLength + '"
        Group="' + $sitecolGroup + '" Mult="' + $fieldMulti + '" Sortable="FALSE" StaticName="' + $fieldInternalName + '" List="' + $lookupListGuid + '"
        Name="' + $fieldInternalName + '" Hidden="' + $fieldHidden + '" ReadOnly="' + $fieldReadonly + '">
' 
        #Create site column from XML string
        $web.Fields.AddFieldAsXml($lookupXMLString)
        Write-Host "The Category site column has been added." -foregroundcolor green
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}
 
#Create Date Column
function CreateDate
{
    param ($sSiteCollectionUrl)  
    try
    {
        $web = Get-SPWeb $SiteURL 
    
        $fieldXML = '
        Name="Report_x0020_Date"
        Description="Report Publish Date"
        DisplayName="Report Date"
        StaticName="Report Date"
        Format="DateOnly"
        Group="OwnColumns"
        Hidden="FALSE"
        Required="FALSE" 
        Sealed="FALSE"
        ShowInDisplayForm="TRUE"
        ShowInEditForm="TRUE"
        ShowInListSettings="TRUE"
        ShowInNewForm="TRUE">
'  
        #Create site column from XML string
        $web.Fields.AddFieldAsXml($fieldXML)  
       
        write-Host "Added the field Report Date to the Site" -foregroundcolor green           
           
        #Disposing SPSite and SPWeb objects
        $web.Dispose()  
        
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}
 
#Create Choice Column
function CreateFrequency
{
    param ($sSiteCollectionUrl,$sFieldDisplayName, $sFieldInternalName, $sFieldType)  
    try
    {
        $spSite = Get-SPSite -Identity $sSiteCollectionUrl
         $spWeb = $spSite.OpenWeb()   
 
    
        #We check the field type is not null
        if($sFieldType -ne '')
        {
            $spWeb.Fields.Add($sFieldInternalName,$sFieldType,$false)
            $spChoiceField=$spWeb.Fields.GetField($sFieldInternalName)
            write-Host "Added the field Frequency to the Site" -foregroundcolor green
            $spChoiceField.Group="OwnColumns"
            $spChoiceField.Choices.Add("Weekly")
            $spChoiceField.Choices.Add("Months")
            $spChoiceField.Choices.Add("Annually")
            $spChoiceField.Choices.Add("Adhoc")
            $spChoiceField.Title=$sFieldDisplayName
            $spChoiceField.DefaultValue=""
            $spChoiceField.Required = "TRUE"
            $spChoiceField.FillInChoice=$false
            $spChoiceField.Update()
        }
                     
        #Disposing SPSite and SPWeb objects
        $spWeb.Dispose()
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}

#Create User Column
function CreateOwner
{
    param ($sSiteCollectionUrl)  
    try
    {
        $web = Get-SPWeb $SiteURL 
    
        $fieldXML = '
        Name="BIOwner"
        Description="Main business owner of published content."
        DisplayName="Owner"
        List="UserInfo"
        ShowField="ImnName"
        UserSelectionMode="PeopleOnly"
        UserSelectionScope="0"
        StaticName="BIOwner"
        Group="OwnColumns"
        Hidden="FALSE"
        Required="TRUE"
        Sealed="FALSE"
        ShowInDisplayForm="TRUE"
        ShowInEditForm="TRUE"
        ShowInListSettings="TRUE"
        ShowInNewForm="TRUE">
' 
        #Create site column from XML string
        $web.Fields.AddFieldAsXml($fieldXML)  
       
        write-Host "Added the field Owner to the Site" -foregroundcolor green           
           
        #Disposing SPSite and SPWeb objects
        $web.Dispose()  
        
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}

# get Site URL

$SiteURL = Read-Host -Prompt 'Enter Root Site URL and / @ end'
$rootWeb = Get-SPWeb $SiteURL
CreateCategory -sSiteCollectionUrl $SiteURL
CreateDate -sSiteCollectionUrl $SiteURL
CreateOwner -sSiteCollectionUrl $SiteURL
CreateFrequency -sSiteCollectionUrl $SiteURL -sFieldDisplayName "Frequency"  -sFieldInternalName "Frequency" -sFieldType "Choice"

Highlighted in blue color can be change as per your requirement.

Thanks

October 31, 2013

Convert text files between character sets

Hello Friends,

I was trying to upload the Bulk data from Flat text file to SQL Table, but it was required to have character sets as ANCII.. but when we manually change some data in text file it is keeping first column first value as null..

So after spending time on it, I found that file has to be converted to ANCII format..

Here is the commands for same..

On Windows with Powershell:

PS C:\> gc -en utf8 'in.txt' | Out-File -en ascii 'out.txt'

(No ISO-8859-15 support though; it says that supported charsets are unicode, utf7, utf8, utf32, ascii, bigendianunicode, default, and oem.)

CsCvt - Kalytta's Character Set Converter (http://www.cscvt.de) is another great command line based conversion tool for Windows.


Enjoy...