PowerShell Dispose-All

With all the talk of Dispose safety in object model code, it’s easy to forget that those same objects need to be cleaned up in PowerShell as well. Sure, SharePoint will clean everything up when the thread ends, but my PowerShell doesn’t get closed all that often, leaving open SPRequests for extended periods of time. To combat that, I wrote a quick function that will clean up all my IDisposable variables for me:

function Dispose-All {
    Get-Variable -exclude Runspace |
        Where-Object {
            $_.Value -is [System.IDisposable]
        } |
        Foreach-Object {
            $_.Value.Dispose()
            Remove-Variable $_.Name
        }
}

For some reason, I don’t think it would be a good idea to Dispose() the current Runspace… (Edit: Apparently I define $Runspace in a long-forgotten part of my profile script, so don’t be worried if you don’t have that defined.)

Of course this isn’t foolproof, as variables can be overwritten and not all IDisposables will have been assigned to variables in the first place, but you could certainly adapt your shell behavior to make the most out of a catch-all cleanup like this.

About these ads

One Response to “PowerShell Dispose-All”

  1. Links (12/14/2008) « Steve Pietrek - Everything SharePoint Says:

    […] PowerShell Dispose-All Possibly related posts: (automatically generated)Links (10/28/2007)How to Build Your Own Social Network in the Enterprise for FreeFootnote Site Lets You Search and Modify WWII Records […]


Comments are closed.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: