MOSS MVP

Monday, October 19, 2009

SharePoint 2010: STSADM and PowerShell

The information in this article is based on BETA 1 of SharePoint 2010 - there will likely be differences with the RTM release.

Finally, the NDA is lifted and we can openly talk about SharePoint 2010! There's so many cool things to talk about it's hard to decide where to begin, but as the focus of my blog has generally been on STSADM then I suppose that's a good place to start. The first thing we should do is load the new SharePoint 4.0 Management Console which can be found under the Administrative Tools section of the start menu:

 image

This new console window is actually just a PowerShell console which pre-loads the SharePoint PowerShell Snap-in.  You can see that by looking at the target for the shortcut:

C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoExit  " & ' C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\\sharepoint.ps1 ' "

If you look at the SharePoint.ps1 file you'll see the following (trimmed for brevity):

Add-PsSnapin Microsoft.SharePoint.PowerShell
Set-location $home

# SIG # Begin signature block
#
MIIXUAYJKoZIhvcNAQcCoIIXQTCCFz0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
#
gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
...
# lS3atVtgARZMVlgfulkx701xMUWQMbBRejnOVVox8LpDQzsQvK2vnezr5lsCN/hx
#
pa5c4o4RVsqRkYZ5nZeglcFoZOiB3k+r59+Qh/UGRpvh/abyPGHTOP59ctWtokjB
#
dMHfVxsRLBRCQzkU6/h/hU/5pzA=
#
SIG # End signature block

From this you can see that you can easily load up any PowerShell console app (either the native PowerShell console or a any other editor such as PowerGUI or the PowerShell ISE) and simply run the Add-PsSnapin cmdlet to load the new SharePoint 2010 cmdlets as shown above. I'll cover the PowerShell stuff in bit but first lets take a look at the STSADM changes. I did a simple stsadm -help command and saved that to a file in both my 2007 and 2010 environment and then compared those files. Here's what I found:

  • The following STSADM commands no longer exist:
    • associatewebapp
    • createcmsmigrationprofile
    • createssp
    • deletecmsmigrationprofile
    • deletessp
    • deletessptimerjob
    • editcmsmigrationprofile
    • editssp
    • enablecmsurlredirect
    • enumssp
    • enumssptimerjobs
    • grantiis7permission
    • listqueryprocessoroptions
    • mysite
    • preupgradecheck
    • restoressp
    • runcmsmigrationprofile
    • setdefaultssp
    • setqueryprocessoroptions
    • setsharedwebserviceauthn
    • setsspport
    • trimauditlog
  • The following STSADM commands have been added:
    • add-adsdefaultapplication
    • add-ecsblockedexcelfiletype
    • monitordb
    • patchpostaction
    • remove-adsdefaultapplication
    • remove-ecsblockedexcelfiletype

From the list above you can see that the bulk of the items removed have to do with the SSP and CMS migration features which were part of the 2007 product but have been removed from the 2010 product (2010 has a whole new services architecture which is really cool, but outside the scope of this article - stay tuned! - 2010 also does not support upgrading from Microsoft CMS, you must upgrade to SharePoint 2007 and then SharePoint 2010).

Also note that very few new commands have been added - in fact I was surprised to see that any were added - why? Because PowerShell is what we should all be using - STSADM is dead - just don't use it, forget that these new commands have been added as there are PowerShell equivalents (I wouldn't be surprised if they get pulled come RTM). That said, at beta there may be some stuff that still only exists with STSADM but expect that not to be the case going forward.

So now that we have that out of the way, lets talk about some PowerShell (as of this post I'm officially done creating STSADM extensions - at least for 2010, I may still have need for some new stuff with the 2007 product). In your new SharePoint 4.0 Management Console type the following command: gcm -pssnapin microsoft.sharepoint.powershell | select Name, Definition | fl > .\sp2010cmdlets.txt

Take a look at the file you just generated, you now have a listing of the 492 new PowerShell cmdlets that ship with SharePoint 2010. For brevity sake I won't show the syntax but here's a listing of all the new cmdlets that are available:

Add-SPClaimMapping
Add-SPFeatureSetMember
Add-SPInfoPathUserAgent
Add-SPProfileServiceApplicationTenant
Add-SPServiceApplicationProxyGroupMember
Add-SPSolution
Add-SPUserSolution
Backup-SPConfigurationDatabase
Backup-SPFarm
Backup-SPSite
Check-SPContentDatabase
Clear-SPBusinessDataCatalogPartitionData
Clear-SPLogLevel
Clear-SPMetadataWebServicePartitionData
Clear-SPSecureStoreCredentialMapping
Connect-SPConfigurationDatabase
Copy-SPBusinessDataCatalogAclToChildren
Disable-SPBusinessDataCatalogEntity
Disable-SPFeature
Disable-SPInfoPathFormTemplate
Disable-SPSessionStateService
Disable-SPSingleSignOn
Disable-SPTimerJob
Disable-SPWebApplicationHttpThrottling
Disconnect-SPConfigurationDatabase
Dismount-SPContentDatabase
Dismount-SPStateServiceDatabase
Enable-SPBusinessDataCatalogEntity
Enable-SPFeature
Enable-SPInfoPathFormTemplate
Enable-SPSessionStateService
Enable-SPTimerJob
Enable-SPWebApplicationHttpThrottling
Export-SPBusinessDataCatalogModel
Export-SPBusinessDataCatalogPartitionData
Export-SPEnterpriseSearchTopology
Export-SPInfoPathAdministrationFiles
Export-SPMetadataWebServicePartitionData
Export-SPProfileServiceApplicationTenant
Export-SPSiteSubscriptionSettings
Export-SPWeb
Get-SPAccessServiceApplication
Get-SPAlternateURL
Get-SPBackupHistory
Get-SPBrowserCustomerExperienceImprovementProgram
Get-SPBusinessDataCatalogMetadataObject
Get-SPBusinessDataCatalogThrottleConfig
Get-SPCertificate
Get-SPCertificateStore
Get-SPClaimProviderManager
Get-SPContentDatabase
Get-SPContentDeploymentJob
Get-SPContentDeploymentPath
Get-SPCustomLayoutsPage
Get-SPDatabase
Get-SPDataConnectionFile
Get-SPDataConnectionFileDependent
Get-SPDesignerSettings
Get-SPDiagnosticConfig
Get-SPDiagnosticsProvider
Get-SPEdiscoveryHubSearchScope
Get-SPediscoveryHubSite
Get-SPEnterpriseSearchAdministrationComponent
Get-SPEnterpriseSearchCrawlComponent
Get-SPEnterpriseSearchCrawlContentSource
Get-SPEnterpriseSearchCrawlCustomConnector
Get-SPEnterpriseSearchCrawlDatabase
Get-SPEnterpriseSearchCrawlExtension
Get-SPEnterpriseSearchCrawlMapping
Get-SPEnterpriseSearchCrawlRule
Get-SPEnterpriseSearchCrawlTopology
Get-SPEnterpriseSearchExtendedClickThroughExtractorJobDefinition
Get-SPEnterpriseSearchExtendedConnectorProperty
Get-SPEnterpriseSearchExtendedQueryProperty
Get-SPEnterpriseSearchIndexPartition
Get-SPEnterpriseSearchLanguageResourcePhrase
Get-SPEnterpriseSearchManagerService
Get-SPEnterpriseSearchManagerServiceInstance
Get-SPEnterpriseSearchManagerServiceProxy
Get-SPEnterpriseSearchMetadataCategory
Get-SPEnterpriseSearchMetadataCrawledProperty
Get-SPEnterpriseSearchMetadataManagedProperty
Get-SPEnterpriseSearchMetadataMapping
Get-SPEnterpriseSearchPropertyDatabase
Get-SPEnterpriseSearchQueryAuthority
Get-SPEnterpriseSearchQueryComponent
Get-SPEnterpriseSearchQueryDemoted
Get-SPEnterpriseSearchQueryKeyword
Get-SPEnterpriseSearchQueryScope
Get-SPEnterpriseSearchQueryScopeRule
Get-SPEnterpriseSearchQuerySuggestionCandidates
Get-SPEnterpriseSearchQueryTopology
Get-SPEnterpriseSearchRankingModel
Get-SPEnterpriseSearchSecurityTrimmer
Get-SPEnterpriseSearchService
Get-SPEnterpriseSearchServiceApplication
Get-SPEnterpriseSearchServiceApplicationProxy
Get-SPEnterpriseSearchServiceInstance
Get-SPEnterpriseSearchSiteHitRule
Get-SPExcelBlockedFileType
Get-SPExcelDataConnectionLibrary
Get-SPExcelDataProvider
Get-SPExcelFileLocation
Get-SPExcelServiceApplication
Get-SPExcelUserDefinedFunction
Get-SPFarm
Get-SPFarmConfig
Get-SPFeature
Get-SPFeatureSet
Get-SPHelpCollection
Get-SPIdentityProvider
Get-SPIisWebServiceApplicationPool
Get-SPIisWebServiceSettings
Get-SPInfoPathFormsService
Get-SPInfoPathFormTemplate
Get-SPInfoPathUserAgent
Get-SPInfoPathWebServiceProxy
Get-SPLogEvent
Get-SPLogLevel
Get-SPManagedAccount
Get-SPManagedPath
Get-SPMetadataServiceApplication
Get-SPMetadataServiceApplicationProxy
Get-SPMobileMessagingAccount
Get-SPObjectSecurity
Get-SPParentFarmTrust
Get-SPProcessAccount
Get-SPProduct
Get-SPSearchService
Get-SPSearchServiceInstance
Get-SPSecureStoreApplication
Get-SPSecurityTokenService
Get-SPServer
Get-SPServiceApplication
Get-SPServiceApplicationProxy
Get-SPServiceApplicationProxyGroup
Get-SPServiceContext
Get-SPServiceEndpoint
Get-SPServiceInstance
Get-SPSessionStateService
Get-SPSite
Get-SPSiteAdministration
Get-SPSiteSubscription
Get-SPSiteSubscriptionConfig
Get-SPSiteSubscriptionMetadataConfig
Get-SPSolution
Get-SPStateServiceApplication
Get-SPStateServiceApplicationProxy
Get-SPStateServiceDatabase
Get-SPTaxonomySession
Get-SPTimerJob
Get-SPTopologyWebServiceApplication
Get-SPTopologyWebServiceProxy
Get-SPUsageApplication
Get-SPUsageDefinition
Get-SPUsageService
Get-SPUser
Get-SPUserSolution
Get-SPVisioExternalData
Get-SPVisioPerformance
Get-SPVisioSafeDataProvider
Get-SPVisioServiceApplication
Get-SPVisioServiceApplicationProxy
Get-SPWeb
Get-SPWebAnalyticsServiceApplication
Get-SPWebApplication
Get-SPWebApplicationHttpThrottlingMonitors
Get-SPWebPartPack
Get-SPWebTemplate
Get-SPWorkflowConfig
Grant-SPBusinessDataCatalogMetadataObject
Grant-SPServiceApplication
Import-SPBusinessDataCatalogModel
Import-SPBusinessDataCatalogPartitionData
Import-SPEnterpriseSearchTopology
Import-SPInfoPathAdministrationFiles
Import-SPMetadataWebServicePartitionData
Import-SPProfileServiceApplicationTenant
Import-SPSiteSubscriptionSettings
Import-SPWeb
Initialize-SPContentDatabase
Initialize-SPResourceSecurity
Initialize-SPStateServiceDatabase
Install-SPApplicationContent
Install-SPDataConnectionFile
Install-SPFeature
Install-SPHelpCollection
Install-SPInfoPathFormTemplate
Install-SPSolution
Install-SPUserSolution
Install-SPWebPartPack
Install-SPWebTemplate
Merge-SPLogFile
Mount-SPContentDatabase
Mount-SPStateServiceDatabase
Move-SPBlobStorageLocation
Move-SPUser
New-SPAccessServiceApplication
New-SPAlternateURL
New-SPBusinessDataCatalogServiceApplication
New-SPBusinessDataCatalogServiceApplicationProxy
New-SPCentralAdministration
New-SPCertificate
New-SPClaimMapping
New-SPClaimsObject
New-SPClaimsPrincipal
New-SPConfigurationDatabase
New-SPContentDatabase
New-SPContentDeploymentJob
New-SPContentDeploymentPath
New-SPEnterpriseSearchCrawlComponent
New-SPEnterpriseSearchCrawlContentSource
New-SPEnterpriseSearchCrawlCustomConnector
New-SPEnterpriseSearchCrawlDatabase
New-SPEnterpriseSearchCrawlExtension
New-SPEnterpriseSearchCrawlMapping
New-SPEnterpriseSearchCrawlRule
New-SPEnterpriseSearchCrawlTopology
New-SPEnterpriseSearchLanguageResourcePhrase
New-SPEnterpriseSearchMetadataCategory
New-SPEnterpriseSearchMetadataCrawledProperty
New-SPEnterpriseSearchMetadataManagedProperty
New-SPEnterpriseSearchMetadataMapping
New-SPEnterpriseSearchPropertyDatabase
New-SPEnterpriseSearchQueryAuthority
New-SPEnterpriseSearchQueryComponent
New-SPEnterpriseSearchQueryDemoted
New-SPEnterpriseSearchQueryKeyword
New-SPEnterpriseSearchQueryScope
New-SPEnterpriseSearchQueryScopeRule
New-SPEnterpriseSearchQueryTopology
New-SPEnterpriseSearchRankingModel
New-SPEnterpriseSearchSecurityTrimmer
New-SPEnterpriseSearchServiceApplication
New-SPEnterpriseSearchServiceApplicationProxy
New-SPEnterpriseSearchSiteHitRule
New-SPExcelBlockedFileType
New-SPExcelDataConnectionLibrary
New-SPExcelDataProvider
New-SPExcelFileLocation
New-SPExcelServiceApplication
New-SPExcelUserDefinedFunction
New-SPFeatureSet
New-SPIdentityProvider
New-SPIisWebServiceApplicationPool
New-SPLogFile

New-SPManagedAccount
New-SPManagedPath
New-SPMetadataServiceApplication
New-SPMetadataServiceApplicationProxy
New-SPObaSolutionPackage
New-SPParentFarmTrust
New-SPProfileServiceApplication
New-SPProfileServiceApplicationProxy
New-SPSecureStoreApplication
New-SPSecureStoreApplicationField
New-SPSecureStoreServiceApplication
New-SPSecureStoreServiceApplicationProxy
New-SPSecureStoreTargetApplication
New-SPServiceApplicationProxyGroup
New-SPSite
New-SPSiteSubscription
New-SPStateServiceApplication
New-SPStateServiceApplicationProxy
New-SPStateServiceDatabase
New-SPSubscriptionSettingsServiceApplication
New-SPSubscriptionSettingsServiceApplicationProxy
New-SPUsageApplication
New-SPUsageLogFile
New-SPUser
New-SPVisioSafeDataProvider
New-SPVisioServiceApplication
New-SPVisioServiceApplicationProxy
New-SPWeb
New-SPWebAnalyticsServiceApplication
New-SPWebAnalyticsServiceApplicationProxy
New-SPWebApplication
New-SPWebApplicationExtension
New-SPWordConversionServiceApplication
New-SPWordConversionServiceApplicationProxy
Publish-SPServiceApplication
Receive-SPSharedServiceApplicationInfo
Remove-SPAlternateURL
Remove-SPBusinessDataCatalogModel
Remove-SPBusinessDataCatalogPartition
Remove-SPBusinessDataCatalogThrottleConfig
Remove-SPCertificate
Remove-SPClaimMapping
Remove-SPConfigurationDatabase
Remove-SPContentDatabase
Remove-SPContentDeploymentJob
Remove-SPContentDeploymentPath
Remove-SPEnterpriseSearchCrawlComponent
Remove-SPEnterpriseSearchCrawlContentSource
Remove-SPEnterpriseSearchCrawlCustomConnector
Remove-SPEnterpriseSearchCrawlDatabase
Remove-SPEnterpriseSearchCrawlExtension
Remove-SPEnterpriseSearchCrawlMapping
Remove-SPEnterpriseSearchCrawlRule
Remove-SPEnterpriseSearchCrawlTopology
Remove-SPEnterpriseSearchLanguageResourcePhrase
Remove-SPEnterpriseSearchMetadataCategory
Remove-SPEnterpriseSearchMetadataManagedProperty
Remove-SPEnterpriseSearchMetadataMapping
Remove-SPEnterpriseSearchPropertyDatabase
Remove-SPEnterpriseSearchQueryAuthority
Remove-SPEnterpriseSearchQueryComponent
Remove-SPEnterpriseSearchQueryDemoted
Remove-SPEnterpriseSearchQueryKeyword
Remove-SPEnterpriseSearchQueryScope
Remove-SPEnterpriseSearchQueryScopeRule
Remove-SPEnterpriseSearchQueryTopology
Remove-SPEnterpriseSearchRankingModel
Remove-SPEnterpriseSearchSecurityTrimmer
Remove-SPEnterpriseSearchServiceApplication
Remove-SPEnterpriseSearchServiceApplicationProxy
Remove-SPEnterpriseSearchSiteHitRule
Remove-SPExcelBlockedFileType
Remove-SPExcelDataConnectionLibrary
Remove-SPExcelDataProvider
Remove-SPExcelFileLocation
Remove-SPExcelUserDefinedFunction
Remove-SPFeatureSet
Remove-SPFeatureSetMember
Remove-SPIdentityProvider
Remove-SPIisWebServiceApplicationPool
Remove-SPInfoPathUserAgent
Remove-SPManagedAccount
Remove-SPManagedPath
Remove-SPParentFarmTrust
Remove-SPProfileServiceApplicationTenant
Remove-SPSecureStoreApplication
Remove-SPServiceApplication
Remove-SPServiceApplicationProxy
Remove-SPServiceApplicationProxyGroup
Remove-SPServiceApplicationProxyGroupMember
Remove-SPSite
Remove-SPSiteSubscription
Remove-SPSiteSubscriptionMetadataConfig
Remove-SPSiteSubscriptionSettings
Remove-SPSolution
Remove-SPSolutionDeploymentLock
Remove-SPStateServiceDatabase
Remove-SPUsageApplication
Remove-SPUser
Remove-SPUserSolution
Remove-SPVisioSafeDataProvider
Remove-SPVisioServiceApplication
Remove-SPVisioServiceApplicationProxy
Remove-SPWeb
Remove-SPWebApplication
Rename-SPServer
Restart-SPEnterpriseSearchQueryComponent
Restore-SPEnterpriseSearchServiceApplication
Restore-SPFarm
Restore-SPSite
Resume-SPStateServiceDatabase
Revoke-SPBusinessDataCatalogMetadataObject
Revoke-SPServiceApplication
Set-SPAccessServiceApplication
Set-SPAlternateURL
Set-SPBrowserCustomerExperienceImprovementProgram
Set-SPBusinessDataCatalogMetadataObject
Set-SPBusinessDataCatalogServiceApplication
Set-SPBusinessDataCatalogThrottleConfig
Set-SPCentralAdministration
Set-SPContentDatabase
Set-SPContentDeploymentJob
Set-SPContentDeploymentPath
Set-SPCustomLayoutsPage
Set-SPDataConnectionFile
Set-SPDesignerSettings
Set-SPDiagnosticConfig
Set-SPDiagnosticsProvider
Set-SPediscoveryHub
Set-SPEnterpriseSearchAdministrationComponent
Set-SPEnterpriseSearchCrawlContentSource
Set-SPEnterpriseSearchCrawlDatabase
Set-SPEnterpriseSearchCrawlRule
Set-SPEnterpriseSearchCrawlTopology
Set-SPEnterpriseSearchExtendedConnectorProperty
Set-SPEnterpriseSearchExtendedQueryProperty
Set-SPEnterpriseSearchIndexPartition
Set-SPEnterpriseSearchMetadataCategory
Set-SPEnterpriseSearchMetadataCrawledProperty
Set-SPEnterpriseSearchMetadataManagedProperty
Set-SPEnterpriseSearchMetadataMapping
Set-SPEnterpriseSearchPropertyDatabase
Set-SPEnterpriseSearchQueryAuthority
Set-SPEnterpriseSearchQueryComponent
Set-SPEnterpriseSearchQueryKeyword
Set-SPEnterpriseSearchQueryScope
Set-SPEnterpriseSearchQueryScopeRule
Set-SPEnterpriseSearchQueryTopology
Set-SPEnterpriseSearchRankingModel
Set-SPEnterpriseSearchService
Set-SPEnterpriseSearchServiceApplication
Set-SPEnterpriseSearchServiceApplicationProxy
Set-SPEnterpriseSearchServiceInstance
Set-SPExcelDataConnectionLibrary
Set-SPExcelDataProvider
Set-SPExcelFileLocation
Set-SPExcelServiceApplication
Set-SPExcelUserDefinedFunction
Set-SPFarmConfig
Set-SPIdentityProvider
Set-SPIisWebServiceApplicationPool
Set-SPIisWebServiceSettings
Set-SPInfoPathFormsService
Set-SPInfoPathFormTemplate
Set-SPInfoPathWebServiceProxy
Set-SPLogLevel
Set-SPManagedAccount
Set-SPMetadataServiceApplication
Set-SPMetadataServiceApplicationProxy
Set-SPMobileMessagingAccount
Set-SPParentFarmTrust
Set-SPPassPhrase
Set-SPProfileServiceApplication
Set-SPProfileServiceApplicationProxy
Set-SPProfileServiceApplicationTenant
Set-SPSearchService
Set-SPSearchServiceInstance
Set-SPSecureStoreApplication
Set-SPSecureStoreServiceApplication
Set-SPServiceApplication
Set-SPServiceEndpoint
Set-SPSessionStateService
Set-SPSite
Set-SPSiteAdministration
Set-SPSiteSubscriptionConfig
Set-SPSiteSubscriptionMetadataConfig
Set-SPStateServiceApplication
Set-SPStateServiceApplicationProxy
Set-SPStateServiceDatabase
Set-SPSubscriptionSettingsServiceApplication
Set-SPTimerJob
Set-SPTopologyWebServiceApplication
Set-SPTopologyWebServiceProxy
Set-SPUsageApplication
Set-SPUsageDefinition
Set-SPUsageService
Set-SPUser
Set-SPVisioExternalData
Set-SPVisioPerformance
Set-SPVisioSafeDataProvider
Set-SPVisioServiceApplication
Set-SPWeb
Set-SPWebAnalyticsServiceApplication
Set-SPWebApplication
Set-SPWebApplicationHttpThrottlingMonitor
Set-SPWebApplicationSiginRedirectUrl
Set-SPWebTemplate
Set-SPWordConversionServiceApplication
Set-SPWorkflowConfig
Start-SPAdminJob
Start-SPAssignment
Start-SPContentDeploymentJob
Start-SPEnterpriseSearchManagerServiceInstance
Start-SPEnterpriseSearchServiceInstance
Start-SPInfoPathFormTemplate
Start-SPServiceInstance
Start-SPTimerJob
Stop-SPAssignment
Stop-SPEnterpriseSearchManagerServiceInstance
Stop-SPEnterpriseSearchServiceInstance
Stop-SPInfoPathFormTemplate
Stop-SPServiceInstance
Suspend-SPStateServiceDatabase
Test-SPInfoPathFormTemplate
Uninstall-SPDataConnectionFile
Uninstall-SPFeature
Uninstall-SPHelpCollection
Uninstall-SPInfoPathFormTemplate
Uninstall-SPSolution
Uninstall-SPUserSolution
Uninstall-SPWebPartPack
Uninstall-SPWebTemplate
Unpublish-SPServiceApplication
Update-SPFarmEncryptionKey
Update-SPInfoPathFormTemplate
Update-SPInfoPathUrl
Update-SPSecureStoreApplicationServerKey
Update-SPSecureStoreCredentialMapping
Update-SPSecureStoreGroupCredentialMapping
Update-SPSecureStoreMasterKey
Update-SPSolution
Update-SPUserProfilePhotoStore
Update-SPUserSolution
Upgrade-SPContentDatabase
Upgrade-SPEnterpriseSearchServiceApplication
Upgrade-SPSingleSignOnDatabase

If you're going to be working with the SharePoint PowerShell cmdlets then there are two cmdlets that you should learn before any others: Start-SPAssignment and Stop-SPAssignment. If you've used the custom cmdlets that I created for the 2007 product and read my articles around them then you should be familiar with the core issue that I was trying to solve with some of them - the handling of disposable objects. When you use a cmdlet such as Get-SPSite you are returning back a disposable object, an object that implements the IDisposable interface in order to release handles to unmanaged resources which cause memory leaks if not released. I chose to solve the issue by simply not returning back disposable objects and instead using a proxy object. Microsoft chose a different route.

If you look closely at the definitions of the cmdlets from the text file you created above you should notice that every cmdlet has an -AssignmentCollection parameter which takes in an SPAssignmentCollection object type. The purpose of this collection is to store disposable objects so that they can be disposed when your operations complete. You create a new assignment collection by calling the Start-SPAssignment cmdlet. You can then optionally pass the created assignment collection object into your subsequent calls by either using the pipeline or directly setting the parameter (otherwise the global collection will be used). Lets look at the help for the cmdlet to understand this better:

PS C:\> help start-spassignment

NAME
    Start-SPAssignment

SYNOPSIS
    Initiates a new assignment store.


SYNTAX
    Start-SPAssignment [-Global <SwitchParameter>] [<CommonParameters>]


DETAILED DESCRIPTION
    Use this command to properly dispose of objects used with variable assignme
    nts.
    Using SPWeb, SPSite, or SPSiteAdminsitration objects can use large amounts
    of memory and using these objects, or lists of these objects, in PowerShell
     scripts requires proper memory management. By default, all Get commands di
    spose of these objects immediately after the pipeline finishes, but using S
    PAssignment, you can assign the list of objects to a variable and dispose o
    f the objects after they are no longer needed. You can also ensure that the
     objects will remain as long as you need them, even throughout multiple ite
    rations of commands.
    There are three levels of assignment:
    * No assignment - The object is not assigned to a variable and is disposed
      of after each iteration of the command.
    * Simple assignment - All objects are assigned to the global assignment sto
      re. This is done by using the Global parameter. When using this level, al
      l objects are assigned to a global store and are disposed of when the Sto
      p-SPAssignment command is called.
    * Advanced assignment - Objects are assigned to named stores for disposal.
      You can dispose of objects by using the -Identity parameter with the Stop
      -SPAssignment command.
    Regardless of the level used, all objects are disposed of when the PowerShe
    ll runspace is closed.


RELATED LINKS

REMARKS
    To see the examples, type: "get-help Start-SPAssignment -examples".
    For more information, type: "get-help Start-SPAssignment -detailed".
    For technical information, type: "get-help Start-SPAssignment -full".

As you can see from the help text there are three levels of assignment: No assignment (dispose immediately), simple assignment (use a global store), and advanced assignment (use a named store). Let's take a look at the syntax (note that in Beta 1 most of the help files do not match the actual syntax so I rarely rely on the help text to tell me what the cmdlet syntax is - instead I use the Get-Command (gcm) cmdlet):

PS C:\> gcm Start-SPAssignment -syntax
Start-SPAssignment [-Global] [-AssignmentCollection <SPAssignmentCollection>] [
-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningAction <ActionPre
ference>] [-ErrorVariable <String>] [-WarningVariable <String>] [-OutVariable <
String>] [-OutBuffer <Int32>]

If you specify the -Global switch then you do not need to store the returned object or pass it into your cmdlets - internally this cmdlet stores the object in a static variable which is used by all subsequent calls - this is the "simple assignment" method mentioned in the help text. If you do not specify the -Global switch then you must store the returned object in a variable and pass that variable into all subsequent cmdlet calls that return disposable objects and provide the variable to the Stop-SPAssignment cmdlet with the same variable via the -SemiGlobal parameter (this may change to Identity for the RTM) - this is the "advanced assignment" mentioned in the help text. So what about the "no assignment" option? The "no assignment" option is basically when you do not create an SPAssignmentCollection using the Start-SPAssignment cmdlet which causes cmdlets that return disposable objects to dispose of the object immediately after the call to WriteObject. So as long as the pipeline is active the object remains un-disposed but at the end of the pipeline the object is disposed.

So now we'll look at the syntax for the Stop-SPAssignment cmdlet:

PS C:\> gcm Stop-SPAssignment -syntax
Stop-SPAssignment [[-SemiGlobal] <SPAssignmentCollection>] [-Global] [-Assignme
ntCollection <SPAssignmentCollection>] [-Verbose] [-Debug] [-ErrorAction <Actio
nPreference>] [-WarningAction <ActionPreference>] [-ErrorVariable <String>] [-W
arningVariable <String>] [-OutVariable <String>] [-OutBuffer <Int32>]

As you can see this is pretty straightforward, if you used the -Global switch for the Start-SPAssignment cmdlet then you'll use it here, otherwise you would use the -SemiGlobal parameter and pass the variable you created earlier.

Here's a complete example demonstrating both approaches:

#Use of the Global assignment variable
Start-SPAssignment -Global
$site = Get-SPSite "http://portal"
$site | fl
Stop-SPAssignment -Global

#Use of a semi-global, or named variable
$gc = Start-SPAssignment
$site = $gc | Get-SPSite "http://mysites"
$site | fl
$gc | Stop-SPAssignment

For the second example you can see that I'm passing in the variable using the pipeline rather than setting the parameter directly (for both the Get-SPSite cmdlet and the Stop-SPAssignment cmdlet). I could have easily set the parameter names directly but this just results in less code.

So one thing you should be asking is when do I need to do this - every cmdlet takes an SPAssignmentCollection so does that mean that I always have to deal with this stuff? My simple answer is, no, you don't have to do this all the time, only when you know you are working with disposable objects. The problem is that most people don't know when they are working with disposable objects, and in many cases what disposable objects are. So my first best practice recommendation for SharePoint 2010 will be to always use the simple assignment approach (use the global assignment variable) unless you specifically know to do otherwise. So wrap all your scripts with a call to Start-SPAssignment and Stop-SPAssignment. If you have functions that do not return values then wrap those using the advanced approach as shown below:

function Set-SomethingInteresting([string]$siteUrl)
{
    trap {
        $gc | Stop-SPAssignment
    }
    
    $gc = Start-SPAssignment
    $site = $gc | Get-SPSite $siteUrl
    Write-Host "Doing something interesting..."
    $gc | Stop-SPAssignment
}
Set-SomethingInteresting "http://mysites"

So as you can see SharePoint 2010 introduces all kinds of really cool stuff - I've literally not even scratched the surface with what you can do with PowerShell and SharePoint 2010, let alone all the cool new features that 2010 introduces. Over the coming weeks and months I hope to provide details on how to do a full scripted install of SharePoint 2010 including detail on how to script out every single service - this will be critical information that every administrator and developer should have as PowerShell is going to be the recommended way to start and configure your services in the new architecture.

0 comments: