2 Answers
2

Use of objects, such as SPWeb or SPSite, in PowerShell requires a proper memory management. Get commands dispose of these objects immediately after the pipeline finishes, but by using SPAssignment, you can assign the list of objects to a variable and dispose of the objects after they are no longer needed. Here is an example of usage of SPAssignment object, you can assign SPWeb to a variable and dispose of when they are needed to free up memory. See below:

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:

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'.

This looks promising! I'll give it a try. (your guess in the begining of your answer is right ;) )
–
jumboJun 21 '12 at 15:31

Unfortunately the Sharepoint Management Shell behaves exactly the same :( Did you tried it? Did it work for you in Shp Mngmt Shell?
–
jumboJun 21 '12 at 15:44

As I already wrote, this is not the solution for my problem, but thanks for mentioning the config script, it is important to set ReuseThread option when I try to use Start-Assignment cmdlet.
–
jumboJun 21 '12 at 18:55

1

I did not try this, and I didn't know (remember?) about SPAssingment. It is stated on MSDN: "It is important to note that every site collection returned by the Get-SPWeb cmdlet is automatically disposed of at the end of the pipeline. To store the results of Get-SPWeb in a local variable, the Start-SPAssignment and Stop-SPAssignment cmdlets must be used to avoid memory leaks." on technet.microsoft.com/en-us/library/ff607807.aspx
–
DribbelJun 22 '12 at 6:02

Wow, I didn't know that this is on MSDN. I should have look there first. Thanks.
–
jumboJun 22 '12 at 6:08