Removing SPSite Property Bag Keys w/ PowerShell

I recently encountered a scenario where it was necessary to remove keys from the property bag of a site collection. Site collection properties are stored within the Properties collection on the RootWeb of the Site, but Properties.Remove(“key”) failed every time we tried it. It turns out that in addition to toggling the AllowUnsafeUpdates flag, you also must update the Properties object, then remove the key from the AllProperties collection (this was the magic piece we were missing).

$site = Get-SPSite http://path/to/site/collection
$web = $site.RootWeb
$web.AllowUnsafeUpdates = "true"
$web.Properties.Remove("_keytoremove")
$web.Properties.Update()
$web.AllProperties.Remove("_keytoremove")
$web.AllowUnsafeUpdates = "false"
$web.AllowUnsafeUpdates = "true"
$web.Update()
$web.AllowUnsafeUpdates = "false"

Once you've executed the commands above to remove the script, re-instantiate the Site and Web objects and query the AllProperties collection to ensure your key has been removed.

$site = Get-SPSite http://path/to/site/collection
$web = $site.RootWeb
$web.AllProperties