I want to write a script which could potentially clean up a load of unused assets, but I would like it not to trigger events (index rebuilds etc).
Is there a way to say "do this silently" in a Powershell script?
This is how you could use the using statement inside Powershell
function Using-Object
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[AllowEmptyCollection()]
[AllowNull()]
[object]
$InputObject,
[Parameter(Mandatory = $true)]
[scriptblock]
$ScriptBlock
)
try
{
.$ScriptBlock
}
finally
{
if ($null -ne $InputObject -and $InputObject -is [System.IDisposable])
{
$InputObject.Dispose()
}
}
}
Using-Object ($streamWriter = New-Object System.IO.StreamWriter("$SitecoreDataFolder\newfile.txt")) {
$streamWriter.WriteLine('Line written inside Using block.')
$streamWriter
}
This is how you could disable events in Sitecore
Using-Object ($ed = New-Object Sitecore.Data.Events.EventDisabler) {
# "Disabled"
}
Notice that a script execution triggers some events in the background (you can observe index rebuild jobs even if you run empty script).
Once you wrap something with using statement, everything what is inside should work in 'switched context', with all events disabled.
I tested it and number of items added to indexing queue is different.
Wrapping your code in a BulkUpdateContext
block as mentioned in the Powershell GitBook will make the tasks more performant and also silence any events or tasks.
Import-Function -Name New-UsingBlock
New-UsingBlock (New-Object Sitecore.Data.BulkUpdateContext) {
# insert cleanup code here...
}
New-UsingBlock
is now a built in command. No need to import the function in 4.x versions of SPE.
Commented
Oct 24, 2016 at 3:46