在C#中集成Powershell

时间:2014-08-25 20:11:31

标签: c# powershell scripting visual-studio-2013

需要将此PowerShell脚本集成到我的C#汇编代码中。不知道怎么做。如果需要任何其他信息,请不要犹豫。提前谢谢。

PowerShell脚本:

#Script that does the linking and renaming:

# Creates a variable called IncidentID and points Incident # to it for use within the script
Param(
[string]$IncidentID
)

# Load the SMlets module
Import-Module SMlets 

# Get the Incident Class
$IncClass = Get-SCSMClass -Name System.WorkItem.Incident$

# Get the RMA Class
$RMAClass = Get-SCSMClass -Name COMPANY.RMA.Class

# Build the Filter String
$FilterStr = "ID -eq " + $IncidentID

# Find the Incident we need to link to an RMA
$Inc = Get-SCSMObject -Class $IncClass -Filter $FilterStr
$RMAIncText = "[Linked to Incident " + $Inc.ID + "]"
$RMADescription = $RMAIncText 
New-SCSMObject -Class $RMAClass -PropertyHashtable (@{Title = $Inc.Title; Description = $RMADescription})

# Find the new RMA to be linked
$FilterStr = "Description -eq '$RMADescription'"
$RMA = Get-SCSMObject -Class $RMAClass -Filter $FilterStr

#Set RMA Number Variable
$RMANumber = $RMA.RMA_ID; 

#Clean up DisplayName, Title and Description  
$RMA | Set-SCSMObject -PropertyHashtable @{"DisplayName"  =  $RMANumber; "Title" =  $RMANumber; "Description" =  $RMANumber;}

## Create an Incident Related Items instance referencing the new RMA
$RWIClass = Get-SCSMRelationshipClass -Name System.WorkItemRelatesToWorkItem$
New-SCSMRelationshipObject -Relationship $RWIClass -Source $Inc -Target $RMA -Bulk

# Unload the SMlets module
Remove-Module SMlets

汇编代码:

public class RMATask : ConsoleCommand
    {
        public RMATask()
        {
        }
        public override void ExecuteCommand(IList<NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection<string> parameters)
        {
            IManagementGroupSession session = (IManagementGroupSession)FrameworkServices.GetService<IManagementGroupSession>();
            EnterpriseManagementGroup emg = session.ManagementGroup;

            ManagementPack mp = emg.ManagementPacks.GetManagementPack(new Guid("a82d62c5-ece0-35fd-a266-9afa246dea78"));
            ManagementPackClass mpc = emg.EntityTypes.GetClass(new Guid("4b081ab1-f48e-9c62-77bc-76bc31349030"));
            ManagementPackObjectTemplate mpt = emg.Templates.GetObjectTemplate(new Guid("92ed7c4d-aff5-819e-90f8-c92064c50cd6"));

            NavigationModelNodeBase nodeIn = nodes[0];

            NavigationModelNodeBase nmnbNew;
            NavigationModelNodeTask nmntNew = NavigationTasksHelper.CreateNewInstanceLink(mpc, mpt);
            Microsoft.EnterpriseManagement.GenericForm.GenericCommon.MonitorCreatedForm(nodeIn, nmntNew, out nmnbNew);
        }
    }

对于那些对这里的细节感兴趣的人,他们是: 问题 基本上,我们有帮助台分析师生成事件。有时,他们可能需要生成RMA(退货授权,如果您不知道这意味着什么,只知道这是他们需要填写的另一种形式),并且RMA需要与事件相关联。事件不需要有RMA,但每个RMA都需要附加到其相应的父事件上。

为此,我创建了一个名为COMPANY.RMA.Class的新类,在Visual Studio中从头开始创建了一个新表单,并将MP(管理包)XML和表单程序集(.dll)打包到MPB(管理包)中束)。 我将其上传到控制台,并创建了一个名为“创建RMA”的新控制台任务,该任务在选择事件模块时变得可见。

此任务将启动我的PowerShell脚本,该脚本将获取所选或打开的事件的ID,创建RMA对象,并将创建的RMA对象与事件的ID#相关联(以后可以看到它)在事件的“相关项目”选项卡中)。 但是,我遇到了一个问题。我正确地创建了链接功能,但是我无法让RMA表单在创建后自动打开。相反,当任务运行时,它会创建对象并保存它,但分析师必须关闭事件并重新打开它以刷新新数据,导航到“相关项”选项卡,然后选择要创建的新创建的RMA它并填写表格。这是一项额外的工作,应予以消除。 正确的功能应该是创建RMA表单,将其与打开/选定的事件相关联,然后启动刚刚创建的RMA表单以允许分析师填写其详细信息。

显然没有直接从控制台任务调用/启动表单的功能。看来我必须直接修改汇编代码才能访问SCSM SDK(我需要工作的层)。这就是我丢失的地方 - 我不知道如何将我的PowerShell脚本转换为C#汇编代码。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:6)

您可以使用PowerShell class在应用中托管PowerShell。

主机应用程序可以定义运行命令的运行空间,在本地或远程计算机上打开会话,并根据应用程序的需要同步或异步调用命令。 有指导here

答案 1 :(得分:0)

我最终解决了这个问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// using System.Threading.Tasks; <- .NET 4.5 only
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.ConnectorFramework;
// using Microsoft.EnterpriseManagement.UI.Core;
using Microsoft.EnterpriseManagement.UI.Extensions.Shared;
using Microsoft.EnterpriseManagement.UI.FormsInfra;
using Microsoft.EnterpriseManagement.UI.Core.Connection;
using Microsoft.EnterpriseManagement.UI.DataModel;
using Microsoft.EnterpriseManagement.UI.SdkDataAccess;
using Microsoft.EnterpriseManagement.UI.SdkDataAccess.DataAdapters;
using Microsoft.EnterpriseManagement.UI.WpfWizardFramework;
using Microsoft.EnterpriseManagement.ServiceManager.Application.Common;
using Microsoft.EnterpriseManagement.ConsoleFramework;
using Microsoft.EnterpriseManagement.GenericForm;
// using System.Management.Automation;
[assembly: CLSCompliant(true)]

namespace COMPANY.RMA
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>

    class RMATask : CreateWithLinkHandler
    {
        public RMATask()
        {


            try
            {
                // Sealed Class GUID
                this.createClassGuid = new Guid("9ebd95da-1b16-b9ea-274d-6b0c16ce1bf3");
                this.classToDelegate = new Dictionary<Guid, CreateLinkHelperCallback>()
                {
                    { ApplicationConstants.WorkItemTypeId, new CreateLinkHelperCallback (this.WorkItemCallback) }
                };
            }
            catch (Exception exc1)
            {
                MessageBox.Show(exc1.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void WorkItemCallback(IDataItem RMAForm, IDataItem IncidentForm)
        {
            try
            {
                // Note to self: RelatedWorkItems should be in MP XML as alias under TypeProjections
                if (RMAForm != null && RMAForm.HasProperty("RelatedWorkItems"))
                {
                    // Perform Linking
                    RMAForm["RelatedWorkItems"] = IncidentForm;
                    // Copy Incident Title to RMA Title
                    RMAForm["Title"] = IncidentForm["Title"];
                    // Copy Incident Description to RMA Description
                    RMAForm["Description"] = IncidentForm["Description"];
                }
            }
            catch (Exception exc2)
            {
                MessageBox.Show(exc2.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }