1

I have been reading and I've found different approaches about when to use Dispose()

I want to know if when using SharePoint 2016 Management Shell I will need to call it for the following cases:

  1. $deletedSite = Get-SPDeletedSite /sites/SiteA
  2. $s = Get-SPSite -Identity http:///Sites/Site1
  3. $w = Get-SPWeb http://sitename
2

Mostly what my experience is you have to call dispose whenever you create the variables and all of 3 scenarios you mentioned required disposal. But another thing is, if you close the PowerShell window then it automatically dispose the object for you.

If you are not using the assignment variables then you don't need to call the dispose as it will dispose after each iteration. i.e.

Get-SPWebApplication | Get-SPSite -limit all | ForEach-Object { write-host $_.Url  }

Here is the nice article you can read: WordPress - Powershell and Disposing

  • I called $deletedSite.Dispose() and I got an error saying that Dispose method doesn't exist on that class – MLC Jan 22 at 21:27
4

Typically disposing isn't much of an issue. If you've got a large farm and are doing a lot of looping you may want to consider disposing after you complete your task for that site/web.

The reason it's not much of an issue is because the objects just hold up memory when the PowerShell app is running. Once you close out of PowerShell, the memory those sites/webs were using is now freed up. If I recall correctly, you'll only use a few MB of ram if you don't dispose properly, and that gets cleared once you close out of PowerShell...

But if you're concerned about the RAM hog, then try to structure your scripts similar to any of the following:

foreach($site in (Get-SPSite -Limit ALL)){
    # Your Code for the site
    foreach($web in ($site | Get-SPWeb -Limit ALL)){
        # Your code for the Web

        $web.dispose()
    }
$site.dispose()
}

or

Get-SPSite -Limit ALL | %{
    # Your code for the Site
    $_| Get-SPWeb -Limit ALL | %{
        # Your code for the Web
        $_.dispose() # Disposes each web after it's been used.
    }
    $_.dispose() # Disposes site after webs are used.
}

or

function myFunction1 {
    param(
        [SPWeb]$web
        # ...
    );
    # Fn code
}
$myWeb = Get-SPWeb http(s)://myCollection/sites/web
myFunction -web $myWeb

$myWeb.dispose()

# alternatively,
function myFunction2 {
    param(
        [String]$Url
        # ...
    );
    $web = Get-SPWeb $Url
    # Fn code
    $web.dispose()
}
myFunction2 -Url http(s)://myCollection/sites/web

Note:

I don't think you can call dispose on $deletedSite, since it's deleted... But I may be wrong there. If so, just deal with it similar to the last example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.