Ensure_SiteColumn

Language:
PowerShell
Keywords:
SharePoint
Code Snippet

## Ensure_s that a Site Column exists.. if it does, do nothing; if it does not, create it based on parameters
Function Ensure_SiteColumn( [Microsoft.SharePoint.SPWeb]$tWeb
                          , $tFieldName
                          , [Microsoft.SharePoint.SPFieldType]$tFieldType
                          ) {

    if ($tFieldType -eq [Microsoft.SharePoint.SPFieldType]::Lookup) {
        throw New-Object System.NotImplementedException([System.String]::Format("Ensure_SiteColumn does not support Lookup field types"))
    }

    if (!$tWeb.Fields[$tFieldName]) {

        Write-Output([System.String]::Format("Column [{1}] : Adding to Web [{0}]", $tWeb.Url, $tFieldName))

        # special handling of Calculated field
        if ($tFieldType -eq [Microsoft.SharePoint.SPFieldType]::Calculated) {
            $tField = $tWeb.Fields.Add($tFieldName, $tFieldType, $false)
        } else {
            $tField = $tWeb.Fields.CreateNewField([System.Enum]::GetName([Microsoft.SharePoint.SPFieldType], $tFieldType), $tFieldName)
            $tWeb.Fields.Add($tField) | Out-Null
        }

        $tWeb.Update()
    }
} # Function Ensure_SiteColumn(...)

Example

Code:

Ensure_SiteColumn  $tSite.RootWeb  "MyFieldName 1" ([Microsoft.SharePoint.SPFieldType]::Note)
Ensure_SiteColumn  $tSite.RootWeb  "MyFieldName 2" ([Microsoft.SharePoint.SPFieldType]::DateTime)
Ensure_SiteColumn  $tSite.RootWeb  "MyFieldName 3" ([Microsoft.SharePoint.SPFieldType]::Text)
 

Output:

Column [MyFieldName1] : Adding to Web [http://SPServer/sites/test]
Column [MyFieldName2] : Adding to Web [http://SPServer/sites/test]
Column [MyFieldName3] : Adding to Web [http://SPServer/sites/test]
 ​

Created 2011-10-13
comments powered by Disqus
Login