SchemaVersion (Set/Get)

Stores a System.Version in the SPWeb property bag for schema versioning

[Updated : 2012/02/03]
Previously, the code snippet used SPWeb.Properties[key]... turns out, there are bugs when trying to remove the property. This may not be an issue for 99% of the cases, but I don't want to find myself in that 1%, and end up spending a lot of time figuring out why. So new with SP2010, the SPWeb object now has additional methods for GetProperty(name), AddProperty, SetProperty(name, value), and DeleteProperty (name).
Language:
PowerShell
Keywords:
SharePoint
Code Snippet

### SCHEMA VERSION ###

Function GetSchemaVersion( [Microsoft.SharePoint.SPWeb]$tWeb
                         , [System.String]$tKey ) {

    if ($tWeb.GetProperty($tKey) -eq $null) {
        
# Property doesn't exist? Sounds like version 0.0.0.0 #

        $tSchemaVersion_Current = New-Object System.Version(0, 0, 0, 0)

    } else {
        
# Simply get the current value #

        $tSchemaVersion_Current = $tWeb.GetProperty($tKey)

    }

    return $tSchemaVersion_Current

}

Function SetSchemaVersion( [Microsoft.SharePoint.SPWeb]$tWeb

                         , [System.String]$tKey

                         , [System.Version]$tVersion

                         ) {

    if ($tWeb.GetProperty($tKey) -eq $null) {
        
# Property does not exist... yet #

        $tWeb.AddProperty($tKey, $tVersion.ToString()) | Out-Null

    } else {
        
# Property already exists # 
        
if ($tVersion -eq $null) {
            
# Replacing with NULL? just delete it #

            $tWeb.DeleteProperty($tKey)

        else {
            
# update with new value #

            $tWeb.SetProperty($tKey, $tVersion)

        }

    }

    $tWeb.Update()

}

Example

if ((GetSchema $tWeb "MyCustomSchema") -eq (New-Object System.Version(0, 0, 0, 0))) {

  # Upgrade to 1.0.0.0 #

}

if ((GetSchema $tWeb "MyCustomSchema") -eq (New-Object System.Version(1, 0, 0, 0))) {

  # Upgrade to 1.1.0.0 #

}


Created 2011-10-13
comments powered by Disqus
Login