Batch delete script for Items within Notification Server

book

Article ID: 180781

calendar_today

Updated On:

Products

Management Platform (Formerly known as Notification Server)

Issue/Introduction

 

Resolution

The following script can be used to delete a set of items based on item guids fetched from a custom query. Within the script is a section to include your select statement. The script looks at item dependancies and keeps the referential integrity of the database, which is much preferred over culling rows directly from the database tables.

The script is provided as follows:

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using System.IO;

 

using Altiris.NS.ContextManagement;

using Altiris.NS.ItemManagement;

 

class NScript

{

    const String SQL = @"

                Place a Custom Query Here representing GUIDS that need to be deleted.

                Example:  select GUID from ItemToDelete

                ";

 

    static void Main(string[] args)

    {

        Console.Clear();

                List<Guid> guids = new List<Guid>();

 

        using (DatabaseContext context = DatabaseContext.GetContext())

        {

            Console.WriteLine("Starting..");

            SqlCommand cmd = (SqlCommand)context.CreateCommand(SQL);

            cmd.CommandType = CommandType.Text;

            using (SqlDataReader reader = cmd.ExecuteReader())

            {

                while (reader.Read())

                {

                                   guids.Add(reader.GetGuid(0));

                                }

                   }

 

                   foreach (Guid guid in guids)

                   {

                IItem item;

                try

                                {

                                   item = Item.GetItem(guid, ItemLoadFlags.Writeable);

                                   Console.WriteLine("Calling Delete() for: {0.EN_US}", item.Name);

                                   item.Delete();

                                }

                catch (Exception ex)

                                {

                                   Console.WriteLine("There was an error deleting {0.EN_US}: {1.EN_US}", guid, ex.Message);

                                }

                   }

        }

        Console.WriteLine("Done!");

    }

}

 **** NOTE: This script is provided as it is and not considered as a supported script. Please be cautious when deleting items using this script. Ensure there is a valid full backup of the database and your select query returns the results you are expecting.