Bulk Deleting Entities by Date Range: A Utility Content Hub Doesn't Give You Out of the Box

Hello Sitecorians! 👋


In this blog, I will show a small command-line utility that deletes entities in Sitecore Content Hub in bulk, the safe way. You give it your instance, your credentials, an entity definition and a range. It backs everything up to a CSV file first, asks you to confirm, and only then deletes.


The code is on GitHub, so you can use it as it is.


So, let's get started! 😊


The Use Case

Sooner or later, every Content Hub project needs to clean up data:

  • Test assets uploaded during UAT.
  • A failed import that created hundreds of wrong entities.
  • Entities of a feature that was removed.
  • Old jobs, logs or temporary records that nobody needs any more.


Deleting these one by one in the UI is slow. A mass delete in the UI works on what you select on the page, so you cannot simply give it a range, for example all assets created on 23 September. And once an entity is hard-deleted, it is gone. If you pick the wrong range, there is no undo.


So the requirement was:

  • Work for any entity definition, not only assets.
  • Select by an ID range, a created or modified date range, or a list of IDs.
  • Back up every entity to CSV before deleting, with all properties, all languages and all relations.
  • Show what will be deleted, and ask for a confirmation first.
  • Log every delete, so you know exactly what happened.

Note: This tool does a hard delete. The entity does not go to the trash and cannot be restored from Content Hub. For assets that someone may want back, use Move to trash in Content Hub instead.


How It Works

The utility is a small .NET 8 console app built on the Content Hub Web Client SDK. It has three commands: find and backup only read, and delete runs both of them before it deletes anything.


Each step is a gate. If nothing matches, if the backup is incomplete, or if you do not type the confirmation, the run stops before a single entity is deleted.


Step 1: Get the Tool and Connect


You need the .NET 8 SDK and an OAuth client in Content Hub (Manage → OAuth clients → New OAuth client). The user you sign in with must be allowed to read and delete the entities you select.


Download the code from GitHub and go to the src folder. You can pass the connection on the command line:


cd src
dotnet run -- find --host=https://<your-instance>.sitecorecontenthub.cloud --client-id=<id> --username=<user> --definition=M.Asset --created-from=2026-01-01 --created-to=2026-01-31


The client secret and password are asked for at the prompt and hidden while you type, so they never end up in your command history.


If you use the same instance often, save it once in appsettings.json, put the secrets in appsettings.local.json (git-ignored), and use --env=Sandbox instead.


Step 2: Choose What to Delete

--definition is always required, plus at least one range. If you give more than one range, an entity must match all of them.


OptionSelects
--definition=M.AssetThe entity definition. Any definition works, including your own.
--from-id=40000 --to-id=40500An ID range, both ends included
--created-from=2026-01-01 --created-to=2026-01-31A created date range, in UTC. A date alone as the end means up to the end of that day.
--modified-from / --modified-toThe same, for the modified date
--ids=test-assets.txtA file with one ID per line
--allEvery entity of the definition (use with care)


With --ids, the tool checks each ID. IDs that do not exist, or that belong to another definition, are left out and reported. So a wrong line in the file cannot delete something you did not mean.


Step 3: Find First

Always start with find. It only reads:


dotnet run -- find --env=Sandbox --definition=M.Asset --created-from=2026-01-01 --created-to=2026-01-31


It shows how many entities match and the first ten, and it saves all matching IDs to matched-ids_<time>.txt. If the number looks wrong, change the range and run it again. Nothing has been changed yet.


In the code, Content Hub filters the definition and the created date, and the tool checks the rest:


var query = Query.CreateQuery(entities => from e in entities
                                          where e.DefinitionName == definition
                                                && e.CreatedOn >= createdFrom
                                                && e.CreatedOn < createdTo
                                          select e);
query.Take = 100;

// Only IDs and system fields are loaded, so this is fast
var scroller = client.Querying.CreateEntityScroller(query, TimeSpan.FromMinutes(5),
    new EntityLoadConfiguration(CultureLoadOption.None, PropertyLoadOption.None, RelationLoadOption.None));


Step 4: Back Up to CSV

The backup command saves every matching entity, and still changes nothing:


dotnet run -- backup --env=Sandbox --definition=M.Asset --created-from=2026-01-01 --created-to=2026-01-31


It loads each entity in full, with all properties, all languages and all relations, and writes two files:

  • backup_<definition>_<time>.csv: one row per entity, easy to open in Excel. A multi-language property gets one column per language, like Title [en-US]. A relation gets one column with its IDs joined by ;, like TagToAsset (Child).
  • backup_<definition>_<time>.jsonl: the same data as one JSON object per line, with exact values. This is the better file if you ever need to re-create data with a script.


The heart of it:


var full = new EntityLoadConfiguration(CultureLoadOption.All, PropertyLoadOption.All, RelationLoadOption.All);
var entities = await client.Entities.GetManyAsync(ids, full);

foreach (var property in entity.Properties)
{
    if (IsCultureSensitive(property))
        foreach (var culture in entity.Cultures)
            row[$"{property.Name} [{culture.Name}]"] = entity.GetPropertyValue<object>(property.Name, culture);
    else
        row[property.Name] = entity.GetPropertyValue<object>(property.Name);
}

foreach (var relation in entity.Relations)
    row[relation.Name] = string.Join(";", relation.GetIds());


Open the CSV and check it before you go on.


Note: The backup holds metadata only. When you delete an asset, its files are deleted too, and they are not in the CSV.


Step 5: Delete

When the backup looks right, run delete with the same range:


dotnet run -- delete --env=Sandbox --definition=M.Asset --created-from=2026-01-01 --created-to=2026-01-31


The tool goes through these steps, in this order:

  1. It finds the entities again, so the list is current.
  2. It backs them up again. If even one entity cannot be backed up, it stops and deletes nothing.
  3. It shows the count and asks you to type, for example, DELETE 42. Anything else stops the run.
  4. It deletes the entities one by one, with a short pause between them.

foreach (var m in matches)
{
    try
    {
        await Retry.RunAsync(() => client.Entities.DeleteAsync(m.Id), $"Delete {m.Id}");
        await log.WriteLineAsync($"{m.Id},{m.Identifier},deleted,,{DateTime.Now:o}");
    }
    catch (Exception ex)
    {
        await log.WriteLineAsync($"{m.Id},{m.Identifier},failed,{ex.Message},{DateTime.Now:o}");
    }
    await Task.Delay(delayMs);
}


If one delete fails, for example because Content Hub refuses to delete an entity that is still in use, the tool logs it and carries on.


Step 6: Check the Log


Every result is written to delete-log_<time>.csv as it happens: Id, Identifier, Result (deleted or failed), Message and Time. Even if the run is stopped halfway, the log shows exactly what was deleted.


Run find again with the same range. It should now find nothing, or only the entities that failed.


Safety Built In

A bulk delete should be hard to get wrong, so the tool has a few guards:


GuardWhat it does
Range requiredIt will not run without a range, unless you pass --all
Backup firstEvery delete run backs up first, and stops if the backup is incomplete
Typed confirmationYou type DELETE <count>. --yes skips this, for scripted runs only
LimitIt stops if more than --max entities match (default 1000)
System definitions blockedM.User, M.UserGroup, M.Setting, M.Script, M.Action, M.Trigger, Portal.Page and others need --allow-system
Paced, with retries--delay-ms between deletes, and retries on timeouts and throttling


Conclusion:

I tested it on my sandbox: delete every asset created on 23 September (IST). In UTC, that day runs from 22 September 18:30 to 23 September 18:30, so I passed the times as well:


dotnet run -- delete --host=https://<your-instance>.sitecorecontenthub.cloud --client-id=<id> --username=<user> --definition=M.Asset --created-from=2026-09-22T18:30 --created-to=2026-09-23T18:30


The run:


The backup CSV keeps everything you need to check later what was deleted, one row per asset with every property, language and relation:


Verify With GraphQL


To see the result outside the tool, I used the GraphQL Preview API of Content Hub (/api/graphql/preview/v1). It filters on the created date with createdOn_gt and createdOn_lt, and total gives the count:


query AssetsCreatedOn23Sep {
  allM_Asset(
    first: 50
    where: {
      createdOn_gt: "2026-09-22T18:29:59Z"
      createdOn_lt: "2026-09-23T18:30:00Z"
    }
  ) {
    total
    results {
      id
      fileName
      createdOn
    }
  }
}


Before the delete, it returned the same 27 assets the tool found:

After the delete, the same query returns nothing:


{
  "data": {
    "allM_Asset": {
      "total": 0,
      "results": []
    }
  }
}


Note: The delivery API (Experience Edge) only returns published assets, so test assets often don't show there at all. Use the Preview API to check, and send your preview token in the X-GQL-Token header. Blur the token in any screenshot.


Conclusion


A bulk delete is a small piece of code, but a big risk. This utility makes it safe and repeatable: select entities of any definition by ID, date or a list, find first, back up to CSV and JSON, confirm with the count, delete with a log. Run it on a sandbox first, keep the backup files, and agree any production cleanup with your team.


I hope this helps you in your Content Hub journey! If you have any questions, feel free to drop a comment below. 😊


Stay tuned for more! 👋

Post a Comment (0)
Previous Post Next Post