11

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?

14

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.

8

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...
}
  • 1
    The New-UsingBlock is now a built in command. No need to import the function in 4.x versions of SPE. – Michael West Oct 24 '16 at 3:46

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.