
Данная статья является справочной, и содержит в себе примеры кода на C# и PowerShell, которые могут понадобиться при работе с SCSM 2010 SP1 SDK.
Содержание
- 1 Подключение библиотеки SDK
- 2 Подключение к серверу SCSM
- 3 Подключение к серверу с указанием логина и пароля
- 4 Подключение к серверу с указанными языковыми настройками (UI)
- 5 Получение класса
- 6 Получение объекта по внутреннему ID (Guid)
- 7 Получение объектов по заданному критерию
- 8 Получение объектов по строковому критерию и классу
- 9 Получение объектов по XML-критерию
- 10 Получение объектов с заданным набором свойств
- 11 Получение объектов type projection
- 12 Получение type projection по ID объекта
- 13 Поделиться в соц. сетях
Подключение библиотеки SDK
Для подключения SDK требуется подключить библиотеку Microsoft.EnterpriseManagement.Core.dll. Она расположена в папке %PROGRAMFILES%\Microsoft System Center\Service Manager 2010\SDK Binaries\. Кроме этого, данная библиотека установлена в GAC (Global Assembly Cache) на всех компьютерах, где присутствует консоль SCSM (и естественно на всех серверах SCSM). В Visual Studio необходимо добавить эту библиотеку в Reference:
В PowerShell необходимо загрузить библиотеку с помощью метода [Reflection.Assembly]::LoadWithPartialName или LoadFile:
$InstallPath = "c:\Program Files\Microsoft System Center\Service Manager 2010\SDK Binaries\" $dll = "Microsoft.EnterpriseManagement.Core.dll" $dllPath = $InstallPath + $dl [reflection.assembly]::LoadFile($dllPath) | out-null
Если библиотека установлена в GAC можно использовать более короткую версию:
$dll = "Microsoft.EnterpriseManagement.Corel" [reflection.assembly]::LoadWithPartialName($dll) | out-null
Подключение к серверу SCSM
// C#
EnterpriseManagementGroup mg = new EnterpriseManagementGroup("serverName");
# PowerShell
$MG = new-object Microsoft.EnterpriseManagement.EnterpriseManagementGroup("serverName")
# можно сократить название типа (аналог using в C#)
$NS = "Microsoft.EnterpriseManagement"
$EMGType = "${NS}.EnterpriseManagementGroup"
$MG = new-object $EMGType "serverName"
Подключение к серверу с указанием логина и пароля
// 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
Подключение к серверу с указанными языковыми настройками (UI)
// 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
Получение класса
// по внутреннему ID (Guid)
ManagementPack mp = mg.ManagementPacks.GetManagementPack(new Guid("35D5DE4C-0284-4622-BB9C-97ADDE830136"));
// по имени
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
# по внутреннему ID (Guid)
$mp = $mg.ManagementPacks.GetManagementPack([Guid]"35D5DE4C-0284-4622-BB9C-97ADDE830136")
# по имени
$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]
}
Получение объекта по внутреннему ID (Guid)
Полезно при работе в workfow (здесь и далее подразумевается, что соединение с сервером установлено и переменная называется mg и $mg соответственно для C# и PowerShell).
// 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))
Получение объектов по заданному критерию
// C#
// получение по строковому критерию. Актуально только для Generic-свойств
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)
{
// работаем с объектом
}
}
# poweshell
# Если здесь не сделать жесткое приведение типов вожет возникнуть ошибка при вызове метода Invoke ниже:
# 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)
{
# работаем в объектом
}
Получение объектов по строковому критерию и классу
//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)
{
// работаем с объектом
}
}
}
# 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)
{
# работаем с объектом
}
}
Получение объектов по XML-критерию
// 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];
// Версия и токен всех системных пакетов совпадают.
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)
{
// работаем с объектом
}
}
}
# powershell
# обратите внимание на экранирование знака $, иначе $Context будет восприниматься как переменная
$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];
# Версия и токен всех системных пакетов совпадают.
[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)
{
# работаем с объектами
}
}
Получение объектов с заданным набором свойств
Полезно для уменьшения объема передаваемых данных при получении большого количества объектов. В примерах до этого формировался запрос вида SELECT * FROM Table, в примере ниже формируется запрос вида 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);
// если свойство находится в другом классе, текущий класс надо указывать явно
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)
{
// работаем с объектами
}
}
#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
# если свойство находится в другом классе, текущий класс надо указывать явно
$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)
{
# работаем с объектами
}
}
Получение объектов type projection
// 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;
// Если указать ObjectPropertyRetrievalBehavior.All, то для самого объекта будет возвращены только указанные свойства
// а для связанных объектов все свойства
ObjectQueryOptions options = new ObjectQueryOptions(ObjectPropertyRetrievalBehavior.All);
incidentCl.TryGetProperty("Id", out prop);
// если свойство находится в другом классе его надо указывать явно
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);
// или получить объекты со всеми свойствами
// 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)
# Если указать ObjectPropertyRetrievalBehavior.All, то для самого объекта будет возвращены только указанные свойства
# а для связанных объектов все свойства
$options = new-object Microsoft.EnterpriseManagement.Common.ObjectQueryOptions([Microsoft.EnterpriseManagement.Common.ObjectPropertyRetrievalBehavior]::None)
$prop = $null
$incidentCl.TryGetProperty("Id", [ref]$prop) | out-null
# если свойство находится в другом классе, текущий класс надо указывать явно
$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)
{
# обратите внимание, что способ получения свойств отличается от C#
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")
}
}
Получение type projection по ID объекта
Крайне полезно при работе в 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")