I'm guessing that you are using a regular PowerShell session, probably with the SharePoint snapp-in loaded. And not the 'SharePoint Management Shell'.
With a regular powershell session each command is executed with-in its own thread. And disposable objects, like SPWeb
, are automatically disposed on the end of a thread. Thus what could happen is that the Garbage Collector is quick and disposes your SPWeb
before you execute the next statement.
Disposing does not clear or destroy an object, it just gives an object a chance to close connections, clean up things the GC won't clean up, etc. Most properties will still be available (like Title
) but actions that require a database connection, like $w.list["listName"]
, will error out.
SharePoint Management Shell
The SP Management Shell is just a regular powershell session with this tiny bit of script executed when it loads:
$ver = $host | select version
if ($ver.Version.Major -gt 1) {$Host.Runspace.ThreadOptions = “ReuseThread”}
Add-PsSnapin Microsoft.SharePoint.PowerShell
Set-location $home
Notice the setting on ThreadOptions
. With the SP Management Shell you get a sligtly different powershell (in an ugly console). One that reuses the same thread for succesive commands, and thus a PowerShell that won't dispose objects 'behind your back'.
See this blog for more information.
Load C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\\sharepoint.ps1
, instead of just adding the SnapIn
Tip
Use the PowerShell ISE
, which has ThreadReuse on as default. And it is a nice tool for writing and testing scripts.