在C#中集成Powershell

本文关键字:Powershell 集成 | 更新日期: 2023-09-27 18:19:32

需要将此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#程序集代码。如有任何帮助,我们将不胜感激。

在C#中集成Powershell

您可以使用PowerShell类在应用程序中托管PowerShell。

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

我最终解决了这个问题。

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);
            }
        }
    }