Showing posts with label SCSM. Show all posts
Showing posts with label SCSM. Show all posts

Monday, May 2, 2016

System Center Service Manager 2012 R2 CSV sync by using Import-SCSMClassInstance

Problem: import-SCSMinstance imports objects that are in a specified CSV file, but... it does not remove "obsolete" objects. - I want to really sync - load what is missing, and remove what is obsolete

 if you drop all objects and then import them again, objects get a new GUID, so you lose history for the objects that are imported again, so this is not a preferred solution.

here is how you truly sync (mirror) the objects - this example is a simple class only with displaynames of groups:

Create your CSV file, this should contain all the objects that should be in your class
in my example, I load them from a SQL database:

$query = "select last_name from ca_contact where contact_type=2308"
$connection = new-object system.data.sqlclient.sqlconnection($StrConn);
$adapter = new-object system.data.sqlclient.sqldataadapter ($query, $connection)
$set = new-object system.data.dataset
$adapter.Fill($set)
$table = new-object system.data.datatable
$table = $set.Tables[0]

this is collecting some group names into $table
then create the CSV file and I add the values also to array $csv (I  run a "-contains" against this array - which is not possible against the $table variable)

$csvfile = "C:\SCSMimport\USDGroups.csv"
$csv=@()
Foreach ($R in ($table))
{
 
    Add-Content $csvfile ($R.last_name)
     $csv += $name
}

get all your current objects loaded in SCSM:
$GrpClass = Get-SCSMClass -Name USDgroups
$all = Get-SCSMClassInstance -Class $GrpClass

and now we compare $all against the array that contains anything that should be in the group.
 
foreach ($obj in $all)
{    if ($csv -notcontains $obj.DisplayName)
    {        "obsolete group : " + $obj.DisplayName
        Remove-SCSMClassInstance -Instance $obj
     }
}
 


So.. anything not in the CSV but still loaded in the class in SCSM is now removed from SCSM

and then the last step to ensure new objects are added:
Import-SCSMInstance -DataFileName $csvfile -FormatFileName 'C:\tools\SCSMimport\USDGroups.xml'

 that's it !