Skip to content

Code snippets for SCSM 2010 SP1 SDK. Part 1.

Code snippets for SCSM 2010 SP1 SDK. Part 1. published on 6 Comments on Code snippets for SCSM 2010 SP1 SDK. Part 1.

image

This article contains code snippets for C# and PowerShell that can be helpful when you work with SCSM 2010 SP1 SDK.

 

 

Add reference to SDK assembly

To start using SDK you need to add reference to the Microsoft.EnterpriseManagement.Core.dll library. This library located in %PROGRAMFILES%\Microsoft System Center\Service Manager 2010\SDK Binaries\ folder at SCSM server. Also this library installed in GAC on each computer with SCSM console installed (and all SCSM servers too).

To add reference in Visual Studio just press right mouse button then click to Add Reference item and locate the Microsoft.EnterpriseManagement.Core.dll file:
image
At PowerShell you must load assembly with [Reflection.Assembly]::LoadWithPartialName or LoadFile methods:

$InstallPath = "c:\Program Files\Microsoft System Center\Service Manager 2010\SDK Binaries\"
$dll = "Microsoft.EnterpriseManagement.Core.dll"
$dllPath = $InstallPath + $dll

[reflection.assembly]::LoadFile($dllPath) | out-null

If library installed in GAC you can use shorten version:

$dll = "Microsoft.EnterpriseManagement.Corel"
[reflection.assembly]::LoadWithPartialName($dll) | out-null

Connect to SCSM server

// C#
EnterpriseManagementGroup mg = new EnterpriseManagementGroup("serverName");
# PowerShell
$MG = new-object Microsoft.EnterpriseManagement.EnterpriseManagementGroup("serverName")

# use "C# using-like" aproach
$NS = "Microsoft.EnterpriseManagement"
$EMGType = "${NS}.EnterpriseManagementGroup"
$MG = new-object $EMGType "serverName"

Connect to server with specified login and password

// C#
EnterpriseManagementConnectionSettings settings = new EnterpriseManagementConnectionSettings("serverName");
settings.UserName = "userName"
char[] pass = { 'p', '@', 's', s', 'w', '0', 'r', 'd' };
settings.Password = new System.Security.SecureString();
foreach (char c in pass)
    settings.Password.AppendChar(c);
settings.Domain = "DOMAIN";
EnterpriseManagementGroup mg = new EnterpriseManagementGroup(settings);
#PowerShell
$NS = "Microsoft.EnterpriseManagement"

$settings = new-object ($NS + ".EnterpriseManagementConnectionSettings") "serverName"
$settings.UserName = "userName"
$settings.Password = ConvertTo-SecureString "p@ssw0rd" -AsPlainText -Force
$settings.Domain = "DOMAIN";
$mg = new-object ($NS + ".EnterpriseManagementGroup") $settings

Connect to server with specified UI culture

// C#
EnterpriseManagementConnectionSettings settings = new EnterpriseManagementConnectionSettings("serverName");
settings.UserName = "userName"
char[] pass = { 'p', '@', 's', s', 'w', '0', 'r', 'd' };
settings.Password = new System.Security.SecureString();
foreach (char c in pass)
    settings.Password.AppendChar(c);
settings.Domain = "DOMAIN";

settings.ThreeLetterWindowsLanguageName = "RUS";

EnterpriseManagementGroup mg = new EnterpriseManagementGroup(settings);
#PowerShell
$NS = "Microsoft.EnterpriseManagement"

$settings = new-object ($NS + ".EnterpriseManagementConnectionSettings") "serverName"
$settings.UserName = "userName"
$settings.Password = ConvertTo-SecureString "p@ssw0rd" -AsPlainText -Force
$settings.Domain = "DOMAIN"

$settings.ThreeLetterWindowsLanguageName = "RUS"

$mg = new-object ($NS + ".EnterpriseManagementGroup") $settings

Get the class by ID (Guid) or name

// by ID (Guid)
ManagementPack mp = mg.ManagementPacks.GetManagementPack(new Guid("35D5DE4C-0284-4622-BB9C-97ADDE830136"));

// by name
ManagementPackCriteria cr = new ManagementPackCriteria("Name = 'MP.Internal.Name'");
IList<ManagementPack> mps = mg.ManagementPacks.GetManagementPacks(cr);
if (mps != null && mps.Count > 0)
{
   ManagementPack mp = mps[0];
}
# powershell
# by ID (Guid)
$mp = $mg.ManagementPacks.GetManagementPack([Guid]"35D5DE4C-0284-4622-BB9C-97ADDE830136")

# by name
$cr = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackCriteria("Name = 'MP.Internal.Name'")
$mps = $mg.ManagementPacks.GetManagementPacks($cr)
if ($mps -and $mps.Count -gt 0)
{
   $mp = $mps[0]
}

Get object by internal ID (Guid)

Helpful when you work inside workflow (here and below implies that you already connected to server and using the mg and $mg variable in  C# and PowerShell respectively).

// C#
EnterpriseManagementObject obj = mg.EntityObjects.GetObject<EnterpriseManagementObject>(new Guid("35D5DE4C-0284-4622-BB9C-97ADDE830136"), ObjectQueryOptions.Default);

# powershell
$MethodType = ([Guid],[Microsoft.EnterpriseManagement.Common.ObjectQueryOptions])
$GetObject = $managementGroup.EntityObjects.GetType().GetMethod("GetObject",$MethodType)
$GetObjectMethod = $GetObject.MakeGenericMethod([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObject])
$obj = $GetObjectMethod.Invoke($managementGroup.EntityObjects, ($ObjectId, [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions]::Default))

Get object by generic criteria

// C#
// work only with generic properties
EnterpriseManagementObjectGenericCriteria genericCr = new EnterpriseManagementObjectGenericCriteria("Name = 'IR1416'");
IObjectReader<EnterpriseManagementObject> reader = mg.EntityObjects.GetObjectReader<EnterpriseManagementObject>(genericCr, ObjectQueryOptions.Default);
if (reader != null && reader.Count > 0)
{
  foreach (EnterpriseManagementObject obj in reader)
  {
      // do something
  }
}
# poweshell

# you must use type cust to prevent this error when Invoke method called below:
# "Object of type 'System.Management.Automation.PSObject' cannot be converted to type 'Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectGenericCriteria'."
[Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectGenericCriteria]$genericCr = new-object Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectGenericCriteria("Name = 'IR1416'")
[Type[]]$MethodType = ([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectGenericCriteria],
            [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions])
   
$method = $mg.EntityObjects.GetType().GetMethod("GetObjectReader",$MethodType)
$genericMethod = $method.MakeGenericMethod([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObject])
$objects = $genericMethod.Invoke($mg.EntityObjects, ($genericCr, [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions]::Default))
foreach($obj in $objects)
{
   # do something
}

Get objects by string criteria and class

//c#

ManagementPackClassCriteria classCr = new ManagementPackClassCriteria("Name = 'System.WorkItem.Incident'");
IList<ManagementPackClass> classes = mg.EntityTypes.GetClasses(classCr);

if (classes != null && classes.Count > 0)
{
    ManagementPackClass cl = classes[0];

    EnterpriseManagementObjectCriteria cr = new EnterpriseManagementObjectCriteria("TargetResolutionTime > '5/19/2011'", cl);
    IObjectReader<EnterpriseManagementObject> reader = mg.EntityObjects.GetObjectReader<EnterpriseManagementObject>(cr, ObjectQueryOptions.Default);
    if (reader != null && reader.Count > 0)
    {
        foreach (EnterpriseManagementObject obj in reader)
        {
            //  do something
        }
    }
}
# powershell
$classCr = new-object  Microsoft.EnterpriseManagement.Configuration.ManagementPackClassCriteria("Name = 'System.WorkItem.Incident'")
$classes = $mg.EntityTypes.GetClasses($classCr)

if ($classes -and $classes.Count -gt 0)
{
    $cl = $classes[0]
    [Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria]$cr = new-object Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria("TargetResolutionTime > '5/19/2011'", $cl)
    [Type[]]$MethodType = ([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria],
                [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions])
       
    $method = $mg.EntityObjects.GetType().GetMethod("GetObjectReader",$MethodType)
    $genericMethod = $method.MakeGenericMethod([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObject])
    $objects = $genericMethod.Invoke($mg.EntityObjects, ($cr, [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions]::Default))
    foreach($obj in $objects)
    {
        # do something
    }
}

Get objects by XML criteria

// c#

string strCriteria = @"<Criteria xmlns='http://Microsoft.EnterpriseManagement.Core.Criteria/'>
<Reference Id='System.WorkItem.Library' PublicKeyToken='{0}' Version='{1}' Alias='WorkItem' />
<Expression>
<And>
    <Expression>
    <SimpleExpression>
        <ValueExpressionLeft>
        <Property>$Context/Property[Type='System.WorkItem.Incident']/TargetResolutionTime$</Property>
        </ValueExpressionLeft>
        <Operator>Less</Operator>
        <ValueExpressionRight>
        <Token>[Now]</Token>
        </ValueExpressionRight>
    </SimpleExpression>
    </Expression>
    <Expression>
    <SimpleExpression>
        <ValueExpressionLeft>
        <Property>$Context/Property[Type='WorkItem!System.WorkItem']/CreatedDate$</Property>
        </ValueExpressionLeft>
        <Operator>Less</Operator>
        <ValueExpressionRight>
        <Value>04/29/2011</Value>
        </ValueExpressionRight>
    </SimpleExpression>
    </Expression>
</And>
</Expression>
</Criteria>";

ManagementPackCriteria mpCr = new ManagementPackCriteria("Name = 'System.WorkItem.Incident.Library'");
IList<ManagementPack> mps = mg.ManagementPacks.GetManagementPacks(mpCr);

ManagementPackClassCriteria classCr = new ManagementPackClassCriteria("Name = 'System.WorkItem.Incident'");
IList<ManagementPackClass> classes = mg.EntityTypes.GetClasses(classCr);

if (mps != null && mps.Count > 0 && classes != null && classes.Count > 0)
{
    ManagementPack mp = mps[0];
    ManagementPackClass cl = classes[0];
    // For all system management packs version and KeyToken are same.
    EnterpriseManagementObjectCriteria cr = new EnterpriseManagementObjectCriteria(string.Format(strCriteria, mp.KeyToken, mp.Version),cl, mp, mg);
    IObjectReader<EnterpriseManagementObject> reader = mg.EntityObjects.GetObjectReader<EnterpriseManagementObject>(cr, ObjectQueryOptions.Default);
    if (reader != null && reader.Count > 0)
    {
        foreach (EnterpriseManagementObject obj in reader)
        {
            // do something
        }
    }
}
# powershell

# note to escaping the $ character, otherwise $Context will parsed as variable
$strCriteria = "<Criteria xmlns='http://Microsoft.EnterpriseManagement.Core.Criteria/'>
<Reference Id='System.WorkItem.Library' PublicKeyToken='{0}' Version='{1}' Alias='WorkItem' />
<Expression>
<And>
    <Expression>
    <SimpleExpression>
        <ValueExpressionLeft>
        <Property>`$Context/Property[Type='System.WorkItem.Incident']/TargetResolutionTime$</Property>
        </ValueExpressionLeft>
        <Operator>Less</Operator>
        <ValueExpressionRight>
        <Token>[Now]</Token>
        </ValueExpressionRight>
    </SimpleExpression>
    </Expression>
    <Expression>
    <SimpleExpression>
        <ValueExpressionLeft>
        <Property>`$Context/Property[Type='WorkItem!System.WorkItem']/CreatedDate$</Property>
        </ValueExpressionLeft>
        <Operator>Less</Operator>
        <ValueExpressionRight>
        <Value>04/29/2011</Value>
        </ValueExpressionRight>
    </SimpleExpression>
    </Expression>
</And>
</Expression>
</Criteria>"

$mpCr = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackCriteria("Name = 'System.WorkItem.Incident.Library'")
$mps = $mg.ManagementPacks.GetManagementPacks($mpCr)

$classCr = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackClassCriteria("Name = 'System.WorkItem.Incident'")
$classes = $mg.EntityTypes.GetClasses($classCr)

if ($mps -and $mps.Count -gt 0 -and $classes -and $classes.Count -gt 0)
{
    $mp = $mps[0];
    $cl = $classes[0];
    # For all system management Version and KeyToken are same.
    [string]::Format($strCriteria, $mp.KeyToken, $mp.Version)
    try
    {
    [Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria]$cr = 
                new-object Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria(
                    [string]::Format($strCriteria, $mp.KeyToken, $mp.Version),
                    $cl, 
                    $mp, 
                    $mg)
    }
    catch
    {
        $_.Exception.InnerException.InnerException
    }
    [Type[]]$MethodType = ([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria],
                [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions])
       
    $method = $mg.EntityObjects.GetType().GetMethod("GetObjectReader",$MethodType)
    $genericMethod = $method.MakeGenericMethod([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObject])
    $objects = $genericMethod.Invoke($mg.EntityObjects, ($cr, [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions]::Default))
    foreach($obj in $objects)
    {
        # do something
    }
}

Get objects with specified properties

This approach helpful to increase amount of data transferred from server. If you doesn’t use this your query look likt SELECT * FROM Table, when you use them – like SELECT Prop1, Prop2 FROM Table.

// C#

ManagementPackClassCriteria classCr = new ManagementPackClassCriteria("Name = 'System.WorkItem.Incident'");
IList<ManagementPackClass> classes = mg.EntityTypes.GetClasses(classCr);

if (classes != null && classes.Count > 0)
{
    ManagementPackClass incidentCl = classes[0];
    EnterpriseManagementObjectCriteria cr = new EnterpriseManagementObjectCriteria("TargetResolutionTime > '5/19/2011'", incidentCl);

    ManagementPackProperty prop = null;
               
    ObjectQueryOptions options = new ObjectQueryOptions(ObjectPropertyRetrievalBehavior.None);
    options.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered;
    incidentCl.TryGetProperty("Id", out prop);
    // if property declared in parent class you must set it directly
    options.AddPropertyToRetrieve(incidentCl, prop);
    prop = null;
    incidentCl.TryGetProperty("TargetResolutionTime", out prop);
    options.AddPropertyToRetrieve(prop);

    IObjectReader<EnterpriseManagementObject> reader = mg.EntityObjects.GetObjectReader<EnterpriseManagementObject>(cr, options);
    foreach (EnterpriseManagementObject obj in reader)
    {
        // do something
    }
}
#powershell

$classCr = new-object  Microsoft.EnterpriseManagement.Configuration.ManagementPackClassCriteria("Name = 'System.WorkItem.Incident'")
$classes = $mg.EntityTypes.GetClasses($classCr)

if ($classes -and $classes.Count -gt 0)
{
    $incidentCl = $classes[0]
   
    [Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria]$cr = new-object Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria("TargetResolutionTime > '5/19/2011'", $incidentCl)
    [Type[]]$MethodType = ([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObjectCriteria],
                [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions])
       
    $method = $mg.EntityObjects.GetType().GetMethod("GetObjectReader",$MethodType)
    $genericMethod = $method.MakeGenericMethod([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObject])
    
               
    $options = new-object Microsoft.EnterpriseManagement.Common.ObjectQueryOptions([Microsoft.EnterpriseManagement.Common.ObjectPropertyRetrievalBehavior]::None)
    $options.ObjectRetrievalMode = [Microsoft.EnterpriseManagement.Common.ObjectRetrievalOptions]::Buffered
    $prop = $null
    $incidentCl.TryGetProperty("Id", [ref]$prop) | out-null
    #  if property declared in parent class you must set it directly
    $options.AddPropertyToRetrieve($incidentCl, $prop)
    $prop = $null
    $incidentCl.TryGetProperty("TargetResolutionTime", [ref]$prop)  | out-null
    $options.AddPropertyToRetrieve($prop)
    # без жесткого приведения типов падает с ошибкой "Object of type 'System.Management.Automation.PSObject' cannot be converted to type 'Microsoft.EnterpriseManagement.Common.ObjectQueryOptions'."
    $objects = $genericMethod.Invoke($mg.EntityObjects, ($cr, [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions]$options))
    foreach($obj in $objects)
    {
        # do something
    }
}

Get type projection objects

// c#

string strCriteria = @"<Criteria xmlns='http://Microsoft.EnterpriseManagement.Core.Criteria/'>
<Reference Id='System.WorkItem.Library' PublicKeyToken='{0}' Version='{1}' Alias='WorkItem' />
<Expression>
<And>
    <Expression>
    <SimpleExpression>
        <ValueExpressionLeft>
        <Property>$Context/Property[Type='System.WorkItem.Incident']/TargetResolutionTime$</Property>
        </ValueExpressionLeft>
        <Operator>Less</Operator>
        <ValueExpressionRight>
        <Token>[Now]</Token>
        </ValueExpressionRight>
    </SimpleExpression>
    </Expression>
    <Expression>
    <SimpleExpression>
        <ValueExpressionLeft>
        <Property>$Context/Property[Type='WorkItem!System.WorkItem']/CreatedDate$</Property>
        </ValueExpressionLeft>
        <Operator>Less</Operator>
        <ValueExpressionRight>
        <Value>04/29/2011</Value>
        </ValueExpressionRight>
    </SimpleExpression>
    </Expression>
</And>
</Expression>
</Criteria>";

ManagementPackCriteria mpCr = new ManagementPackCriteria("Name = 'System.WorkItem.Incident.Library'");
IList<ManagementPack> mps = mg.ManagementPacks.GetManagementPacks(mpCr);
ManagementPack incidentMp = mps != null && mps.Count >0?mps[0]:null;

ManagementPackClassCriteria classCr = new ManagementPackClassCriteria("Name = 'System.WorkItem.Incident'");
IList<ManagementPackClass> classes = mg.EntityTypes.GetClasses(classCr);
ManagementPackClass incidentCl = classes != null && classes.Count > 0?classes[0]:null;

classCr = new ManagementPackClassCriteria("Name = 'System.Domain.User'");
classes = mg.EntityTypes.GetClasses(classCr);
ManagementPackClass domainUserCl = classes != null && classes.Count > 0 ? classes[0] : null;

ManagementPackTypeProjectionCriteria tpCr = new ManagementPackTypeProjectionCriteria("Name = 'System.WorkItem.Incident.ProjectionType'");
IList<ManagementPackTypeProjection> projList = mg.EntityTypes.GetTypeProjections(tpCr);
ManagementPackTypeProjection incidentProj = projList != null && projList.Count > 0 ? projList[0] : null;


if (incidentMp != null && incidentCl != null && incidentProj != null)
{
    string criteria = string.Format(strCriteria, incidentMp.KeyToken, incidentMp.Version);
    ObjectProjectionCriteria cr = new ObjectProjectionCriteria(criteria, incidentProj, incidentMp, mg);

    ManagementPackProperty prop = null;
    // If you set ObjectPropertyRetrievalBehavior.All, then for object itselff only specified property returned
    // but all properties for related objects
    ObjectQueryOptions options = new ObjectQueryOptions(ObjectPropertyRetrievalBehavior.All);
    incidentCl.TryGetProperty("Id", out prop);
    //  if property declared in parent class you must set it directly
    options.AddPropertyToRetrieve(incidentCl, prop);
    prop = null;
    incidentCl.TryGetProperty("TargetResolutionTime", out prop);
    options.AddPropertyToRetrieve(prop);
    prop = null;
    domainUserCl.TryGetProperty("Domain", out prop);
    options.AddPropertyToRetrieve(prop);
    prop = null;
    domainUserCl.TryGetProperty("UserName", out prop);
    options.AddPropertyToRetrieve(prop);
    prop = null;

    IObjectProjectionReader<EnterpriseManagementObject> reader = mg.EntityObjects.GetObjectProjectionReader<EnterpriseManagementObject>(cr, options);
    // or get all properties
    // IObjectProjectionReader<EnterpriseManagementObject> reader = mg.EntityObjects.GetObjectProjectionReader<EnterpriseManagementObject>(cr, ObjectQueryOptions.Default);
    foreach (EnterpriseManagementObjectProjection proj in reader)
    {
        Console.WriteLine(proj.Object[null, "Id"]);
        Console.WriteLine(proj["CreatedWorkItem"][0].Object[null, "Domain"]);
        Console.WriteLine(proj["CreatedWorkItem"][0].Object[null, "UserName"]);
    }
}
#powershell 

$strCriteria = "<Criteria xmlns='http://Microsoft.EnterpriseManagement.Core.Criteria/'>
<Reference Id='System.WorkItem.Library' PublicKeyToken='{0}' Version='{1}' Alias='WorkItem' />
<Expression>
<And>
    <Expression>
    <SimpleExpression>
        <ValueExpressionLeft>
        <Property>`$Context/Property[Type='System.WorkItem.Incident']/TargetResolutionTime$</Property>
        </ValueExpressionLeft>
        <Operator>Less</Operator>
        <ValueExpressionRight>
        <Token>[Now]</Token>
        </ValueExpressionRight>
    </SimpleExpression>
    </Expression>
    <Expression>
    <SimpleExpression>
        <ValueExpressionLeft>
        <Property>`$Context/Property[Type='WorkItem!System.WorkItem']/CreatedDate$</Property>
        </ValueExpressionLeft>
        <Operator>Less</Operator>
        <ValueExpressionRight>
        <Value>04/29/2011</Value>
        </ValueExpressionRight>
    </SimpleExpression>
    </Expression>
</And>
</Expression>
</Criteria>"

$mpCr = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackCriteria("Name = 'System.WorkItem.Incident.Library'")
$mps = $mg.ManagementPacks.GetManagementPacks($mpCr)
if($mps -and $mps.Count -gt 0) { $incidentMp = $mps[0] }

$classCr = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackClassCriteria("Name = 'System.WorkItem.Incident'")
$classes = $mg.EntityTypes.GetClasses($classCr)
if($classes -and $classes.Count -gt 0) { $incidentCl = $classes[0] }

$classCr = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackClassCriteria("Name = 'System.Domain.User'")
$classes = $mg.EntityTypes.GetClasses($classCr);
if($classes -and $classes.Count -gt 0) { $domainUserCl = $classes[0] }

$tpCr = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackTypeProjectionCriteria("Name = 'System.WorkItem.Incident.ProjectionType'")
$projList = $mg.EntityTypes.GetTypeProjections($tpCr)
if($projList -and $projList.Count -gt 0) { $incidentProj = $projList[0] }

if ($incidentMp -and $incidentCl -and $incidentProj)
{
    
     $criteria = [string]::Format($strCriteria, $incidentMp.KeyToken, $incidentMp.Version)
     [Microsoft.EnterpriseManagement.Common.ObjectProjectionCriteria]$cr = 
        new-object Microsoft.EnterpriseManagement.Common.ObjectProjectionCriteria($criteria,
            $incidentProj, 
            $incidentMp, 
            $mg)
    # If you set ObjectPropertyRetrievalBehavior.All, then for object itselff only specified property returned
    # but all properties for related objects
    $options = new-object Microsoft.EnterpriseManagement.Common.ObjectQueryOptions([Microsoft.EnterpriseManagement.Common.ObjectPropertyRetrievalBehavior]::None)
    $prop = $null
    $incidentCl.TryGetProperty("Id", [ref]$prop) | out-null
    # if property declared in parent class you must set it directly
    $options.AddPropertyToRetrieve($incidentCl, $prop)
    $prop = $null
    $incidentCl.TryGetProperty("TargetResolutionTime", [ref]$prop)  | out-null
    $options.AddPropertyToRetrieve($prop)
    $prop = $null
    $domainUserCl.TryGetProperty("Domain", [ref]$prop)  | out-null
    $options.AddPropertyToRetrieve($prop)
    $prop = $null
    $domainUserCl.TryGetProperty("UserName", [ref]$prop)  | out-null
    $options.AddPropertyToRetrieve($prop)
    
    [Type[]]$MethodType = ([Microsoft.EnterpriseManagement.Common.ObjectProjectionCriteria],[Microsoft.EnterpriseManagement.Common.ObjectQueryOptions])
    $GetObjectProjectionReader = $mg.EntityObjects.GetType().GetMethod("GetObjectProjectionReader",$MethodType)
    $GetObjectProjectionReaderMethod = $GetObjectProjectionReader.MakeGenericMethod([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObject])
    $reader = $GetObjectProjectionReaderMethod.Invoke($mg.EntityObjects, ($cr, [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions]$options))
    foreach($proj in $reader)
    {
        # note to different from c# way to access the properties
        write-host $proj.Object.Item($null, "Id")
        write-host $proj["CreatedWorkItem"][0].Object.Item($null, "Domain")
        write-host $proj["CreatedWorkItem"][0].Object.Item($null, "UserName")
    }
}

Get type projection by object ID

Very helpful when you work with workflow

// C#

Guid objId = new Guid("c8144a24-444b-b721-d885-064ddf11d8b7");

ManagementPackTypeProjectionCriteria tpCr = new ManagementPackTypeProjectionCriteria("Name = 'System.WorkItem.Incident.ProjectionType'");
IList<ManagementPackTypeProjection> projList = mg.EntityTypes.GetTypeProjections(tpCr);
ManagementPackTypeProjection incidentProj = projList != null && projList.Count > 0 ? projList[0] : null;

List<Guid> objectsToLoad = new List<Guid>();
objectsToLoad.Add(objId);

ObjectQueryOptions options = new ObjectQueryOptions(ObjectPropertyRetrievalBehavior.All);
options.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered;

IObjectProjectionReader<EnterpriseManagementObject> reader =
mg.EntityObjects.GetObjectProjectionReader<EnterpriseManagementObject>(new ObjectProjectionCriteria(incidentProj), options);
EnterpriseManagementObjectProjection proj = reader.GetData(objectsToLoad)[0];
# powershell

$objId = [Guid]"c8144a24-444b-b721-d885-064ddf11d8b7"
    
$listType = [System.Collections.Generic.List``1]
$listGuid = $listType.MakeGenericType(([System.Guid]))

$tpCr = new-object Microsoft.EnterpriseManagement.Configuration.ManagementPackTypeProjectionCriteria("Name = 'System.WorkItem.Incident.ProjectionType'")
$projList = $mg.EntityTypes.GetTypeProjections($tpCr)
if($projList -and $projList.Count -gt 0) { $incidentProj = $projList[0] }

$objectsToLoad = new-object $listGuid.Fullname
$objectsToLoad.Add($objId)

$options = new-object Microsoft.EnterpriseManagement.Common.ObjectQueryOptions([Microsoft.EnterpriseManagement.Common.ObjectPropertyRetrievalBehavior]::All)
$options.ObjectRetrievalMode = [Microsoft.EnterpriseManagement.Common.ObjectRetrievalOptions]::Buffered

[Type[]]$MethodType = ([Microsoft.EnterpriseManagement.Common.ObjectProjectionCriteria],[Microsoft.EnterpriseManagement.Common.ObjectQueryOptions])
$GetObjectProjectionReader = $mg.EntityObjects.GetType().GetMethod("GetObjectProjectionReader",$MethodType)
$GetObjectProjectionReaderMethod = $GetObjectProjectionReader.MakeGenericMethod([Microsoft.EnterpriseManagement.Common.EnterpriseManagementObject])
[Microsoft.EnterpriseManagement.Common.ObjectProjectionCriteria]$Criteria = new-object Microsoft.EnterpriseManagement.Common.ObjectProjectionCriteria($incidentProj)
$reader = $GetObjectProjectionReaderMethod.Invoke($mg.EntityObjects, ([Microsoft.EnterpriseManagement.Common.ObjectProjectionCriteria]$Criteria, [Microsoft.EnterpriseManagement.Common.ObjectQueryOptions]$options))
$proj = $reader.GetData($objectsToLoad)[0]
write-host $proj.Object.Item($null, "Id")

Share

6 Comments

Hi there, has anyone received UnauthorizedAccessEnterpriseManagementException while trying to connect to the server with specified username and password?

Leave a Reply

Primary Sidebar

%d bloggers like this: