Dell Feature Management Engine

Dell.FeatureManagement.Pack.PowerShellAPITaskProbe.FMPEngine (ProbeActionModuleType)

Element properties:

TypeProbeActionModuleType
IsolationAny
AccessibilityInternal
RunAsDefault
InputTypeSystem.BaseData
OutputTypeMicrosoft.Windows.SerializedObjectData

Member Modules:

ID Module Type TypeId RunAs 
PSP ProbeAction Microsoft.Windows.PowerShellProbe Default

Overrideable Parameters:

IDParameterTypeSelectorDisplay NameDescription
TimeoutSecondsint$Config/TimeoutSeconds$TimeoutTimeout
LogLevelint$Config/LogLevel$Log LevelDell FMP Powershell Task Logging
Forcebool$Config/Force$ForceForce

Source Code:

<ProbeActionModuleType ID="Dell.FeatureManagement.Pack.PowerShellAPITaskProbe.FMPEngine" Accessibility="Internal" Batching="false" PassThrough="false">
<Configuration>
<IncludeSchemaTypes>
<SchemaType>Dell.FeatureManagement.Pack.ImportMethod</SchemaType>
<SchemaType>Dell.FeatureManagement.Pack.MonitoringLevel</SchemaType>
</IncludeSchemaTypes>
<xsd:element minOccurs="1" name="ScriptName" type="xsd:string"/>
<xsd:element minOccurs="1" name="LogLevel" type="xsd:integer"/>
<xsd:element minOccurs="1" name="LogDirectory" type="xsd:string"/>
<xsd:element minOccurs="1" name="MPActionType" type="xsd:string"/>
<xsd:element minOccurs="1" name="TimeoutSeconds" type="xsd:integer"/>
<xsd:element minOccurs="1" name="Force" type="xsd:boolean"/>
<xsd:element minOccurs="1" name="addonarg1" type="xsd:string"/>
<xsd:element minOccurs="1" name="PreferredMethod" type="xsd:string"/>
</Configuration>
<OverrideableParameters>
<OverrideableParameter ID="TimeoutSeconds" Selector="$Config/TimeoutSeconds$" ParameterType="int"/>
<OverrideableParameter ID="LogLevel" Selector="$Config/LogLevel$" ParameterType="int"/>
<OverrideableParameter ID="Force" Selector="$Config/Force$" ParameterType="bool"/>
</OverrideableParameters>
<ModuleImplementation Isolation="Any">
<Composite>
<MemberModules>
<ProbeAction ID="PSP" TypeID="Windows!Microsoft.Windows.PowerShellProbe">
<ScriptName>$Config/ScriptName$</ScriptName>
<ScriptBody><Script>
# ------------------------------------------------------------------ #
# Script : Management Server Connection Script #
# Author: Vaideeswaran Ganesan ,Shailesh K V, Vignesh Pandian , Vijay kumar A T#
# (c) Copyright Dell Inc. 2012-2015. All rights reserved #
# ------------------------------------------------------------------ #

param($scriptname, $mpActionType, $logLevel, $logDirectory, $force, $addonarg1, $PreferredMethod)

# Get the existing culture information from the system
$OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
$OldUICulture = [System.Threading.Thread]::CurrentThread.CurrentUICulture

# Change the culture setting to en-US in order for the below powershell commands to execute using english locale
[Threading.Thread]::CurrentThread.CurrentCulture = "en-US"
[Threading.Thread]::CurrentThread.CurrentUICulture = "en-US"
if ($addonarg1 -eq $null)
{
$addonarg1 = "http://licensewebserver.company.com:8543/"
}

$addonarg1 = (($addonarg1 + "/") -replace '/+$', '/')
$addonarg2 = (($PreferredMethod + "/") -replace '/+$', '/')
$MSComputerName = (hostname)

$DebugScript = $false

#$logLevel= 1
#$logDirectory = "FMP_TESTING"

# Logging Header
If ($logLevel -ne 0)
{
$TempFolder = [environment]::GetEnvironMentVariable("temp","machine")
$LogLocation = $TempFolder + "\" + $logDirectory + "\"
If(!(Test-Path -path($TempFolder)))
{
# create the directory if not present
New-Item $TempFolder -type directory | Out-Null
}

If(!(Test-Path -path($LogLocation)))
{
# create the directory if not present
New-Item $LogLocation -type directory | Out-Null
}
$Global:LogFileLocation = $LogLocation + $scriptname + ".log"
If(!(Test-Path -path($LogFileLocation)))
{
# create the file if it does not exist
New-Item $LogFileLocation -type file | Out-Null
}
Else
{
$logFileSize = Get-ChildItem $LogFileLocation | ForEach-Object {($_.Length/1KB)}
If ($logFileSize -gt 512)
{
# existingLogFile is greater than 512 KB
$archiveTime = Get-Date -f "yyyy-MM-dd_HH.mm"
Rename-Item $LogFileLocation ("ArchivedLog_" + $scriptname + "_" + $archiveTime + ".log")
New-Item $LogFileLocation -type file | Out-Null
}
}
}

# -----------------------------------------------------------------------
# includes timestamp, msg and supports archiving over 512 KB
# ------------------------------------------------------------------------
Function psDebugLog
{
param($level, $message)
if (($level -gt 0) -and ($level -le $logLevel))
{
$currentTime = Get-Date -f "yyyy-MM-dd_HH.mm.ss"
Out-File -FilePath $LogFileLocation -InputObject ($currentTime + " :: " + $message) -Append
}
}


function Write-Info
{
param ([string] $msg)
psDebugLog -level 1 -message $msg
Write-Host $msg
}
function Write-WarningInfo
{
param ([string] $msg)
psDebugLog -level 1 -message $msg
Write-Host $msg
}
function Write-ErrorInfo
{
param ([string] $msg)
psDebugLog -level 1 -message $msg
Write-Host $msg
}

Write-Info -msg ("ActionType = " + $mpActionType)
# -----------------------------------------------------------------------------------
# Creating new SCE2010 Module - for connection to SCE and SCE task functionality
# -----------------------------------------------------------------------------------
$sce2010Interface = new-module {
[object]$connection = $null
[string] $state = ''
[string] $loglocation = '.\test.log'
[int] $logLevel = 1
[string] $product = "SCE 2010"

function Write-Info
{
param ([string] $msg)
#Write-Host $msg
}

Function psDebugLog
{
param($level, $message)
if (($level -gt 0) -and ($level -le $logLevel))
{
$currentTime = Get-Date -f "yyyy-MM-dd_HH.mm.ss"
Out-File -FilePath $this.loglocation -InputObject ($currentTime + " :: " + $message) -Append
}
}

function GetConnection()
{
$this.connection = [Microsoft.EnterpriseManagement.ManagementGroup]::connect("localhost")
$this.state = 'connected'
}

function LoadSnapins()
{
$regSCEPathValue = $null;
$regSCEPathValue = $(Get-ItemProperty "HKLM:\software\Microsoft\System Center Essentials\2.0\Setup\Components").installpath;
psDebugLog -level 1 -message ("SCE Path found = " + $regSCEPathValue)
[System.Reflection.Assembly]::LoadFile($regSCEPathValue + "\SDK Binaries\Microsoft.EnterpriseManagement.OperationsManager.Common.dll") &gt; $null
[System.Reflection.Assembly]::LoadFile($regSCEPathValue + "\SDK Binaries\Microsoft.EnterpriseManagement.OperationsManager.dll") &gt; $null
$this.state = 'snapins loaded'
}

Function GetManagementPacks()
{
return $this.connection.GetManagementPacks()
}

function InstallManagementPack($ImportPath)
{
$v = $null
try {
$this.connection.ImportManagementPack($ImportPath)
} catch {
$v = $_
}
return $v
}

function UninstallManagementPack($ManagementPack)
{
$this.connection.UninstallManagementPack($ManagementPack)
$v = $null
return $v
}

function PrintDebug()
{
Write-Info -msg ("Product: " + $this.Product)
Write-Info -msg ("State: " + $this.State)
}

function GetSCOMInstallDir()
{
return $(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft Operations Manager\3.0\Setup").InstallDirectory;
}

function GetManagementGroup()
{
return $this.connection
}

function IsSCE2010()
{
return $true
}

function IsSCOM2007R2()
{
return $false
}

function IsSCOM2012()
{
return $false
}

Function GetClassFriendlyName($className)
{
$monClasses=$this.connection.GetMonitoringClasses($className)
$monManagementPack=$monClasses[0]
return $monManagementPack.GetManagementPack().FriendlyName
}

Export-ModuleMember -function * -variable *
} -asCustomObject

# -----------------------------------------------------------------------------------
# Creating new SCOM2007 R2 Module - for connection to 2007R2 and 2007R2 task functionality
# -----------------------------------------------------------------------------------
$scom2007r2Interface = new-module {
[object]$connection = $null
[string] $state = ''
[string] $loglocation = '.\test.log'
[int] $logLevel = 1
[string] $product = "SCOM 2007 R2"

function Write-Info
{
param ([string] $msg)
psDebugLog -level 1 -message $msg
Write-Host $msg
}

Function psDebugLog
{
param($level, $message)
if (($level -gt 0) -and ($level -le $logLevel))
{
$currentTime = Get-Date -f "yyyy-MM-dd_HH.mm.ss"
Out-File -FilePath $this.loglocation -InputObject ($currentTime + " :: " + $message) -Append
}
}

function GetConnection()
{
$MachineRegErrorMsg = "Can not find Operations Manager Management Server name for the local machine.";
$UserRegKeyPath = "HKCU:\software\Microsoft\Microsoft Operations Manager\3.0\User Settings";
$MachineRegKeyPath = "HKLM:\software\Microsoft\Microsoft Operations Manager\3.0\Machine Settings";
$UserRegValueName = "SDKServiceMachine";
$MachineRegValueName = "DefaultSDKServiceMachine";
$ConnectingMsg = "Connecting to Operations Manager Management Server '{0}'.";
$ConnectErrorMsg = "Can not connect to Operations Manager Management Server '{0}'.";
$AccessDeniedErrorMsg = "Access is denied to Operations Manager Management Server '{0}'.";

$regKey = $null;
$regValue = $null;

# Set the initial server value to the MS argument.
# If the argument is empty the normal registry lookup sequence will kickin.
# If the argument is not empty the user will be connected to the specified connection.
$server = $null;

# Get the User Operations Manager Product Registry Key
if ($server -eq $null -or $server.Length -eq 0)
{
$regValue = Get-ItemProperty -path:$UserRegKeyPath -name:$UserRegValueName -ErrorAction:SilentlyContinue;

if ($regValue -ne $null)
{
$server = $regValue.SDKServiceMachine;
}
}

if ($server -eq $null -or $server.Length -eq 0)
{
# Get the Machine Operations Manager Product Registry Key if the user setting could not be found.
$regValue = Get-ItemProperty -path:$MachineRegKeyPath -name:$MachineRegValueName -ErrorAction:SilentlyContinue;

if ($regValue -ne $null)
{
$server = $regValue.DefaultSDKServiceMachine;
}
}

# If the default Operations Manager Management Server name can not be found in the registry then default to 'localhost'.
if ($server -eq $null -or $server.Length -eq 0)
{
psDebugLog -level 1 -message ($MachineRegErrorMsg)
$server = "localhost";
}

# Create a connection and make it the current location.
if ($server -ne $null -and $server.Length -gt 0)
{
# Format the connecting message.
$msg = $ConnectingMsg -f $server;
psDebugLog -level 1 -message ($msg)

# Create the new connection.
$error.Clear();
$this.connection = New-ManagementGroupConnection -ConnectionString:$server -ErrorAction:SilentlyContinue
psDebugLog -level 1 -message ("After : " + $msg)
if ($this.connection -ne $null)
{
psDebugLog -level 1 -message ("Connection Success! " + $this.connection)
}

# If the connection failed due to insufficient access then prompt for credentials.
if ($error.Count -gt 0 -and $error[0].Exception -is [Microsoft.EnterpriseManagement.Common.UnauthorizedAccessMonitoringException])
{
psDebugLog -level 1 -message ("Failed to connect")
$error.Clear();
}

if ($error.Count -gt 0 -and $error[0].Exception -is [Microsoft.EnterpriseManagement.Common.UnauthorizedAccessMonitoringException])
{
$errMsg = $AccessDeniedErrorMsg -f $server;
psDebugLog -level 1 -message $errMsg
}

if ($this.connection -eq $null)
{
$errMsg = $ConnectErrorMsg -f $server;
psDebugLog -level 1 -message $errMsg
}
}

if ($this.connection -ne $null)
{
psDebugLog -level 1 -message ("Setting to path: " + "OperationsManagerMonitoring::")
Set-Location "OperationsManagerMonitoring::"
psDebugLog -level 1 -message ("Current Directory: " + (pwd).Path)
psDebugLog -level 1 -message ("Setting to path: " + $server)
Set-Location $server;
psDebugLog -level 1 -message ("Current Directory: " + (pwd).Path)
}
$this.state = 'connected'
return $this.connection

}

function LoadSnapins()
{
$snapin = (Get-PsSnapin Microsoft.EnterpriseManagement.OperationsManager.Client -ErrorVariable $snapinerr -ErrorAction:SilentlyContinue)
if ($snapin -eq $null)
{
Add-PsSnapin Microsoft.EnterpriseManagement.OperationsManager.Client -ErrorVariable $snapinerr -ErrorAction:SilentlyContinue
if ($snapinerr -eq $null -or $snapinerr.Count -eq 0) {
# successful!
psDebugLog -level 1 -message "Snapin succeeded"
}
else
{
psDebugLog -level 1 -message "Snapin Failed"
psDebugLog -level 1 -message $snapinerr
}
}
$this.state = 'snapins loaded'
}

Function GetManagementPacks()
{
return (Get-ManagementPack)
}

function InstallManagementPack($ImportPath)
{
# $this.connection.ManagementGroup.ManagementPacks.ImportManagementPack($ImportPath)
Install-ManagementPack -filepath $ImportPath -ErrorAction:SilentlyContinue -ErrorVariable v
return $v
}

function UninstallManagementPack($ManagementPack)
{
Uninstall-ManagementPack -ManagementPack $ManagementPack -ErrorAction:SilentlyContinue -ErrorVariable v
return $v
}

function PrintDebug()
{
Write-Info -msg ("Product: " + $this.Product)
Write-Info -msg ("State: " + $this.State)
}

function GetSCOMInstallDir()
{
return $(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft Operations Manager\3.0\Setup").InstallDirectory;
}

function GetManagementGroup()
{
return $this.connection.ManagementGroup
}

function IsSCE2010()
{
return $false
}

function IsSCOM2007R2()
{
return $true
}

function IsSCOM2012()
{
return $false
}

Function GetClassDetails($className)
{
return (Get-MonitoringClass | where { $_.Name -eq $className })
}

Function GetClassFriendlyName($className)
{
$className = GetClassDetails($className)
$mpName = $className.GetManagementPack()
return $mpName.FriendlyName
}

Function EnableProyxingForInBandServers()
{
$scomAgents = get-agent | where {$_.ProxyingEnabled -match "False"}

$dellWindowsServerClass = Get-MonitoringClass -Name "Dell.WindowsServer.Server"
$dellWindowsServerInstances = Get-MonitoringObject -MonitoringClass $dellWindowsServerClass

if ($scomAgents -ne $null -And $dellWindowsServerInstances -ne $null -And $scomAgents.Count -ne 0 -And $dellWindowsServerInstances.Count -ne 0) {
psDebugLog -level 1 -message "Found Agent managed computers and Dell Servers (Agent-based). Both the lists are non-empty"
Write-Info -msg ("INFO: Enabling Agent proxying for Dell Servers (Agent-based)")

# create a dictionary of display name to the agent objects
$dispNameSCOMAgentMap = @{}
foreach ($agent in $scomAgents) {
if ($agent -ne $null) {
psDebugLog -level 1 -message "Adding Agent to display names map: " $agent.DisplayName
$dispNameSCOMAgentMap += @{$agent.DisplayName = $agent}
}
}

foreach ($dellServerInstance in $dellWindowsServerInstances) {
psDebugLog -level 1 -message $dellServerInstance.DisplayName + ":" + $dispNameSCOMAgentMap[$dellServerInstance.DisplayName]
if ($dispNameSCOMAgentMap[$dellServerInstance.DisplayName] -ne $null) {
psDebugLog -level 1 -message "Enabling Agent proxy for: " + $dellServerInstance.DisplayName + ":" + $dispNameSCOMAgentMap[$dellServerInstance.DisplayName]
$dispNameSCOMAgentMap[$dellServerInstance.DisplayName].ProxyingEnabled=$true
$dispNameSCOMAgentMap[$dellServerInstance.DisplayName].ApplyChanges()
}
else {
psDebugLog -level 1 -message $dispNameSCOMAgentMap[$dellServerInstance.DisplayName] + " is null"
}
}
}
else {
Write-Info -msg ("INFO: There are no Agent Managed computers or Dell Servers (Agent-based) that need Agent Proxying.")
psDebugLog -level 1 "There are no Agent Managed computers or Dell Servers (Agent-based)"
}
Write-Info -msg ("Done")
psDebugLog -level 1 "Done"
}

Export-ModuleMember -function * -variable *
} -asCustomObject

# -----------------------------------------------------------------------------------
# Creating new SCOM2012 Module - for connection to 2012 and 2012 task functionality
# -----------------------------------------------------------------------------------
$scom2012Interface = new-module {
[object]$connection = $null
[object]$mgmtGroup = $null
[string] $state = ''
[string] $loglocation = '.\test.log'
[int] $logLevel = 1
[string] $product = "SCOM 2012"

function Write-Info
{
param ([string] $msg)
psDebugLog -level 1 -message $msg
Write-Host $msg
}

Function psDebugLog
{
param($level, $message)
if (($level -gt 0) -and ($level -le $logLevel))
{
$currentTime = Get-Date -f "yyyy-MM-dd_HH.mm.ss"
Out-File -FilePath $this.loglocation -InputObject ($currentTime + " :: " + $message) -Append
}
}

function GetConnection()
{
$managementServerName = ""
$persistConnection = $false
$interactive = $false
$MachineRegErrorMsg = "Can not find Operations Manager Management Server name for the local machine.";
$UserRegKeyPath = "HKCU:\software\Microsoft\Microsoft Operations Manager\3.0\User Settings";
$MachineRegKeyPath = "HKLM:\software\Microsoft\Microsoft Operations Manager\3.0\Machine Settings";
$UserRegValueName = "SDKServiceMachine";
$MachineRegValueName = "DefaultSDKServiceMachine";
$ConnectingMsg = "Connecting to Operations Manager Management Server '{0}'.";
$ConnectErrorMsg = "Can not connect to Operations Manager Management Server '{0}'.";
$AccessDeniedErrorMsg = "Access is denied to Operations Manager Management Server '{0}'.";
$ConnectPromptMsg = "Enter the name of the Operations Manager Management Server to connect to.";
$ConnectPrompt = "Management Server";
$serviceNotRunningErrorMsg = "The Data Access service is either not running or not yet initialized. Check the event log for more information.";
$HostNotFoundErrorMsg = "No such host is known";

$regKey = $null;
$regValue = $null;

# Set the initial server value to the MS argument.
# If the argument is empty the normal registry lookup sequence will kickin.
# If the argument is not empty the user will be connected to the specified connection.
$server = $managementServerName;
$drive = $null;

# Get the User Operations Manager Product Registry Key
if ($server -eq $null -or $server.Length -eq 0)
{
$regValue = Get-ItemProperty -path:$UserRegKeyPath -name:$UserRegValueName -ErrorAction:SilentlyContinue;

if ($regValue -ne $null)
{
$server = $regValue.SDKServiceMachine;
}
}

if ($server -eq $null -or $server.Length -eq 0)
{
# Get the Machine Operations Manager Product Registry Key if the user setting could not be found.
$regValue = Get-ItemProperty -path:$MachineRegKeyPath -name:$MachineRegValueName -ErrorAction:SilentlyContinue;

if ($regValue -ne $null)
{
$server = $regValue.DefaultSDKServiceMachine;
}
}

# If the default Operations Manager Management Server name can not be found in the registry then default to 'localhost'.
if ($server -eq $null -or $server.Length -eq 0)
{
psDebugLog -level 1 -message $MachineRegErrorMsg
$server = "localhost";
}

# Create a connection and make it the current location.
$this.connection = $null;

if ($server -ne $null -and $server.Length -gt 0)
{
# Format the connecting message.
$msg = $ConnectingMsg -f $server;
psDebugLog -level 1 -message $msg

#Check if there are any exixting connections
$getState = Get-SCOMManagementGroupConnection -ComputerName: $server
if($getState.IsActive -eq "True")
{
$this.connection = $getState
$this.state = 'connected'
}
else
{
# Create the new connection.
$this.connection = New-SCOMManagementGroupConnection -ComputerName: $server -PassThru -ErrorAction:Stop
$this.state = 'connected'
}

}

$this.mgmtGroup = Get-SCOMManagementGroup
return $this.connection
}


function LoadSnapins()
{
Import-Module OperationsManager
$this.state = 'snapins loaded'
}

Function GetManagementPacks()
{
return (Get-SCManagementPack)
}

function InstallManagementPack($ImportPath)
{
Import-SCManagementPack $ImportPath -ErrorAction:SilentlyContinue -ErrorVariable v
#mgmtGroup.ManagementPacks.ImportManagementPack($ImportPath)
return $v
}

function UninstallManagementPack($ManagementPack)
{
Remove-SCManagementPack -ManagementPack $ManagementPack -ErrorAction:SilentlyContinue -ErrorVariable v
return $v
}

function GetSCOMInstallDir()
{
return $(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft Operations Manager\3.0\Setup").InstallDirectory;
}

function GetManagementGroup()
{
return $this.mgmtGroup
}

function IsSCE2010()
{
return $false
}

function IsSCOM2007R2()
{
return $false
}

function IsSCOM2012()
{
return $true
}

Function GetClassDetails($className)
{
return (Get-SCOMClass | where { $_.Name -eq $className })
}

Function GetClassFriendlyName($className)
{
$className = GetClassDetails($className)
$mpName = $className.GetManagementPack()
return $mpName.FriendlyName
}

Function EnableProyxingForInBandServers()
{
$scomAgents = Get-SCOMAgent | where {$_.ProxyingEnabled.Value -eq $False}

$dellWindowsServerClass = Get-SCOMClass -Name "Dell.WindowsServer.Server"
$dellWindowsServerInstances = Get-SCOMClassInstance -Class $dellWindowsServerClass

if ($scomAgents -ne $null -And $dellWindowsServerInstances -ne $null -And $scomAgents.Count -ne 0 -And $dellWindowsServerInstances.Count -ne 0) {
psDebugLog -level 1 -message "Found Agent managed computers and Dell Servers (Agent-based). Both the lists are non-empty"
Write-Info -msg ("INFO: Enabling Agent proxying for Dell Servers (Agent-based)")

# create a dictionary of display name to the agent objects
$dispNameSCOMAgentMap = @{}
foreach ($agent in $scomAgents) {
if ($agent -ne $null) {
psDebugLog -level 1 -message "Adding Agent to display names map: " $agent.DisplayName
$dispNameSCOMAgentMap += @{$agent.DisplayName = $agent}
}
}

foreach ($dellServerInstance in $dellWindowsServerInstances) {
psDebugLog -level 1 -message $dellServerInstance.DisplayName + ":" + $dispNameSCOMAgentMap[$dellServerInstance.DisplayName]
if ($dispNameSCOMAgentMap[$dellServerInstance.DisplayName] -ne $null) {
psDebugLog -level 1 -message "Enabling Agent proxy for: " + $dellServerInstance.DisplayName + ":" + $dispNameSCOMAgentMap[$dellServerInstance.DisplayName]
Enable-SCOMAgentProxy -Agent $dispNameSCOMAgentMap[$dellServerInstance.DisplayName]
}
else {
psDebugLog -level 1 -message $dispNameSCOMAgentMap[$dellServerInstance.DisplayName] + " is null"
}
}
}
else {
Write-Info -msg ("INFO: There are no Agent Managed computers or Dell Servers (Agent-based) that need Agent Proxying.")
psDebugLog -level 1 "There are no Agent Managed computers or Dell Servers (Agent-based)"
}
Write-Info -msg ("Done")
psDebugLog -level 1 "Done"
}

Export-ModuleMember -function * -variable *
} -asCustomObject

$dellMP = new-module {
function GetInstallDir()
{
return $(Get-ItemProperty "HKLM:\SOFTWARE\Dell\Dell Server Management Pack Suites").Path;
}

function GetEqualLogicInstallDir()
{
return $(Get-ItemProperty "HKLM:\SOFTWARE\Dell\Dell EqualLogic Storage Management Pack Suite").Path;
}

function GetTempDir($directory)
{
$TempFolder = [environment]::GetEnvironMentVariable("temp","machine")
$Location = $TempFolder + "\" + $directory + "\"
If (!(Test-Path -path($TempFolder)))
{
# create the directory if not present
New-Item $TempFolder -type directory | Out-Null
}

If(!(Test-Path -path($Location)))
{
# create the directory if not present
New-Item $Location -type directory | Out-Null
}
return $Location
}

function GetExportDir($suffix)
{
$expDir = $(GetTempDir("FMPInsUpgActionsExportDir"))
$expDir += $suffix


If(!(Test-Path -path($expDir)))
{
# create the directory if not present
New-Item $expDir -type directory | Out-Null
}

return $expDir;
}

function GetImportDir($impSuffix)
{
$impDir = $(GetInstallDir)
$fullPath = get-childitem $impDir -recurse -filter $impSuffix
if ($fullpath.Count -ne $null)
{
$impDir = $fullpath[0].FullName
}
else
{
$impDir = $fullPath.FullName
}

return $impDir;
}

function GetEqualLogicImportDir($impSuffix)
{
$impDir = $(GetEqualLogicInstallDir)
$fullPath = get-childitem $impDir -recurse -filter $impSuffix
if ($fullpath.Count -ne $null)
{
$impDir = $fullpath[0].FullName
}
else
{
$impDir = $fullPath.FullName
}

return $impDir;
}

function Get41ImportDir($impSuffix)
{
$impDir = 'C:\Dell Management Packs\Server Mgmt Suite\4.1'
$fullPath = get-childitem $impDir -recurse -filter $impSuffix
if ($fullpath.Count -ne $null)
{
$impDir = $fullpath[0].FullName
}
else
{
$impDir = $fullPath.FullName
}

return $impDir;
}

Export-ModuleMember -function * -variable *
} -asCustomObject


try {
Add-Type @'
public enum FMPActions
{
Delete,
Export,
DiscoveryRuleOverride,
AddConsoleTask,
Import,
OverrideTransfer,
SetPreferredMonitoringTask,
PrintMessage,
TransferOverrides,
CollectOverridesAction
}

public class FMPResponse
{
public bool operationSuccessful;
public object returnMessage;
public string recoveryActions;
}

public class FMPCommand
{
public FMPActions type;

public FMPResponse resp;
public bool RequiresOverrideMP;
public string mpname, mpdesc;
public System.Collections.Hashtable mprefs;
public FMPCommand()
{
RequiresOverrideMP = false;
mpname = ""; mpdesc = "";
mprefs = new System.Collections.Hashtable();
}

public void buildSuccessfulFMPResponseObject(string returnMessage)
{
resp = new FMPResponse();
resp.operationSuccessful = true;
resp.returnMessage = returnMessage;
resp.recoveryActions = "";
}
public void buildFailedFMPResponseObject(string returnMessage, string recoveryActions)
{
resp = new FMPResponse();
resp.operationSuccessful = false;
resp.returnMessage = returnMessage;
resp.recoveryActions = recoveryActions;
}
}

public class DeleteOptions : FMPCommand
{
public string mp;
public bool recurse;
public bool noexecute;
public DeleteOptions(string mp, bool recurse)
{
type = FMPActions.Delete;
this.mp = mp;
this.recurse = recurse;
this.noexecute = false;
}
public DeleteOptions(string mp, bool recurse, bool noexecute)
{
type = FMPActions.Delete;
this.mp = mp;
this.recurse = recurse;
this.noexecute = noexecute;
}
}

public class ExportOptions : FMPCommand
{
public string mp;
public string exportdir;
public bool recurse;
public ExportOptions(string mp, string s_exportdir)
{
type = FMPActions.Export;
this.mp = mp;
this.exportdir = s_exportdir;
this.recurse = false;
}
public ExportOptions(string mp, string s_exportdir, bool b_recurse) {
type = FMPActions.Export;
this.mp = mp;
this.exportdir = s_exportdir;
this.recurse = b_recurse;
}
}

public class ImportOptions : FMPCommand
{
public string mp;
public string importdir;
public bool recurse;
public string filename;
public ImportOptions(string mp, string s_importdir)
{
type = FMPActions.Import;
this.mp = mp;
this.importdir = s_importdir;
this.recurse = false;

}
public ImportOptions(string mp, string s_importdir, bool b_recurse) {
type = FMPActions.Import;
this.mp = mp;
this.importdir = s_importdir;
this.recurse = b_recurse;

}
}

public class AddConsoleTask : FMPCommand
{
public string taskTarget;
public string taskID;
public string application;
public string category;
public string taskName;
public string parameters;
public bool requireOutput;
public string workDirectory;
public AddConsoleTask() {}

public AddConsoleTask(string taskTarget, string taskID, string application, string category,
string taskName, string parameters, bool requireOutput, string workDirectory)
{
type = FMPActions.AddConsoleTask;
this.taskTarget = taskTarget;
this.taskID = taskID;
this.application = application;
this.category = category;
this.taskName = taskName;
this.parameters = parameters;
this.workDirectory = workDirectory;
this.requireOutput = requireOutput;
}
}

public class PrintMessage : FMPCommand
{
public string message;

public PrintMessage(string msg)
{
type = FMPActions.PrintMessage;
this.message = msg;
}
}

public class TransferOverrides : FMPCommand
{
public int Operation;
public CollectOverrides ovrds;

public TransferOverrides(int Operation, CollectOverrides ov1)
{
type = FMPActions.TransferOverrides;
this.Operation = Operation;
this.ovrds = ov1;
}
}

public class CollectOverrides : FMPCommand
{
public System.Collections.Hashtable collectfor;
public System.Collections.Hashtable depmps;
public System.Collections.Hashtable depoutmps;

public string exportdir;
public string outputdir;
public System.Collections.Generic.List&lt;string&gt; mps;
public System.Collections.Generic.List&lt;string&gt; mpnames;
public System.Collections.Generic.List&lt;string&gt; outmps;
public string autogensuffix;
public bool useAutoGenerated;

public CollectOverrides(string expDir, string outdir, bool useAutoGeneratedMP)
{
type = FMPActions.CollectOverridesAction;
this.exportdir = expDir;
this.outputdir = outdir;
this.mps = new System.Collections.Generic.List&lt;string&gt;();
this.mpnames = new System.Collections.Generic.List&lt;string&gt;();
this.outmps = new System.Collections.Generic.List&lt;string&gt;();
this.collectfor = new System.Collections.Hashtable();
this.depmps = new System.Collections.Hashtable();
this.depoutmps = new System.Collections.Hashtable();
this.autogensuffix = "";
this.useAutoGenerated = useAutoGeneratedMP;
}

public string CollectOverrideMPsFor(string mpname)
{
if (!collectfor.ContainsKey(mpname)) { collectfor.Add(mpname, "txt"); }
return mpname;
}

public string AddMPName(string mpname)
{
if (!depmps.ContainsKey(mpname)) {
mpnames.Add(mpname);
string mpxml = outputdir + "\\" + mpname + ".xml";
outmps.Add(mpxml);
depoutmps.Add(mpname, mpxml);
mpxml = exportdir + "\\" + mpname + ".xml";
mps.Add(mpxml);
depmps.Add(mpname, mpxml);
}
return (depmps[mpname]).ToString();
}

public string GetNewOutputFile(string mpname)
{
return (outputdir + "\\" + mpname + ".xml");
}
}

public class DiscoveryRuleOverride : FMPCommand
{
public string ruleTarget;
public string discovery;
public string overrideName;
public string overrideParameter;
public string overrideParameterValue;
public string overrideModule;

public DiscoveryRuleOverride()
{
}
public DiscoveryRuleOverride(string ruleTarget, string discovery, string overrideName, string overrideParameter, string overrideParameterValue, string overrideModule)
{
type = FMPActions.DiscoveryRuleOverride;
this.ruleTarget = ruleTarget;
this.discovery = discovery;
this.overrideName = overrideName;
this.overrideParameter = overrideParameter;
this.overrideParameterValue = overrideParameterValue;
this.overrideModule = overrideModule;
}
}

public class SetPreferredMonitoringTask : DiscoveryRuleOverride
{
public SetPreferredMonitoringTask(string method)
{
type = FMPActions.DiscoveryRuleOverride;
this.RequiresOverrideMP = true;
mpname = "Dell.PreferredMonitoringMethod.Override";
mpdesc = "Dell PreferredMonitoringMethod Override File";
this.ruleTarget = "Microsoft.SystemCenter.RootManagementServer";
this.discovery = "Dell.SetPreferredMonitoring.Discovery";
this.overrideName = "SetPreferredMonitoringMethod";
this.overrideParameter = "SetPreferredMonitoringMethod";
this.overrideParameterValue = method;
this.overrideModule = "SPMDiscovery";
}
}

'@
}
catch [Exception] {
$_ | fl * -Force
}

function getExceptionDetails
{
param ($except)
$exp = $except.Exception

$message = $exp.Message
while ($exp -ne $null)
{
$inmsg = $exp.Message
if ($inmsg -notmatch "See inner exception") {
$message = $inmsg
break
}
$exp = $exp.InnerException
}
$message
}

function chkMSOOBTemplatePresence
{
$oobMSTemplatePresentFlag = "False"
# check for presence of Microsoft OOB template and exit if not imported
$scomenv.GetManagementPacks() | foreach -process{
if($_.Name -eq 'Microsoft.SystemCenter.OutofBand.SMASH.Library')
{
$oobMSTemplatePresentFlag = "True"
}
}
# check for presence of Microsoft OOB template - if false, give MSFT download location
if (($oobMSTemplatePresentFlag) -eq "False")
{
Write-Info -msg ("ERROR: Please download and manually import the Microsoft System Center Out of Band Library")
Write-Info -msg ("This Library can be downloaded from http://go.microsoft.com/fwlink/?LinkID=244308")
Write-Info -msg ("This library is a pre-requisite for the Dell Agent-free Server Management Feature. Please retry this task after the library import.")
}
return $oobMSTemplatePresentFlag;
}
#--------------------------------------------------------------------------------
# Function to create override and import MP to refresh the Dashboard
# When the Task is Ran
#--------------------------------------------------------------------------------
Function CreateFMPDashboardRefreshOverride
{
$TempLocation = [environment]::GetEnvironMentVariable("temp","machine") +"\"

$FMPIntervalSeconds = (Get-Random -Minimum 84000 -Maximum 90000)

$TemplateFMPDashboardRefresherOverride = '
&lt;ManagementPack ContentReadable="true" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
&lt;Manifest&gt;
&lt;Identity&gt;
&lt;ID&gt;Dell.FeatureManagement.TaskRefresher&lt;/ID&gt;
&lt;Version&gt;1.0.0.0&lt;/Version&gt;
&lt;/Identity&gt;
&lt;Name&gt;Dell.FeatureManagement.TaskRefresher&lt;/Name&gt;
&lt;References&gt;
&lt;Reference Alias="SystemCenter"&gt;
&lt;ID&gt;Microsoft.SystemCenter.Library&lt;/ID&gt;
&lt;Version&gt;6.1.7221.0&lt;/Version&gt;
&lt;PublicKeyToken&gt;31bf3856ad364e35&lt;/PublicKeyToken&gt;
&lt;/Reference&gt;
&lt;Reference Alias="FeatureManagement"&gt;
&lt;ID&gt;Dell.FeatureManagement.Pack&lt;/ID&gt;
&lt;Version&gt;5.2.0.0&lt;/Version&gt;
&lt;PublicKeyToken&gt;f5205f5754b55108&lt;/PublicKeyToken&gt;
&lt;/Reference&gt;
&lt;/References&gt;
&lt;/Manifest&gt;
&lt;Monitoring&gt;
&lt;Overrides&gt;
&lt;DiscoveryConfigurationOverride ID="OverridingOf.Dell.FeatureManagement.Interval" Context="SystemCenter!Microsoft.SystemCenter.ManagementServer" Enforced="false" Discovery="FeatureManagement!Dell.FMPHostMgmtServer.Discovery" Parameter="IntervalSeconds" Module="FMPHost"&gt;
&lt;Value&gt;FMPIntervalSeconds&lt;/Value&gt;
&lt;/DiscoveryConfigurationOverride&gt;
&lt;/Overrides&gt;
&lt;/Monitoring&gt;
&lt;LanguagePacks&gt;
&lt;LanguagePack ID="ENU" IsDefault="false"&gt;
&lt;DisplayStrings&gt;
&lt;DisplayString ElementID="Dell.FeatureManagement.TaskRefresher"&gt;
&lt;Name&gt;Dell.FeatureManagement.TaskRefresher&lt;/Name&gt;
&lt;/DisplayString&gt;
&lt;/DisplayStrings&gt;
&lt;/LanguagePack&gt;
&lt;/LanguagePacks&gt;
&lt;/ManagementPack&gt;'

$TemplateFMPDashboardRefresherOverride = $TemplateFMPDashboardRefresherOverride.Replace("FMPIntervalSeconds", $FMPIntervalSeconds)
$FMPDashboardRefreshMP = $TempLocation + "Dell.FeatureManagement.TaskRefresher.xml"
$TemplateFMPDashboardRefresherOverride | Out-File -FilePath ($FMPDashboardRefreshMP)
$v = $scomenv.InstallManagementPack($FMPDashboardRefreshMP)
if ($v -eq $null -or $v.Count -eq 0)
{
Write-Info -msg ("Success")
}
else
{
$msg = getExceptionDetails -except $v
if ($msg -match "already imported")
{
Write-Info -msg ("INFO: " + $f.mp + " is already imported")
}
elseif ($msg -match "timeout period elapsed prior to completion of the operation")
{
Write-Info -msg ("ERROR: SCOM Database timeout occurred. You may need to run the task again.")
}
else
{
Write-Info -msg ("ERROR: There were errors in the command.")
Write-Info -msg ("ERROR: " + $msg)
}
}

}

# -----------------------------------------------------------------------
# Check if MP is present or not and return true/false
# ------------------------------------------------------------------------
Function chkMPPresence($mp_string)
{
$mpPresent = $false
$scomenv.GetManagementPacks() | foreach -process {
if($_.Name -eq $mp_string)
{
$mpPresent = "True"
}
}
return $mpPresent
}

# -----------------------------------------------------------------------
# Get if MP is present or not and return null
# ------------------------------------------------------------------------
Function GetMPDetails($mpname)
{
$ret = $scomenv.GetManagementPacks() | where { $_.Name -eq $mpname }
return $ret
}

Function Write-Debug-Msg
{
param($msg)
# Write-Host ("DEBUG :" + $msg)
}

Function Write-Info-Msg
{
param($msg)
# Write-Host ("INFO :" + $msg)
}

Function RenameManifestReference
{
param($overriddenXmlFile,[string]$id,[string]$newid,[string]$version,[string]$publickey)
Write-Debug-Msg -msg ( "RenameManifestReference")
Write-Debug-Msg -msg ( " id to be changed=$id")
Write-Debug-Msg -msg ( " newid=$newid")
Write-Debug-Msg -msg ( " version=$version")
Write-Debug-Msg -msg ( " publickey=$publickey")

$IsRefPresent=$overriddenXmlFile.ManagementPack.Manifest.References.Reference | Where{ ($_.ID -eq $newId)}
if(![string]::IsNullOrEmpty($IsRefPresent))
{
Write-Debug-Msg -msg ( " $newid is already present! Replacing")
}
else
{
Write-Debug-Msg -msg ( " $newid is not present.")
}
$IsRefNode=$overriddenXmlFile.ManagementPack.Manifest.References.Reference | Where{ ($_.ID -eq $id)}

If(![string]::IsNullOrEmpty($IsRefNode))
{
Write-Debug-Msg -msg ( " $id is present. Doing Replacement...")
$IsRefNode.SelectSingleNode("ID").InnerText=$newId
$IsRefNode.SelectSingleNode("Version").InnerText=$version
$IsRefNode.SelectSingleNode("PublicKeyToken").InnerText=$publickey
Write-Debug-Msg -msg ( " Done")
}
else
{
Write-Debug-Msg -msg ( "ERROR: $id is not present!")
}
}

Function CreateReferenceIfNotExists
{
PARAM($overriddenXmlFile,[string]$newid,$version,$publickey)
Write-Debug-Msg -msg ( "CreateRefenceIfNotExists")
Write-Debug-Msg -msg ( " newid=$newid")
Write-Debug-Msg -msg ( " version=$version")
Write-Debug-Msg -msg ( " publickey=$publickey")
$refer = $overriddenXmlFile.ManagementPack.Manifest.References
$AliasName =$newid.Replace('.','')
Write-Debug-Msg -msg ( " alias=$AliasName")

$matchedNodes = $overriddenXmlFile.ManagementPack.Manifest.References.ChildNodes | Where{ ($_.ID -eq $newid) }
If([string]::IsNullOrEmpty($matchedNodes))
{
Write-Debug-Msg -msg ( " (not found. Creating new)")
$newNode = $overriddenXmlFile.CreateElement("Reference")
$newNode.SetAttribute("Alias",$AliasName)

$newRefId=$overriddenXmlFile.CreateElement("ID")
$newRefId.psbase.InnerText = $newid
$child = $newNode.AppendChild($newRefId)
$newVersion=$overriddenXmlFile.CreateElement("Version")
$newVersion.psbase.InnerText = $version
$child = $newNode.AppendChild($newVersion)
$newToken=$overriddenXmlFile.CreateElement("PublicKeyToken")
$newToken.psbase.InnerText = $publickey
$child = $newNode.AppendChild($newToken)
$addchild = $overriddenXmlFile.ManagementPack.Manifest.References.AppendChild($newNode)
Write-Debug-Msg -msg ( " Done")
}
else
{
Write-Debug-Msg -msg ( " (already found. Skipping!)")
}
}

Function GetMPAliasName()
{
param($refMpName,$overriddenXmlFile)
$refer = $overriddenXmlFile.ManagementPack.Manifest.References
$matchedNodes = $overriddenXmlFile.ManagementPack.Manifest.References.ChildNodes | Where{ ($_.ID -eq $refMpName) }
if (![string]::IsNullOrEmpty($matchedNodes))
{
return ($matchedNodes.Alias)
}

return $null
}

function RemoveSecureReferences
{
param ($overriddenXmlFile, $alias)
$removeNodes = @()
foreach ($ovr in $overriddenXmlFile.ManagementPack.Monitoring.Overrides.ChildNodes)
{
if ($ovr.SecureReference -ne $null -and $ovr.SecureReference -match ($alias + "!"))
{
$removeNodes += @($ovr)
}
elseif ($ovr.Context -ne $null -and $ovr.Context -match ($alias + "!"))
{
$removeNodes += @($ovr)
}
}
foreach ($nd in $removeNodes)
{
$languagePackToRemove= $overriddenXmlFile.ManagementPack.LanguagePacks.LanguagePack.DisplayStrings.ChildNodes | where {$_.ElementID -eq $nd.ID}
If($languagePackToRemove -ne $null)
{
foreach ($lpNode in $languagePackToRemove)
{
Write-Debug-Msg -msg ("Removing display string : "+$lpNode.Name)
$ignoreReturn = $overriddenXmlFile.ManagementPack.LanguagePacks.LanguagePack.DisplayStrings.RemoveChild($lpNode)
}
}
Write-Debug-Msg -msg (" Removing Monitor : "+$nd.ID + " (Parameter:"+ $nd.Parameter +")")
$ignoreReturn = $overriddenXmlFile.ManagementPack.Monitoring.Overrides.RemoveChild($nd)
}
}

function ChangeTargetAndIDPrefix
{
param($overriddenXmlFile,$cmcModelAlias,$cmcOM07Alias, $replText)
if (($ovr.Discovery -ne $null) -and ($ovr.Discovery.StartsWith($cmcModelAlias + "!")))
{
$disClassArray=$ovr.Discovery.Split('!')
$ovr.Discovery = $cmcOM07Alias+"!"+$disClassArray[1]
#$ovr.Discovery = ($ovr.Discovery -replace $cmcModelAlias, $cmcOM07Alias)
if ($replText -ne $null)
{
$ovr.Discovery= ([string]$ovr.Discovery).Replace($key, $replText)
}
}
if (($ovr.Monitor -ne $null) -and ($ovr.Monitor.StartsWith($cmcModelAlias + "!")))
{
$monitorClassArray=$ovr.Monitor.Split('!')
$ovr.Monitor = $cmcOM07Alias+"!"+$monitorClassArray[1]
#$ovr.Monitor = ($ovr.Monitor -replace $cmcModelAlias, $cmcOM07Alias)
if ($replText -ne $null)
{
$ovr.Monitor= ([string]$ovr.Monitor).Replace($key, $replText)
}
}
if (($ovr.Rule -ne $null) -and ($ovr.Rule.StartsWith($cmcModelAlias + "!")))
{
$RuleClassArray=$ovr.Rule.Split('!')
$ovr.Rule = $cmcOM07Alias+"!"+$RuleClassArray[1]
#$ovr.Rule = ($ovr.Rule -replace $cmcModelAlias, $cmcOM07Alias)
if ($replText -ne $null)
{
$ovr.Rule = ([string]$ovr.Rule ).Replace($key, $replText)
}
}
if (($ovr.SecureReference -ne $null) -and ($ovr.SecureReference.StartsWith($cmcModelAlias + "!")))
{
$secureReferenceArray=$ovr.Rule.Split('!')
$ovr.SecureReference = $cmcOM07Alias+"!"+$secureReferenceArray[1]
#$ovr.SecureReference = ($ovr.SecureReference -replace $cmcModelAlias, $cmcOM07Alias)
if ($replText -ne $null)
{
$ovr.SecureReference = ([string]$ovr.SecureReference).Replace($key, $replText)
}
}
}

function ChangeTargetAndIDPrefixAndAddProperty
{
param($overriddenXmlFile,[string]$cmcModelAlias,[string]$cmcOM07Alias)
if (($ovr.Discovery -ne $null) -and ($ovr.Discovery.StartsWith($cmcModelAlias + "!")))
{
$disClassArray=$ovr.Discovery.Split('!')
$ovr.Discovery = $cmcOM07Alias+"!"+$disClassArray[1]
#$ovr.Discovery = ($ovr.Discovery -replace $cmcModelAlias, $cmcOM07Alias)
}
if (($ovr.Monitor -ne $null) -and ($ovr.Monitor.StartsWith($cmcModelAlias + "!")))
{
$monitorClassArray=$ovr.Monitor.Split('!')
$ovr.Monitor = $cmcOM07Alias+"!"+$monitorClassArray[1]
#$ovr.Monitor = ($ovr.Monitor -replace $cmcModelAlias, $cmcOM07Alias)
}
if (($ovr.Rule -ne $null) -and ($ovr.Rule.StartsWith($cmcModelAlias + "!")))
{
$ruleClassArray=$ovr.Rule.Split('!')
$ovr.Rule = $cmcOM07Alias+"!"+$ruleClassArray[1]
#$ovr.Rule = ($ovr.Rule -replace $cmcModelAlias, $cmcOM07Alias)
}
if (($ovr.SecureReference -ne $null) -and ($ovr.SecureReference.StartsWith($cmcModelAlias + "!")))
{
$secureReferenceArray=$ovr.Rule.Split('!')
$ovr.SecureReference = $cmcOM07Alias+"!"+$secureReferenceArray[1]
#$ovr.SecureReference = ($ovr.SecureReference -replace $cmcModelAlias, $cmcOM07Alias)
}
}

function ReplaceGlobalGroups
{
param ($infile, $outfile)
$xmldata = (Get-Content $infile)
$xmlfile = [xml]$xmldata
$clsids = @()
if ($xmlfile.ManagementPack.TypeDefinitions.EntityTypes.ClassTypes.ClassType -ne $null)
{
foreach ($cls in $xmlfile.ManagementPack.TypeDefinitions.EntityTypes.ClassTypes.ClassType)
{
$clsids += @($cls.ID)
Write-Info -msg ("Found a class definition: "+ $cls.ID)
}

foreach ($clsid in $clsids)
{
$xmldata = $xmldata -replace $clsid, ($clsid + "_OM12")
}
}
$xmlfile = [xml]$xmldata
$xmlfile.Save($outfile)
}

#Rashma
Function UpgradeCustomGroups
{
param($overriddenXmlFile, $f)
$removeGrpNodes = @()
foreach ($ovr in $overriddenXmlFile.ManagementPack.Monitoring.Discoveries.ChildNodes)
{
#$ovr.DataSource.MembershipRules.MembershipRule.MonitoringClass
$id = $null
$aliasName=$null
if ($ovr.DataSource.MembershipRules.MembershipRule.MonitoringClass -ne $null)
{
$ids = ($ovr.DataSource.MembershipRules.MembershipRule.MonitoringClass -replace '.*!', '')
$id = $ids -replace '".*', ''
if($f['RenameWorkflows'].ContainsKey($id))
{
$ovr.DataSource.MembershipRules.MembershipRule.MonitoringClass= $ovr.DataSource.MembershipRules.MembershipRule.MonitoringClass -replace $id, $f['RenameWorkflows'][$id]
}
}
if ( ($id -ne $null) -and ($f['RemoveWorkflows'].ContainsKey($id) ))
{
$removeGrpNodes += @($ovr)
}
}

foreach ($nd in $removeGrpNodes)
{
$languagePackToRemove= $overriddenXmlFile.ManagementPack.LanguagePacks.LanguagePack.DisplayStrings.ChildNodes | where {$_.ElementID -eq $nd.ID}
If($languagePackToRemove -ne $null)
{
foreach ($lpNode in $languagePackToRemove)
{
$ignoreReturn = $overriddenXmlFile.ManagementPack.LanguagePacks.LanguagePack.DisplayStrings.RemoveChild($lpNode)
}
}
$ignoreReturn = $overriddenXmlFile.ManagementPack.Monitoring.Discoveries.RemoveChild($nd)
}
}

Function TransferMPOverrides
{
param($fileContentPath, $outputFile, $inputs)

$overriddenXmlFile=[xml](Get-Content $fileContentPath)

$removeNodes = @()
$mpAliasNames = @{}
$defaultMP = ""
foreach ($f in $inputs)
{
switch($f['command'])
{
'SetDefaultMP' { $defaultMP = $f['id'] }
'ProcessOverrides' {
$workflowmap = @{}
foreach ($ovr in $overriddenXmlFile.ManagementPack.Monitoring.Overrides.ChildNodes)
{
$id = $null
$aliasName=$null
$contextId= $null
if ($ovr.Context -match "Microsoft.SystemCenter.NetworkDevice" -and $f['UseNetworkStack'] -eq 'SCOM12')
{
Write-Debug-Msg -msg ("Replacing SCOM07 network stack")
$ovr.Context = $ovr.Context -replace "!Microsoft.SystemCenter.NetworkDevice", "!System.NetworkManagement.Node"
}
else
{
$contextId= ($ovr.Context -replace '.*!', '')
if($f['RenameWorkflows'].ContainsKey($contextId))
{
$ovr.Context= $ovr.Context -replace $contextId, $f['RenameWorkflows'][$contextId]
}

}
if($ovr.Discovery -ne $null)
{
$id = ($ovr.Discovery -replace '.*!', '')
if($f['RenameWorkflows'].ContainsKey($id))
{
$ovr.Discovery= $ovr.Discovery -replace $id, $f['RenameWorkflows'][$id]
}
}
elseif($ovr.Monitor -ne $null)
{
$id = ($ovr.Monitor -replace '.*!', '')
if($f['RenameWorkflows'].ContainsKey($id))
{
$ovr.Monitor = $ovr.Monitor -replace $id, $f['RenameWorkflows'][$id]
}
}
elseif($ovr.Rule -ne $null)
{
$id = ($ovr.Rule -replace '.*!', '')
if($f['RenameWorkflows'].ContainsKey($id))
{
$ovr.Rule = $ovr.Rule -replace $id, $f['RenameWorkflows'][$id]
}
}
elseif ($ovr.SecureReference -ne $null)
{
$id = $ovr.ID
}

if (($id -ne $null) -and $f['ChangeTargetIds'].ContainsKey($id) -eq $true)
{
Write-Debug-Msg -msg (" Processing Discovery/Monitor: " + $id)
$aliasName=GetMPAliasName -refMpName $f['ChangeTargetIds'][$id] -overriddenXmlFile $overriddenXmlFile
Write-Debug-Msg -msg (" change alias from : " + $mpAliasNames[$defaultMP])
Write-Debug-Msg -msg (" to : " + $aliasName)
ChangeTargetAndIDPrefix -overriddenXmlFile $overriddenXmlFile -id $id -cmcModelAlias $mpAliasNames[$defaultMP] -cmcOM07Alias $aliasName
Write-Debug-Msg -msg (" Done")
}
foreach($key in $f['ChangeMatchingTargetIds'].Keys)
{
if($id -match $key)
{
Write-Debug-Msg -msg $f['ChangeMatchingTargetIds'][$key]['alias'] ]
$aliasName = $mpAliasNames[ $f['ChangeMatchingTargetIds'][$key]['alias'] ]
$replText = $f['ChangeMatchingTargetIds'][$key]['text']
Write-Debug-Msg -msg (" Processing Rule : " + $id)
Write-Debug-Msg -msg (" change alias from : " + $mpAliasNames[$defaultMP])
Write-Debug-Msg -msg (" to : " + $aliasName)
ChangeTargetAndIDPrefix -id $id -replText $replText -cmcModelAlias $mpAliasNames[$defaultMP] -cmcOM07Alias $aliasName -overriddenXmlFile $overriddenXmlFile
Write-Debug-Msg -msg (" Done")
}
}

$mapkey = $ovr.Context + "&lt;&gt;"
if($ovr.Discovery -ne $null)
{
$mapkey += $ovr.Discovery
}
elseif($ovr.Monitor -ne $null)
{
$mapkey += $ovr.Monitor
}
elseif($ovr.Rule -ne $null)
{
$mapkey += $ovr.Rule
}
elseif($ovr.SecureReference -ne $null)
{
$mapkey += $ovr.ID
}

$isAddedToRemovedList = $false
if ($ovr.Parameter -ne $null) { $mapkey += "&lt;&gt;" + $ovr.Parameter }
if ($ovr.Property -ne $null) { $mapkey += "&lt;&gt;" + $ovr.Property }
if ($workflowmap.ContainsKey($mapkey) -eq $true)
{
$isAddedToRemovedList = $true
Write-Info-Msg -msg (" Duplicate Rule/Discovery/Monitor " +$mapkey + " will be removed")
$removeNodes += @($ovr)
}
else
{
$workflowmap += @{ $mapkey = $ovr }
}

if ($id -eq $null) { continue }
if (($id -ne $null) -and ($f['RemoveWorkflows'].ContainsKey($id) -and ($isAddedToRemovedList -eq $false)))
{
Write-Info-Msg -msg (" Rule/Discovery/Monitor " +$id + " will be removed")
$removeNodes += @($ovr)
}
elseif (($id -ne $null) -and ($f['RemoveOverrideParameters'].ContainsKey($id)))
{
$params=$f['RemoveOverrideParameters'][$id]
if ( ($ovr.Parameter -ne $null -and $params.Contains($ovr.Parameter)) -or
($ovr.Property -ne $null -and $params.Contains($ovr.Property)) )
{
Write-Debug-Msg -msg (" Rule/Discovery/Monitor " +$id + " will be removed")
if ($isAddedToRemovedList -eq $false) { $removeNodes += @($ovr) }
}
}
elseif (($contextId -ne $null) -and ($f['RemoveWorkflows'].ContainsKey($contextId)) -and ($isAddedToRemovedList -eq $false))
{
#Write-Info-Msg -msg (" Rule/Discovery/Monitor " +$id + " will be removed")
$removeNodes += @($ovr)
}
}
#Rashma

UpgradeCustomGroups -overriddenXmlFile $overriddenXmlFile -f $f

Write-Debug-Msg -msg ("All Override Processing Done")
}
'RenameMPID' {
$overriddenXmlFile.ManagementPack.Manifest.Identity.ID = $f['newid']
$renmpid = $f['newid']
foreach ($langpack in $overriddenXmlFile.ManagementPack.LanguagePacks.LanguagePack)
{
$displayString = $langpack.DisplayStrings.ChildNodes | Where {$renmpid -match $_.ElementID}
if ($displayString -ne $null)
{
$displayString.ElementID = $renmpid
if (($displayString.FirstChild.InnerText -match "OM12") -eq $false)
{
$displayString.FirstChild.InnerText += " (OM12)"
}
}
$kbarticle = $langpack.KnowledgeArticles.ChildNodes | Where {$renmpid -match $_.ElementID}
if ($kbarticle -ne $null)
{
$kbarticle.ElementID = $renmpid
}
}
}
'GetMPAliasName' {
if ($mpAliasNames.ContainsKey($f['id']) -eq $false)
{
$oldAlias = GetMPAliasName -refMpName $f['id'] -overriddenXmlFile $overriddenXmlFile
$mpAliasNames += @{ $f['id'] = $oldAlias}
}
}
'RenameManifestReference' {
RenameManifestReference -overriddenXmlFile $overriddenXmlFile -id $f['id'] -newid $f['newid'] -version $f['version'] -publickey $f['publickey']
}
'CreateReferenceIfNotExists' {
CreateReferenceIfNotExists -overriddenXmlFile $overriddenXmlFile -newid $f['newid'] -version $f['version'] -publickey $f['publickey']
}
}
}

foreach ($nd in $removeNodes)
{
$languagePackToRemove= $overriddenXmlFile.ManagementPack.LanguagePacks.LanguagePack.DisplayStrings.ChildNodes | where {$_.ElementID -eq $nd.ID}
If($languagePackToRemove -ne $null)
{
foreach ($lpNode in $languagePackToRemove)
{
Write-Debug-Msg -msg ("Removing display string : "+$lpNode.Name)
$ignoreReturn = $overriddenXmlFile.ManagementPack.LanguagePacks.LanguagePack.DisplayStrings.RemoveChild($lpNode)
}
}
Write-Debug-Msg -msg (" Removing Monitor : "+$nd.ID + " (Parameter:"+ $nd.Parameter +")")
$ignoreReturn = $overriddenXmlFile.ManagementPack.Monitoring.Overrides.RemoveChild($nd)
}
Write-Info -msg (" Saving to " + $outputFile)
$overriddenXmlFile.Save($outputFile + ".tmp")
ReplaceGlobalGroups -infile ($outputFile + ".tmp") -outfile $outputFile
}

function RecurseRemove
{
param($parent, [ref]$ids, $alias)
if ($parent.ChildNodes -eq $null)
{
#Write-Host ($parent.Name + " has no more children")
return 0
}
$MatchingChilds = $parent.ChildNodes | Where { ($_.Target -ne $null -and $_.Target -match ($alias + "!")) -or
($_.Context -ne $null -and $_.Context -match ($alias + "!")) -or
($_.Discovery -ne $null -and $_.Discovery -match ($alias + "!")) -or
($_.Rule -ne $null -and $_.Rule -match ($alias + "!")) -or
($_.SecureReference -ne $null -and $_.SecureReference -match ($alias + "!")) -or
($_.Monitor -ne $null -and $_.Monitor -match ($alias + "!")) -or
($_.Alias -ne $null -and $_.Alias -eq $alias )
}

foreach($child in $MatchingChilds)
{
If(($child -ne $null) -and ($parent -ne $null) -and ![string]::IsNullOrEmpty($child.ID))
{
#write-host ("Delete child -- (Name:ID): " + $child.Name + " : " + $child.ID)
($ids.value) += @{ $child.ID = $child.Name }
$parent.RemoveChild($child)
}
}

foreach ($child in $parent.ChildNodes)
{
RecurseRemove -parent $child -ids $ids -alias $alias
}
}


function RemoveLangPacks
{
param ($parent, [ref]$ids)
foreach ($langpack in $parent.LanguagePacks.LanguagePack)
{
if ($langpack.DisplayStrings.DisplayString -ne $null)
{
foreach ($disp in $langpack.DisplayStrings.DisplayString)
{
if (($ids.value).ContainsKey($disp.ElementID))
{
$langpack.DisplayStrings.RemoveChild($disp)
}
}
}
if ($langpack.KnowledgeArticles.KnowledgeArticle -ne $null)
{
foreach ($disp in $langpack.KnowledgeArticles.KnowledgeArticle)
{
if (($ids.value).ContainsKey($disp.ElementID))
{
$langpack.KnowledgeArticles.RemoveChild($disp)
}
}
}
}
}

#Rashma - cleanup custom group references
function CleanupCustomGrpReferences
{
param($ovrdMPXML)

foreach ($disc in $ovrdMPXML.ManagementPack.Monitoring.Discoveries.Discovery)
{

#if ($disc.InnerText -match "DellOutOfBand")
if($disc.InnerText -ne $null -and $disc.InnerText -match ($alias + "!"))
{

#$s.ManagementPack.Monitoring.Discoveries.RemoveChild($disc)
$ovrdMPXML.ManagementPack.Monitoring.Discoveries.RemoveChild($disc)

$languagePackToRemove= $ovrdMPXML.ManagementPack.LanguagePacks.LanguagePack.DisplayStrings.ChildNodes | where {$_.ElementID -eq $disc.ID}
If($languagePackToRemove -ne $null)
{
foreach ($lpNode in $languagePackToRemove)
{
$ignoreReturn = $ovrdMPXML.ManagementPack.LanguagePacks.LanguagePack.DisplayStrings.RemoveChild($lpNode)
}
}
}

}

}

function CleanupReferences
{
param($mp, $mptodelete, $dellMP, $scomenv)
psDebugLog -level 1 -message ("Remove References of " +$mptodelete + " from " + $mp.Name)

# Get the Override Management Pack
if ($mp -eq $null)
{
# Create a new management pack, if not present
psDebugLog -level 1 -message "INFO: Management Pack not found."
return 0
}
if ($mp.Sealed -eq $true)
{
# Create a new management pack, if not present
psDebugLog -level 1 -message ("ERROR: " + $mp.Name + " is a sealed management pack. You need to manually delete")
return 1
}

$mpStore = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackFileStore;
$mpStore.AddDirectory($dellMP.GetExportDir($mpname));
$mpXmlWriter = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackXmlWriter($dellMP.GetExportDir($mpname));
$mpXmlWriter.WriteManagementPack($mp)
$ovrdMPTextFile = $dellMP.GetExportDir($mp.Name) + "\" + $mp.Name + ".xml"
$outdir = $dellMP.GetExportDir($mp.Name + "\Output")
$ovrdMPEditedFile = $outdir + "\" + $mp.Name + ".xml"
$ovrdMPXML = [xml](Get-Content $ovrdMPTextFile)
if ($ovrdMPXML.ManagementPack.Manifest.References.Reference -ne $null)
{
$found = $false
foreach ($mpalias in $ovrdMPXML.ManagementPack.Manifest.References.Reference)
{
if ($mpalias.ID -ne $mptodelete) { continue }
$found = $true
break
}
}
$mpversion = $ovrdMPXML.ManagementPack.Manifest.Identity.Version
$lastvercomp = $mpversion -replace '\d+.\d+.\d+.', ''
if ($lastvercomp -ne $null) {
$lastvercomp = ([int]$lastvercomp)+1
}
$ovrdMPXML.ManagementPack.Manifest.Identity.Version = ($mpversion -replace '\d+$', $lastvercomp)

$deleteIDs = @{}
RecurseRemove -parent $ovrdMPXML.ManagementPack -ids ([ref]$deleteIDs) -alias $mpalias.Alias

#Rashma
CleanupCustomGrpReferences -ovrdMPXML $ovrdMPXML

RemoveLangPacks -parent $ovrdMPXML.ManagementPack -ids ([ref]$deleteIDs)
$ovrdMPXML.Save($ovrdMPEditedFile)
$v = $scomenv.InstallManagementPack($ovrdMPEditedFile)
if ($v -eq $null -or $v.Count -eq 0)
{
Write-Info -msg ("Success")
}
else
{
$msg = getExceptionDetails -except $v
if ($msg -match "already imported")
{
Write-Info -msg ("INFO: " + $f.mp + " is already imported")
}
elseif ($msg -match "timeout period elapsed prior to completion of the operation")
{
Write-Info -msg ("ERROR: SCOM Database timeout occurred. You may need to run the task again.")
}
else
{
Write-Info -msg ("ERROR: There were errors in the command.")
Write-Info -msg ("ERROR: " + $msg)
}
}

Write-Info -msg ( "INFO: Importing back the override Management Pack " + $ovrdMPEditedFile)
}


function CleanupMPReferencesOnly
{
param($mp, $mptodelete, $dellMP, $scomenv)
psDebugLog -level 1 -message ("Remove MP References of " +$mptodelete + " from " + $mp.Name)

# Get the Override Management Pack
if ($mp -eq $null)
{
# Create a new management pack, if not present
psDebugLog -level 1 -message "INFO: Management Pack not found."
return 0
}
if ($mp.Sealed -eq $true)
{
# Create a new management pack, if not present
psDebugLog -level 1 -message ("ERROR: " + $mp.Name + " is a sealed management pack. You need to manually delete")
return 1
}

$mpStore = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackFileStore;
$mpStore.AddDirectory($dellMP.GetExportDir($mpname));
$mpXmlWriter = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackXmlWriter($dellMP.GetExportDir($mpname));
$mpXmlWriter.WriteManagementPack($mp)
$ovrdMPTextFile = $dellMP.GetExportDir($mp.Name) + "\" + $mp.Name + ".xml"

$ovrdMPXMLText = (Get-Content $ovrdMPTextFile)
$ovrdMPXML = [xml]($ovrdMPXMLText)
$defidalias = $null
if ($ovrdMPXML.ManagementPack.Manifest.References.Reference -ne $null)
{
$found = $false
foreach ($mpalias in $ovrdMPXML.ManagementPack.Manifest.References.Reference)
{
if ($mpalias.ID -ne $mptodelete) { continue }
$found = $true
$defidalias = $mpalias
break
}
}
RemoveSecureReferences -overriddenXmlFile $ovrdMPXML -alias $defidalias.Alias
$outdir = $dellMP.GetExportDir($mp.Name + "\Output")
$ovrdMPEditedFile = $outdir + "\" + $mp.Name + ".xml"
$ovrdMPXML.Save($ovrdMPEditedFile + ".tmp")
$ovrdMPXMLText = (Get-Content ($ovrdMPEditedFile + ".tmp"))
$ovrdMPXML = [xml]($ovrdMPXMLText)

if ($ovrdMPXMLText -notmatch ($defidalias.Alias + "!"))
{
$mpversion = $ovrdMPXML.ManagementPack.Manifest.Identity.Version
$lastvercomp = $mpversion -replace '\d+.\d+.\d+.', ''
if ($lastvercomp -ne $null) {
$lastvercomp = ([int]$lastvercomp)+1
}
$ovrdMPXML.ManagementPack.Manifest.Identity.Version = ($mpversion -replace '\d+$', $lastvercomp)

$deleteIDs = @{}
$removeRefNode=$ovrdMPXML.ManagementPack.Manifest.References.ChildNodes| where {$_.Alias -match $defidalias.Alias}
$ovrdMPXML.ManagementPack.Manifest.References.RemoveChild($removeRefNode)
Write-Info -msg ( "INFO: MP References removed from " + $mp.Name)
$ovrdMPXML.Save($ovrdMPEditedFile)
$v = $scomenv.InstallManagementPack($ovrdMPEditedFile)
if ($v -eq $null -or $v.Count -eq 0)
{
Write-Info -msg ("Success")
}
else
{
$msg = getExceptionDetails -except $v
if ($msg -match "already imported")
{
Write-Info -msg ("INFO: " + $f.mp + " is already imported")
}
elseif ($msg -match "timeout period elapsed prior to completion of the operation")
{
Write-Info -msg ("ERROR: SCOM Database timeout occurred. You may need to run the task again.")
}
else
{
Write-Info -msg ("ERROR: There were errors in the command.")
Write-Info -msg ("ERROR: " + $msg)
}
}

Write-Info -msg ( "INFO: Importing back the override Management Pack " + $ovrdMPEditedFile)
}
}

function DoDeleteMP
{
param($mptodelete, $recursedelete, $collectoverrides, $noexecute)

$oktodelete = $true

$deleteMP = $scomenv.GetManagementPacks() | where-object { $mptodelete -eq $_.Name }
if ($deleteMP -eq $null)
{
psDebugLog -level 1 -message ("The MP to be deleted is not present or was previously deleted")
Write-Info -msg ("INFO: $mptodelete is not present or was previously deleted")
return
}
else
{
psDebugLog -level 1 -message ("The MP to be deleted is present: " + $mptodelete)
Write-Info -msg ("INFO: Preparing to delete $mptodelete")
}
$cleanuprefonly = $false
if ($recursedelete -eq $false)
{
$cleanuprefonly = $true
}
$dependentMPs = @{}
$scomenv.GetManagementPacks() | ForEach-Object {
$scommp = $_
#The only change in below line from $scommp.References to $scommp.References.Values made Remove functionality work SCOM 2012 SP1
$scommp.References.Values | ForEach-Object {
psDebugLog -level 1 -message ("Checking MP----" + $mptodelete + "- == -" + "with name" + $_.Name + "-------")
if ($_.Name -eq $mptodelete)
{
psDebugLog -level 1 -message ("The MP---" + $mptodelete + "---to be deleted is depende up on" + $_.Name + "-----")
$dependentMPs += @{ $scommp.ID = $scommp }
if ($scommp.Sealed -eq $true) {
psDebugLog -level 1 -message ("The MP---" + $mptodelete + "---to be deleted is depende up on sealed MP" + $_.Name + ". Sealed MP's Cannot be deleted therefore not proceeding further.")
Write-Info -msg ("INFO:" + $scommp.Name + " (Sealed) is dependent on " + $deleteMP.Name)
$oktodelete = $false
return
}
}
}
}
if ($oktodelete)
{
foreach ($mpid in $dependentMPs.Keys)
{
$mpname = $dependentMPs[$mpid].Name
# Export MP to Collect Overrides Directory
if ($cleanuprefonly -eq $true)
{
Write-Info -msg ( "INFO: Trying to Clean up MP references only from Management Pack " + $mpname)
$retVal = CleanupMPReferencesOnly -mp $dependentMPs[$mpid] -mptodelete $mptodelete -dellMP $dellMP -scomenv $scomenv

}
else
{
Write-Info -msg ( "INFO: Cleaning up references from Management Pack " + $mpname)
$retVal = CleanupReferences -mp $dependentMPs[$mpid] -mptodelete $mptodelete -dellMP $dellMP -scomenv $scomenv
}

if ($retVal -eq 1)
{
Write-Info -msg ("ERROR: References could not be deleted from :" + $mpname)
}
else
{
Write-Info -msg ("INFO: References deleted successfully from :" + $mpname)
}
}
}

if ($oktodelete -eq $true)
{
Write-Info -msg ("INFO: Deleting Management Pack :" + $deleteMP.Name)
try {
if ($noexecute -eq $false)
{
$v = $scomenv.UninstallManagementPack($deleteMP)
}
} catch [Exception] {
$e = $_
}
if (($e -eq $null -or $e.Count -eq 0) -and ($v -eq $null -or $v.Count -eq 0))
{
Write-Info -msg ("INFO: Management Pack " + $deleteMP.Name + " deleted successfully.")
}
else
{
$msg = getExceptionDetails -except $e
if ($msg -eq $null) { $msg = getExceptionDetails -except $e }
if ($msg -match "have references to this")
{
Write-Info -msg ("ERROR: "+ $deleteMP.Name+" cannot be deleted as it has references")
}
elseif ($msg -notmatch "not present")
{
Write-Info -msg ("ERROR: There were errors while deleting the Management Pack")
Write-Info -msg ("ERROR: " + $msg)
}
}
}
else
{
Write-Info -msg ("INFO: Management Pack " + $deleteMP.Name + " will not be deleted!")
}
}

function DoCollectOverrides
{
param($collectoverrides)

$mpStore = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackFileStore;
$mpStore.AddDirectory($collectoverrides.exportdir);
$mpXmlWriter = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackXmlWriter($collectoverrides.exportdir);
$autogenexportdir = $dellMP.GetExportDir("AutoGeneratedExports")
$mpAGXmlWriter = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackXmlWriter($autogenexportdir);
foreach ($formp in $collectoverrides.collectfor.Keys)
{
$basemp = $scomenv.GetManagementPacks() | where-object { $formp -eq $_.Name }
if ($basemp -eq $null)
{
continue;
}
Write-Info -msg ("INFO: Preparing to collect overrides for $formp")

$dependentMPs = @{}
$allmps = $scomenv.GetManagementPacks()
$autogens = ("_" + $collectoverrides.autogensuffix + "AutoGeneratedByFMP")

$alreadyAutogeneratedMPs = @{}
$allmps | ForEach-Object {
if ($_.Name -match $autogens)
{
$alreadyAutogeneratedMPs += @{ ($_.Name -replace $autogens, "") = $_ }
}

}

$allmps | ForEach-Object {
$scommp = $_
$scommp.References | ForEach-Object {
if ($_.Name -eq $formp)
{
$dependentMPs += @{ $scommp.ID = $scommp }
if ($scommp.Sealed -ne $true) {
if ($collectoverrides.depmps.ContainsKey($scommp.Name) -eq $false -and ($scommp.Name -notmatch $autogens)) {
$mptoexport = $scommp
Write-Info -msg ("INFO: preparing to export " + $scommp.Name)
if ($collectoverrides.useAutoGenerated -eq $true -and $alreadyAutogeneratedMPs.ContainsKey($scommp.Name) -eq $true) {
Write-Info -msg ("INFO: Found already autogenerated MP.")
$mptoexport = $alreadyAutogeneratedMPs[$scommp.Name]
Write-Info -msg ("INFO: Exporting " + $mptoexport.Name)
$mpAGXmlWriter.WriteManagementPack($mptoexport)
$ovrdMPTextFile = $autogenexportdir + "\" + $mptoexport.Name + ".xml"
$ovrdMPXML = [xml](Get-Content $ovrdMPTextFile)
$mpversion = $ovrdMPXML.ManagementPack.Manifest.Identity.Version
$lastvercomp = $mpversion -replace '\d+.\d+.\d+.', ''
if ($lastvercomp -ne $null) {
$lastvercomp = ([int]$lastvercomp)+1
}
$ovrdMPXML.ManagementPack.Manifest.Identity.Version = ($mpversion -replace '\d+$', $lastvercomp)
$renmpid = $scommp.Name
$ovrdMPXML.ManagementPack.Manifest.Identity.ID = $renmpid
foreach ($langpack in $ovrdMPXML.ManagementPack.LanguagePacks.LanguagePack)
{
$displayString = $langpack.DisplayStrings.ChildNodes | Where {$renmpid -match $_.ElementID}
if ($displayString -ne $null)
{
$displayString.ElementID = $renmpid
}
$kbarticle = $langpack.KnowledgeArticles.ChildNodes | Where {$renmpid -match $_.ElementID}
if ($kbarticle -ne $null)
{
$kbarticle.ElementID = $renmpid
}
}
$ovrdMPXML.Save($collectoverrides.exportdir + "\" + $scommp.Name + ".xml")
}
else
{
Write-Info -msg ("INFO: Exporting " + $mptoexport.Name)
$mpXmlWriter.WriteManagementPack($mptoexport)
}
$ignore = $collectoverrides.AddMPName($scommp.Name)
}
}
}
}
}
Write-Info -msg ("INFO: Overrides collected for $formp")
}
}

function DoImportOverrides
{
param($collectoverrides)
foreach ($formp in $collectoverrides.depoutmps.Keys)
{
$v = $scomenv.InstallManagementPack($collectoverrides.depoutmps[$formp])
if ($v -eq $null -or $v.Count -eq 0)
{
Write-Info -msg ("INFO: " + $formp + " is imported successfully")
}
else
{
$msg = getExceptionDetails -except $v
if ($msg -match "already imported")
{
Write-Info -msg ("INFO: " + $formp + " is already imported")
}
elseif ($msg -match "timeout period elapsed prior to completion of the operation")
{
Write-Info -msg ("ERROR: SCOM Database timeout occurred. You may need to run the task again.")
}
else
{
Write-Info -msg ("ERROR: There were errors in the command.")
Write-Info -msg ("ERROR: " + $msg)
}
}

}
}

function GetServerVersion()
{
param($KeyToFind)
$MPLocRegKeyPath = "HKLM:\software\Dell\Dell Server Management Pack Suites";
$mpLoc = $null;
$mpLoc = Get-ItemProperty -path:$MPLocRegKeyPath -name:$KeyToFind -ErrorAction:SilentlyContinue;
return $mpLoc;
}
function GetEqualLogicVersion()
{
param($KeyToFind)
$MPLocRegKeyPath = "HKLM:\SOFTWARE\Dell\Dell EqualLogic Storage Management Pack Suite";
$mpLoc = $null;
$mpLoc = Get-ItemProperty -path:$MPLocRegKeyPath -name:$KeyToFind -ErrorAction:SilentlyContinue;
return $mpLoc;
}
#################################################

# Now, activate the appropriate customObjectmodule (SCOM2012, SCE2010 or SCOM2007R2)
# based on presence detected on mgmtServer

psDebugLog -level 1 -message ("----------------------------------------------")
psDebugLog -level 1 -message ("Begin of " + $scriptname + " Discovery script ")
psDebugLog -level 1 -message ("ComputerName : " + $MSComputerName)
psDebugLog -level 1 -message ("ManagedEntityId : " + $managedEntityID)
psDebugLog -level 1 -message ("sourceID : " + $sourceID)

$MachineRegKeyPath = "HKLM:\software\Microsoft\Microsoft Operations Manager\3.0\Setup";
$MachineRegValueName = "InstallDirectory";
$skuName = $null; $skuVersion = $null
$skuName = Get-ItemProperty -path:$MachineRegKeyPath -name:$MachineRegValueName -ErrorAction:SilentlyContinue;
$skuVersion = Get-ItemProperty -path:$MachineRegKeyPath -name:"CurrentVersion" -ErrorAction:SilentlyContinue;

if ($skuName.InstallDirectory -match "Essentials")
{
$scomenv = $sce2010Interface
}
elseif ( $skuName.InstallDirectory -match "2007" )
{
$scomenv = $scom2007r2Interface
}
else
{
$scomenv = $scom2012Interface
}

$scomenv.loglocation = $LogFileLocation
$scomenv.logLevel = $logLevel
$scomenv.LoadSnapins()
$scomenv.GetConnection() | Out-Null
Write-Info -msg ("SCOM Env: Product: " + $scomenv.Product)
Write-Info -msg ("SCOM Env: State: " + $scomenv.State)

$mgmtGroup = $scomenv.GetManagementGroup()




$CMC_ChangeTargetIds = @{
'Dell.ModularChassis.ChassisRemoteAccessGroupPopulator'='Dell.OperationsLibrary.CMC';
'Dell.ModularChassis.HWGroupPopulator'='Dell.OperationsLibrary.CMC';
'Dell.ModularChassis.CMCPopulateGroup'='Dell.OperationsLibrary.CMC';
'Dell.ModularChassis.DRACMCPopulateGroup'='Dell.OperationsLibrary.CMC';
'Dell.CMCSlot.Discovery'='Dell.CMC.OM07';
'Dell.DRACMCSlot.Discovery'='Dell.CMC.OM07';
'Dell.ModularChassis.DRACMCDiscovery'='Dell.CMC.OM07';
'Dell.ModularChassis.CMCDiscovery'='Dell.CMC.OM07';
'Dell.ModularChassis.CMCAvailability.TrapBased'='Dell.CMC.OM07';
'Dell.ModularChassis.DRACMCAvailability.TrapBased'='Dell.CMC.OM07';
'Dell.ModularChassis.CMCAvailability.Periodic'='Dell.CMC.OM07';
'Dell.ModularChassis.DRACMCAvailability.Periodic'='Dell.CMC.OM07';
'Dell.ModularChassis.ChassisRemoteAccessGroupToDellHWGroupHealthRollupMonitor'='Dell.CMC.OM07';
'Dell.ModularChassis.CMCGroupToChassisRemoteAccessGroupHealthRollupMonitor'='Dell.CMC.OM07';
'Dell.ModularChassis.DRACMCGroupToChassisRemoteAccessGroupHealthRollupMonitor'='Dell.CMC.OM07';
'Dell.ModularChassis.CMCToCMCGroupHealthRollupMonitor'='Dell.CMC.OM07';
'Dell.ModularChassis.DRACMCToDRACMCGroupHealthRollupMonitor'='Dell.CMC.OM07';
}

$CMC_RemoveWorkflows = @{
"Microsoft.SystemCenter.NetworkDevice.CheckDeviceStatus" = "remove"
}

$CMC_RemoveOverrideParameters = @{
"Dell.ModularChassis.CMCDiscovery" = @{ "ChassisType" = "remove"; "Timeout" = "remove" }
"Dell.ModularChassis.DRACMCDiscovery" = @{ "ChassisType" = "remove"; "Timeout" = "remove" }
}
$CMC_RenameWorkflows = @{
'Dell.ModularChassis.CMCDiscovery'='Dell.CMC.Discovery';
'Dell.ModularChassis.DRACMCDiscovery'='Dell.CMC.Discovery';
}

$CMC_ChangeMatchingTargetIds =@{
'Dell.ModularChassis.SNMP.DRACMC10'= @{ 'text' = 'Dell.ModularChassis.DRACMC10'; 'alias' = 'Dell.CMC.OM07' }
'Dell.ModularChassis.SNMP.CMC20' = @{ 'text' = 'Dell.ModularChassis.CMC20'; 'alias' = 'Dell.CMC.OM07' }
}


$DRAC_ChangeTargetIds = @{

'Dell.RemoteAccess.DRAC5iDRAC.Discovery'='Dell.DRAC.OM07';
'Dell.RemoteAccess.iDRACModular.Discovery'='Dell.DRAC.OM07';
'Dell.RemoteAccess.RACAvailability.Periodic'='Dell.DRAC.OM07';
'Dell.RemoteAccess.RACAvailability.TrapBased'='Dell.DRAC.OM07';
'Dell.RemoteAccess.iDRACModularToiDRACModularGroup.HealthRollupMonitor'='Dell.DRAC.OM07';
'Dell.RemoteAccess.iDRACMonolithicToiDRACMonolithicGroup.HealthRollupMonitor'='Dell.DRAC.OM07';
'Dell.RemoteAccess.DRAC5ToDRAC5Group.HealthRollupMonitor'='Dell.DRAC.OM07';
'Dell.RemoteAccess.RACGroupToHWGroup.HealthRollupMonitor'='Dell.DRAC.OM07';
'Dell.RemoteAccess.DRAC5GroupToRACGroup.HealthRollupMonitor'='Dell.DRAC.OM07';
'Dell.RemoteAccess.RACGroup.Populator'='Dell.OperationsLibrary.DRAC';
'Dell.RemoteAccess.DRAC5Group.Populator'='Dell.OperationsLibrary.DRAC';
'Dell.RemoteAccess.iDRACMonolithicGroup.Populator'='Dell.OperationsLibrary.DRAC';
'Dell.RemoteAccess.iDRACModularGroup.Populator'='Dell.OperationsLibrary.DRAC';
'Dell.RemoteAccess.HWGroup.Populator'='Dell.OperationsLibrary.DRAC';
}

$DRAC_RemoveWorkflows = @{
"Microsoft.SystemCenter.NetworkDevice.CheckDeviceStatus" = "remove";
"Dell.RemoteAccess.DRAC4.Discovery" = "remove";
"Dell.RemoteAccess.DRAC4ToDRAC4Group.HealthRollupMonitor" = "remove";
"Dell.RemoteAccess.DRAC4Group.Populator" = "remove";
"Dell.RemoteAccess.SNMP.RAC262401" = "remove";
"Dell.RemoteAccess.DRAC4GroupToRACGroup.HealthRollupMonitor" = "remove"
"Dell.RemoteAccess.iDRACModularToiDRACModularGroup.HealthRollupMonitor" = "remove"
"Dell.RemoteAccess.iDRACMonolithicToiDRACMonolithicGroup.HealthRollupMonitor" = "remove"
"Dell.RemoteAccess.DRAC4" = "remove";
}

$DRAC_RemoveOverrideParameters = @{
"Dell.RemoteAccess.iDRACModular.Discovery" = @{ "Timeout" = "remove" }
"Dell.RemoteAccess.DRAC4.Discovery" = @{ "Timeout" = "remove" }
}
$DRAC_RenameWorkflows = @{
'Dell.RemoteAccess.DRAC5iDRAC.Discovery'='Dell.DRAC.Discovery';
'Dell.RemoteAccess.iDRACModular.Discovery'='Dell.DRAC.Discovery';
'Dell.RemoteAccess.RACAvailability.Periodic' = 'Dell.RAC.Availability.Periodic'
'Dell.RemoteAccess.RACAvailability.TrapBased' = 'Dell.RAC.Availability.TrapBased'
'Dell.RemoteAccess.HWGroup.Populator' = 'Dell.RemoteAccess.HWGroupPopulator'
'Dell.RemoteAccess.iDRAC'='Dell.RemoteAccess.iDRAC6Monolithic';
'Dell.RemoteAccess.iDRACModular'='Dell.RemoteAccess.iDRAC6Modular';
'Dell.RemoteAccess.iDRACMonolithic'='Dell.RemoteAccess.iDRAC6Monolithic';
}

$DRAC_ChangeMatchingTargetIds =@{
'Dell.RemoteAccess.PET' = @{ 'text' = 'Dell.RemoteAccess.PET.RAC'; 'alias' = 'Dell.DRAC.OM07' }
'Dell.RemoteAccess.SNMP.RAC' = @{ 'text' = 'Dell.RemoteAccess.SNMP.RAC'; 'alias' = 'Dell.DRAC.OM07' }
}

$EQL_ChangeTargetIds =@{
'HealthRollupMonitorForRelationhip.DellEqualLogicArrayGroup.Contains.Volumes'='Dell.EqualLogic.Impl';
'HealthRollupMonitorForRelationhip.DellEqualLogicArrayGroup.Contains.StoragePoolGroup' = 'Dell.EqualLogic.Impl';
'HealthRollupMonitorForRelationhip.DellEqualLogicGroup.Contains.DellEqualLogicArrayGroup' = 'Dell.EqualLogic.Impl';
'HealthRollupMonitorForRelationhip.DellHWGp.Contains.DellEqualLogicGroup' = 'Dell.EqualLogic.Impl';
'HealthRollupMonitorForRelationhip.StoragePool.Contains.ArrayMember' = 'Dell.EqualLogic.Impl';
'HealthRollupMonitorForRelationhip.StoragePoolGroup.Contains.StoragePool' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicControllerGroup.PollBasedMonitor'= 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicDiskGroup.PollBasedMonitor' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicArrayMember.PollBasedMonitor' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicSensors.PollBasedMonitor' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicVolumeGroup.PollBasedMonitor' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicPowerSupplyGroup.PollBasedMonitor' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicHelper.PollBasedMonitor' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicEthernetInterfaceGroup.PollBasedMonitor' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicStoragePoolGroup.PollBasedMonitor'='Dell.EqualLogic.Impl';
'Dell.Storage.DellHWGp.Populator'= 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicGroup.Populator'= 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicHelperUtility.Discovery'= 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogicEthernetInterfaceGroup.EventBasedMonitor' = 'Dell.EqualLogic.Impl';
'Dell.Storage.EqualLogic.Discovery'='Dell.EqualLogic.OM07';
}


$EQL_ChangeMatchingTargetIds =@{
'Dell.Storage.EqualLogicAlert' = @{ 'text' = 'Dell.Storage.EqualLogicAlert'; 'alias' = 'Dell.EqualLogic.OM07' }
}

#### CODE LOGIC GOES HERE
$fmpactions = @()

# Check if the culture setting failed
# This check is done in order to determine if we get proper exception message from scom commands
# and show them as info during the below task operations
psDebugLog -level 1 -message ("Culture has been set to: " + [Threading.Thread]::CurrentThread.CurrentCulture)
psDebugLog -level 1 -message ("UICulture has been set to: " + [Threading.Thread]::CurrentThread.CurrentUICulture)
if($OldCulture -ne "en-US" -and $OldUICulture -ne "en-US")
{
Write-Info -msg ("NOTE : Detected a non-English locale. INFO (informational) messages may show up as ERROR messages in the task summary.")
}

Function AssociateRunasAccount()
{
$mpname = 'Dell.SecureReference.Override'
$mpdesc = 'Dell.SecureReference.Override file'
$oneDiscoveryTgtClassName = 'Microsoft.SystemCenter.OOB.WSManDevice'
$oneDiscoveryGenClassName = 'Dell.Server'
$oneDiscoveryTgtClassGroupName = 'Microsoft.SystemCenter.OOB.WSManDeviceGroup'
$oneOverrideName = 'SecureRef-{0}'

# License Configuration
$mpStore = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackFileStore;
$scomInstallDir = $scomenv.GetSCOMInstallDir()
$mpStore.AddDirectory($scomInstallDir);
$mpStore.AddDirectory($dellsuitedir);
$mpXmlWriter = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackXmlWriter($scomInstallDir);

$mgmtGroup = $scomenv.GetManagementGroup()

$oneDiscoveryTgtClassCriteria = New-Object Microsoft.EnterpriseManagement.Configuration.MonitoringClassCriteria($("Name='{0}'" -f $oneDiscoveryTgtClassName));
$retVal = $mgmtGroup.GetMonitoringClasses($oneDiscoveryTgtClassCriteria)
if ($retVal -eq $null -or $retVal.Count -le 0)
{
# Do Error Condition Return

}
$oobWsManDeviceClass = $retVal[0]

$oneDiscoveryTgtClassGroupCriteria = New-Object Microsoft.EnterpriseManagement.Configuration.MonitoringClassCriteria($("Name='{0}'" -f $oneDiscoveryTgtClassGroupName));
$retVal = $mgmtGroup.GetMonitoringClasses($oneDiscoveryTgtClassGroupCriteria)
if ($retVal -eq $null -or $retVal.Count -le 0)
{
# Do Error Condition Return
Write-Info -msg ("Existing Secure reference found none")
}
$oobWsManDeviceGroupClass = $retVal[0]

$oneDiscoveryGenClassCriteria = New-Object Microsoft.EnterpriseManagement.Configuration.MonitoringClassCriteria($("Name='{0}'" -f $oneDiscoveryGenClassName));
$retVal = $mgmtGroup.GetMonitoringClasses($oneDiscoveryGenClassCriteria)
if ($retVal -eq $null -or $retVal.Count -le 0)
{
# Do Error Condition Return

}
$dellServerClass = $retVal[0]

$dellServerInstCriteria = New-Object Microsoft.EnterpriseManagement.Monitoring.MonitoringObjectCriteria("", $dellServerClass)
$dellServerInstances = $mgmtGroup.GetMonitoringObjects($dellServerInstCriteria)

$secRefOverridesMPCriteria = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackCriteria($("Name='{0}'" -f 'Microsoft.SystemCenter.SecureReferenceOverride'));
$retVal = $mgmtGroup.GetManagementPacks($secRefOverridesMPCriteria)
if ($retVal -eq $null -or $retVal.Count -le 0)
{
# Do Error Condition Return

}
$secRefOverridesMP = $retVal[0]

$mpSecRefArray = @{}
if($secRefOverridesMP -ne $null)
{
$mpsecRef = $secRefOverridesMP.GetOverrides() | where { $_.XmlTag -eq 'SecureReferenceOverride' }

if ($mpsecRef -ne $null)
{
foreach ($sec in $mpsecRef)
{
if ($sec.ContextInstance -ne $null) {
$mpSecRefArray += @{ $sec.ContextInstance = $sec.Value }
Write-Info -msg ($sec.ContextInstance.ToString() + " = " + $sec.Value)
}
}
}
}
$mpReferences = @{
'OperationsLibrary' = 'Dell.OperationsLibrary.Common'
'SystemCenter' = 'Microsoft.SystemCenter.Library'
'NetworkDevice' = 'Microsoft.SystemCenter.NetworkDevice.Library'
}

# Get the Override Management Pack
$ovrdMP = $scomenv.GetManagementPacks() | where-object { $mpname -eq $_.Name }
if ($ovrdMP -eq $null)
{
# Create a new management pack, if not present
$ovrdMP = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPack($mpname, $mpdesc, (New-Object Version(1, 0, 0)), $mpStore);
$mgmtGroup.ImportManagementPack($ovrdMP);
}
else
{
if($secRefOverridesMP -ne $null)
{
$mpsecRef = $secRefOverridesMP.GetOverrides() | where { $_.XmlTag -eq 'SecureReferenceOverride' }
if ($mpsecRef -ne $null)
{
foreach ($sec in $mpsecRef)
{
if ($sec.ContextInstance -ne $null -and $mpSecRefArray.Contains($sec.ContextInstance) -ne $true) {
$mpSecRefArray += @{ $sec.ContextInstance = $sec.Value }
Write-Info -msg ($sec.ContextInstance.ToString() + " = " + $sec.Value)
}
}
}
}
}

# Add the MP References. REVISIT: Update References
foreach ($mpRef in $mpReferences.Keys)
{
if ($ovrdMP.References.ContainsKey($mpref) -eq $false)
{
# if $ovrdMP.References[$mpref].Version -lt $refmp.Version, update
$refmp = $scomenv.GetManagementPacks() | where { $_.Name -eq $mpReferences[$mpRef] }
$mprefcons = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackReference($refmp, $refmp.Name, $refmp.KeyToken, $refmp.Version);
$ovrdMP.References.Add($mpref, $mprefcons)
} elseif ($ovrdMP.References[$mpref].Version -lt $refmp.Version) {
$refmp = $scomenv.GetManagementPacks() | where { $_.Name -eq $mpReferences[$mpRef] }
$mprefcons = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackReference($refmp, $refmp.Name, $refmp.KeyToken, $refmp.Version);
$ovrdMP.References.Remove($mpref)
$ovrdMP.References.Add($mpref, $mprefcons)
}
}

$smshCriteria = New-Object Microsoft.EnterpriseManagement.Configuration.MonitoringSecureReferenceCriteria("Name='{0}'" -f 'Microsoft.SystemCenter.OOB.SMASHMonitoringProfile')
$retVal = $mgmtGroup.GetMonitoringSecureReferences($smshCriteria)
if ($retVal -eq $null -or $retVal.Count -le 0)
{
# Do Error Condition Return

}
$smashprofile = $retVal[0]

$oneOverrideName = 'SecureRef-{0}-hola-{1}'
$dellServerHashMap = @{}
$dellServerSecRefHashMap = @{}
Foreach ($server in $dellServerInstances)
{
$property_RemoteAccessIP = $server.GetMonitoringProperties() | where { $_.Name -eq 'RemoteAccessIP' }
$serverIP = $server.GetMonitoringPropertyValue($property_RemoteAccessIP)
$dellServerHashMap += @{ $serverIP = $server }

$oobDeviceForServer = $null
$server.GetMonitoringRelationshipObjects() | foreach -process {
if ($_.TargetMonitoringObject.IsInstanceOf($oobWsManDeviceClass))
{
$oobDeviceForServer = $_.TargetMonitoringObject
}
}

$oobServerWsManGroup = $null
$oobDeviceForServer.GetMonitoringRelationshipObjects() | foreach -process {
if ($_.SourceMonitoringObject.IsInstanceOf($oobWsManDeviceGroupClass))
{
$oobServerWsManGroup = $_.SourceMonitoringObject
}
}
$secrefVal = $null
$secrefKey=$null
foreach ($cls in $oobServerWsManGroup.GetMonitoringClasses())
{
if ($cls.Name -match 'Microsoft.SystemCenter.OOB.*.DeviceGroup')
{
$secrefKey =$cls.Name -replace ".DeviceGroup",""
$secrefVal = $cls.GetManagementPack().GetOverrides() | where { $_.XmlTag -eq 'SecureReferenceOverride' -and $_.Name -match $secrefKey}
}
}

$dellServerSecRefHashMap += @{ $serverIP = $secrefVal.Value }

$overrideDisplayName = ($oneOverrideName -f $server.Id, $server.Name)
$override = (($overrideDisplayName.Replace(" ", [String]::Empty)) -replace '-', '_')

if ($mpSecRefArray.Contains($server.Id) -eq $false)
{
# REVISIT Update if override not found!
$secref = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackSecureReferenceOverride($ovrdMP, $override)
$secref.Value = $secrefVal.Value
$secref.Context = $dellServerClass
$secref.ContextInstance = $server.Id
$secref.SecureReference = $smashprofile
}
else
{
Write-Info -msg ("Not adding " + $server.Id + ". Already exists")

}
}

# verify the changes in the override management pack
$ovrdMP.Verify();

# save the changes into the override management pack
try { $ovrdMP.AcceptChanges() }
catch [Exception] { $_ | fl * -Force }
}
# Set to Scalable
if ($mpActionType -eq "InbandScalableImport")
{
$DetailedPresent = chkMPPresence("Dell.WindowsServer.Detailed")
if ($DetailedPresent -eq $false -or $force -eq $true)
{
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.Server",$dellMP.GetImportDir("Dell.Model.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Server",$dellMP.GetImportDir("Dell.OperationsLibrary.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.Server",$dellMP.GetImportDir("Dell.View.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.WindowsServer.Scalable",$dellMP.GetImportDir("Dell.WindowsServer.Scalable.mp"))
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.WindowsServer.Detailed",$true)
$fmpactions += $object
}
else
{
Write-Info -msg ("WARNING: You may lose detailed monitoring information")
Write-Info -msg ("WARNING: To proceed, run with Auto Resolve Warnings/Errors set to true")
}
}
elseif ($mpActionType -eq "InbandDetailedImport")
{
# Set to Detailed
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.Server",$dellMP.GetImportDir("Dell.Model.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Server",$dellMP.GetImportDir("Dell.OperationsLibrary.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.Server",$dellMP.GetImportDir("Dell.View.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.WindowsServer.Scalable",$dellMP.GetImportDir("Dell.WindowsServer.Scalable.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.WindowsServer.Detailed",$dellMP.GetImportDir("Dell.WindowsServer.Detailed.mp"))
$fmpactions += $object
}
elseif ($mpActionType -eq "EQLSetToScalable")
{
$DetailedPresent = chkMPPresence("Dell.EqualLogic.DetailedMonitoringOn")
$EQLOM07Present = $false
$EQLOM12Present = $false

if($scomenv.IsSCOM2012() -eq $false)
{
$EQLOM07Present = chkMPPresence("Dell.EqualLogic.OM07")
}
else
{
$EQLOM12Present = chkMPPresence("Dell.EqualLogic.OM12")
}

$ScalablePresent = $EQLOM12Present -or $EQLOM07Present

if($force -eq $false)
{
Write-Info -msg ("WARNING: Management Packs could not be Imported/Removed")
Write-Info -msg ("WARNING: To still proceed, run with Auto Resolve Warnings/Errors set to true")
}
elseif ($ScalablePresent -eq $false)
{
$EQL41Present = chkMPPresence("Dell.Storage.EqualLogic")
if($EQLOM07Present -ne $true)
{ $EQLOM07Present = chkMPPresence("Dell.EqualLogic.OM07") }
# upgrade 4.1 to 5.1
if ($EQL41Present -eq $true)
{
$eql_Overrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrdEQL"), $dellMP.GetExportDir("CollectOvrdEQLNew"), $false)
$eql_Overrides.CollectOverrideMPsFor("Dell.Storage.EqualLogic")
$fmpactions += $eql_Overrides

Write-Info -msg "INFO: EQL 4.1 present. Upgrading EQL 4.1 as well"

$object = New-Object DeleteOptions("Dell.Storage.EqualLogic.DetailedMonitoringOn",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Storage.EqualLogic",$true)
$fmpactions += $object
}
$object = New-Object PrintMessage("Importing Dell Connections Hardware Library MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetEqualLogicImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing Dell Operations Common Library MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Common",$dellMP.GetEqualLogicImportDir("Dell.OperationsLibrary.Common.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing EqualLogic Model MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.EqualLogic",$dellMP.GetEqualLogicImportDir("Dell.Model.EqualLogic.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing EqualLogic Operations Library MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.EqualLogic",$dellMP.GetEqualLogicImportDir("Dell.OperationsLibrary.EqualLogic.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing EqualLogic View MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.EqualLogic",$dellMP.GetEqualLogicImportDir("Dell.View.EqualLogic.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing EqualLogic Monitoring MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.EqualLogic.Impl",$dellMP.GetEqualLogicImportDir("Dell.EqualLogic.Impl.mp"))
$fmpactions += $object

if($EQL41Present -eq $true -or $scomenv.IsSCOM2012() -eq $false)
{
$object = New-Object PrintMessage("Importing EqualLogic OM07 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.EqualLogic.OM07",$dellMP.GetEqualLogicImportDir("Dell.EqualLogic.OM07.mp"))
$fmpactions += $object
}

if ($EQL41Present -eq $true)
{
$object = New-Object PrintMessage("Transfering EqualLogic 4.1 overrides to EqualLogic 5.0 ...")
$fmpactions += $object
$object = New-Object TransferOverrides(5, $eql_Overrides)
$fmpactions += $object
}
if($scomenv.IsSCOM2012() -eq $true)
{
$object = New-Object PrintMessage("Importing EqualLogic OM12 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.EqualLogic.OM12",$dellMP.GetEqualLogicImportDir("Dell.EqualLogic.OM12.mp"))
$fmpactions += $object
}
if (($EQL41Present -eq $true -or $EQLOM07Present -eq $true) -and $scomenv.IsSCOM2012() -eq $true)
{
$eqlOM07Overrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrdOld"), $dellMP.GetExportDir("CollectOvrdNew"), $true)
$eqlOM07Overrides.CollectOverrideMPsFor("Dell.EqualLogic.OM07")
$object = New-Object PrintMessage("Transfering EqualLogic 5.0 (OM07) overrides to EqualLogic 5.0 (OM12) ...")
$fmpactions += $object
$fmpactions += $eqlOM07Overrides
$object = New-Object TransferOverrides(6, $eqlOM07Overrides)
$fmpactions += $object
}
}
elseif($DetailedPresent -eq $true)
{
$object = New-Object DeleteOptions("Dell.EqualLogic.DetailedMonitoringOn",$true)
$fmpactions += $object
}
else
{
Write-Info -msg ("WARNING: Required Management Packs have been already Imported")
}

}
elseif ($mpActionType -eq "EQLSetToDetailed")
{
$DetailedPresent = chkMPPresence("Dell.EqualLogic.DetailedMonitoringOn")
#Check if Om12 mp is absent and trigger upgrade
$EQLOM12Present = chkMPPresence("Dell.EqualLogic.OM12")
if($force -eq $false)
{
Write-Info -msg ("WARNING: Management Packs could not be Imported/Removed")
Write-Info -msg ("WARNING: To still proceed, run with Auto Resolve Warnings/Errors set to true")
}
# Check EQL12 mp is absent and trigger mp upgrade from 5x to 5x
elseif($DetailedPresent -eq $false -or $EQLOM12Present -eq $false)
{
$EQL41Present = chkMPPresence("Dell.Storage.EqualLogic")
$EQLOM07Present = chkMPPresence("Dell.EqualLogic.OM07")
# upgrade 4.1 to 5.0
if ($EQL41Present -eq $true)
{
$eql_Overrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrdEQL"), $dellMP.GetExportDir("CollectOvrdEQLNew"), $false)
$eql_Overrides.CollectOverrideMPsFor("Dell.Storage.EqualLogic")
$fmpactions += $eql_Overrides

Write-Info -msg "INFO: EqualLogic 4.1 present. Upgrading EqualLogic 4.1 as well"

$object = New-Object DeleteOptions("Dell.Storage.EqualLogic.DetailedMonitoringOn",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Storage.EqualLogic",$true)
$fmpactions += $object
}
# Set to Detailed
$object = New-Object PrintMessage("Importing Dell Connections Hardware Library MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetEqualLogicImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing Dell Operations Common Library MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Common",$dellMP.GetEqualLogicImportDir("Dell.OperationsLibrary.Common.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing EqualLogic Model MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.EqualLogic",$dellMP.GetEqualLogicImportDir("Dell.Model.EqualLogic.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing EqualLogic Operations Library MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.EqualLogic",$dellMP.GetEqualLogicImportDir("Dell.OperationsLibrary.EqualLogic.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing EqualLogic View MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.EqualLogic",$dellMP.GetEqualLogicImportDir("Dell.View.EqualLogic.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing EqualLogic Monitoring MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.EqualLogic.Impl",$dellMP.GetEqualLogicImportDir("Dell.EqualLogic.Impl.mp"))
$fmpactions += $object

if($EQL41Present -eq $true -or $scomenv.IsSCOM2012() -eq $false)
{
$object = New-Object PrintMessage("Importing EqualLogic OM07 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.EqualLogic.OM07",$dellMP.GetEqualLogicImportDir("Dell.EqualLogic.OM07.mp"))
$fmpactions += $object
}


if($scomenv.IsSCOM2012() -eq $true)
{
$object = New-Object PrintMessage("Importing EqualLogic OM12 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.EqualLogic.OM12",$dellMP.GetEqualLogicImportDir("Dell.EqualLogic.OM12.mp"))
$fmpactions += $object
}
$object = New-Object PrintMessage("Importing Dell EqualLogic Detail Monitoring On MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.EqualLogic.DetailedMonitoringOn",$dellMP.GetEqualLogicImportDir("Dell.EqualLogic.DetailedMonitoringOn.mp"))
$fmpactions += $object
if ($EQL41Present -eq $true)
{
$object = New-Object PrintMessage("Transfering EqualLogic 4.1 overrides to EqualLogic 5.0 ...")
$fmpactions += $object
$object = New-Object TransferOverrides(5, $eql_Overrides)
$fmpactions += $object
}

if (($EQL41Present -eq $true -or $EQLOM07Present -eq $true) -and $scomenv.IsSCOM2012() -eq $true)
{
$eqlOM07Overrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrdOld"), $dellMP.GetExportDir("CollectOvrdNew"), $true)
$eqlOM07Overrides.CollectOverrideMPsFor("Dell.EqualLogic.OM07")
$object = New-Object PrintMessage("Transfering EqualLogic 5.0 (OM07) overrides to EqualLogic 5.0 (OM12) ...")
$fmpactions += $object
$fmpactions += $eqlOM07Overrides
$object = New-Object TransferOverrides(6, $eqlOM07Overrides)
$fmpactions += $object
}
}
else
{
Write-Info -msg ("WARNING: Required Management Packs have been already Imported")
}
}
elseif ($mpActionType -eq "OOBSetToScalable")
{
if($scomenv.IsSCOM2012() -eq $true)
{
$DetailedPresent = chkMPPresence("Dell.Server.OOB.DetailedMonitoringOn")
if ($DetailedPresent -eq $false -or $force -eq $true)
{
$msTemplate = chkMSOOBTemplatePresence
if ($msTemplate -eq "True")
{
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.Server",$dellMP.GetImportDir("Dell.Model.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Server",$dellMP.GetImportDir("Dell.OperationsLibrary.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.Server",$dellMP.GetImportDir("Dell.View.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Common", $dellMP.GetImportDir("Dell.OperationsLibrary.Common.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Server.OOB",$dellMP.GetImportDir("Dell.Server.OOB.mp"))
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Server.OOB.DetailedMonitoringOn",$true)
$fmpactions += $object
}
}
else
{
Write-Info -msg ("WARNING: You may lose detailed monitoring information")
Write-Info -msg ("WARNING: To proceed, run with Auto Resolve Warnings/Errors set to true")
}
}
else
{
Write-Info -msg ("INFO: Set to Server (Agent-free) Scalable Feature - is not supported SCOM 2007 R2/SCE 2010 ")
}
}
elseif ($mpActionType -eq "OOBSetToDetailed")
{
if($scomenv.IsSCOM2012() -eq $true)
{
$msTemplate = chkMSOOBTemplatePresence
if ($msTemplate -eq "True")
{
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.Server",$dellMP.GetImportDir("Dell.Model.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Server",$dellMP.GetImportDir("Dell.OperationsLibrary.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.Server",$dellMP.GetImportDir("Dell.View.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Common", $dellMP.GetImportDir("Dell.OperationsLibrary.Common.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Server.OOB",$dellMP.GetImportDir("Dell.Server.OOB.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Server.OOB.DetailedMonitoringOn",$dellMP.GetImportDir("Dell.Server.OOB.DetailedMonitoringOn.mp"))
$fmpactions += $object
}
}
else
{
Write-Info -msg ("INFO: Set to Server (Agent-free) Detailed Feature - is not supported SCOM 2007 R2/SCE 2010 ")
}
}
elseif ($mpActionType -eq "CMC41Import" -or $mpActionType -eq "CBC41Import" -or $mpActionType -eq "DRAC41Import")
{
if ($mpActionType -eq "DRAC41Import")
{
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.Get41ImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OutOfBand.DRAC",$dellMP.Get41ImportDir("Dell.OutOfBand.DRAC.mp"))
$fmpactions += $object
}
else
{
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.Get41ImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OutOfBand.CMC",$dellMP.Get41ImportDir("Dell.OutOfBand.CMC.mp"))
$fmpactions += $object
}
if ($mpActionType -eq "CBC41Import")
{
$object = New-Object ImportOptions("Dell.WindowsServer.Scalable",$dellMP.Get41ImportDir("Dell.WindowsServer.Scalable.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.ChassisModularServer.Correlation",$dellMP.Get41ImportDir("Dell.ChassisModularServer.Correlation.mp"))
$fmpactions += $object
}
$bootstrapMPDir = 'C:\Dell Management Packs\Server Mgmt Suite\4.1\Overrides'
$mpexts = @( 'mp', 'xml')
foreach ($mpext in $mpexts)
{
$fullPath = get-childitem $bootstrapMPDir -recurse -filter ('*.' + $mpext)
if ($fullpath -ne $null -and $fullpath.Count -ne $null)
{
foreach ($path in $fullpath)
{
$object = New-Object ImportOptions( ($path.Name -replace ('.'+$mpext), ''), $path.FullName)
$fmpactions += $object
}
}
elseif ($fullpath -ne $null)
{
$object = New-Object ImportOptions( ($fullpath.Name -replace '.mp', ''), $fullpath.FullName)
$fmpactions += $object
}
}
}
elseif ($mpActionType -eq "CollectOverrides")
{
$om07Overrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrdx"), $dellMP.GetExportDir("CollectOvrdy"), $true)
$om07Overrides.CollectOverrideMPsFor("Dell.Model.CMC")
$om07Overrides.CollectOverrideMPsFor("Dell.CMC.OM07")
$om07Overrides.CollectOverrideMPsFor("Dell.OperationsLibrary.CMC")
$fmpactions += $om07Overrides
$object = New-Object TransferOverrides(2, $om07Overrides)
$fmpactions += $object
}
elseif ($mpActionType -eq "CMCScalableImport")
{
$CMCDetailedPresent = chkMPPresence("Dell.Chassis.Detailed")
if($CMCDetailedPresent -eq $false -or $force -eq $true)
{
$CMC41Present = chkMPPresence("Dell.OutOfBand.CMC")
$CBCPresent = chkMPPresence("Dell.ChassisModularServer.Correlation")
$CMCOM07Present = chkMPPresence("Dell.CMC.OM07")
$CMCOM12Present = chkMPPresence("Dell.CMC.OM12")
$cmc_cbcOverrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrdOld"), $dellMP.GetExportDir("CollectOvrdNew"), $false)
if ($CMC41Present -eq $true -and $CBCPresent -eq $true)
{
$cmc_cbcOverrides.CollectOverrideMPsFor("Dell.ChassisModularServer.Correlation")
}

if ($CMC41Present -eq $true)
{
$cmc_cbcOverrides.CollectOverrideMPsFor("Dell.OutOfBand.CMC")
}

$fmpactions += $cmc_cbcOverrides

if ($CMC41Present -eq $true -and $CBCPresent -eq $true)
{
Write-Info -msg "INFO: CBC 4.1 present. Upgrading CBC 4.1 as well"
# CBC must be 4.1 version
$object = New-Object DeleteOptions("Dell.ChassisModularServer.Correlation",$true, $false)
$fmpactions += $object
}

if ($CMC41Present -eq $true)
{
Write-Info -msg "INFO: CMC 4.1 present. Upgrading CMC 4.1 as well"
# CMC must be 4.1 version
$object = New-Object DeleteOptions("Dell.OutOfBand.CMC",$true, $false)
$fmpactions += $object
}

$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Import CMC Dependent MPs ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Common",$dellMP.GetImportDir("Dell.OperationsLibrary.Common.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.CMC",$dellMP.GetImportDir("Dell.Model.CMC.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.CMC",$dellMP.GetImportDir("Dell.OperationsLibrary.CMC.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.CMC",$dellMP.GetImportDir("Dell.View.CMC.mp"))
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Chassis.Detailed",$true)
$fmpactions += $object

if($CMC41Present -eq $true -or $scomenv.IsSCOM2012() -eq $false)
{
$object = New-Object PrintMessage("Import CMC OM07 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.CMC.OM07",$dellMP.GetImportDir("Dell.CMC.OM07.mp"))
$fmpactions += $object
}


if($scomenv.IsSCOM2012() -eq $true)
{
$object = New-Object PrintMessage("Import CMC OM12 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.CMC.OM12",$dellMP.GetImportDir("Dell.CMC.OM12.mp"))
$fmpactions += $object
}

if ($CMC41Present -eq $true -and $CBCPresent -eq $true)
{
$object = New-Object PrintMessage("INFO: Importing Chassis Blade Correlation as it was deleted during this session.")
$fmpactions += $object
$object = New-Object PrintMessage("INFO: Import Server MPs ...")
$fmpactions += $object
# Reimporting since 4.1 CBC was removed earlier while upgrading CMC 4.1
$object = New-Object ImportOptions("Dell.Model.Server",$dellMP.GetImportDir("Dell.Model.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.ChassisModularServer.Correlation",$dellMP.GetImportDir("Dell.ChassisModularServer.Correlation.mp"))
$fmpactions += $object
}

if ($CMC41Present -eq $true)
{
$object = New-Object PrintMessage("Transfering CMC 4.1 overrides to CMC 5.x ...")
$fmpactions += $object
$object = New-Object TransferOverrides(1, $cmc_cbcOverrides)
$fmpactions += $object
}

if ( ($CMC41Present -eq $true -or $CMCOM07Present -eq $true) -and $scomenv.IsSCOM2012() -eq $true)
{
$om07Overrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrrdOld"), $dellMP.GetExportDir("CollectOvrrdNew"), $true)
$om07Overrides.CollectOverrideMPsFor("Dell.Model.CMC")
$om07Overrides.CollectOverrideMPsFor("Dell.CMC.OM07")
$om07Overrides.CollectOverrideMPsFor("Dell.OperationsLibrary.CMC")
$object = New-Object PrintMessage("Transfering CMC 5.x (OM07) overrides to CMC 5.x (OM12) ...")
$fmpactions += $object
$fmpactions += $om07overrides
$object = New-Object TransferOverrides(2, $om07Overrides)
$fmpactions += $object
}

if (($CMC41Present -eq $true) -or ($CMCOM07Present -eq $true))
{
Write-Info -msg "INFO: Recreate or verify your instance level overrides and custom groups since it may have been affected during the upgrade operation."
}
}
else
{
Write-Info -msg ("WARNING: You may lose chassis detailed monitoring information")
Write-Info -msg ("WARNING: To proceed, run with Auto Resolve Warnings/Errors set to true")
Write-Info -msg "INFO: For Upgrade, close all CMC related alerts prior to the operation."
Write-Info -msg "INFO: Consider taking a backup of CMC override references."
Write-Info -msg "WARNING: During the upgrade operation, note the following: "
Write-Info -msg " 1. You may lose instance level overrides."
Write-Info -msg " 2. You may lose custom groups"
}
}
elseif ($mpActionType -eq "CMCDetailedImport")
{
if($scomenv.IsSCOM2012() -eq $true)
{
$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing CMC Dependent MPs ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Common",$dellMP.GetImportDir("Dell.OperationsLibrary.Common.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.CMC",$dellMP.GetImportDir("Dell.Model.CMC.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.CMC",$dellMP.GetImportDir("Dell.OperationsLibrary.CMC.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.CMC",$dellMP.GetImportDir("Dell.View.CMC.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Importing CMC OM12 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.CMC.OM12",$dellMP.GetImportDir("Dell.CMC.OM12.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Import CMC Detailed MP and its dependent MPs...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Chassis.Detailed",$dellMP.GetImportDir("Dell.Chassis.Detailed.mp"))
$fmpactions += $object
}
else
{
Write-Info -msg ("INFO: Set to Chassis Detailed Feature - is not supported SCOM 2007 R2")
}
}
elseif ($mpActionType -eq "CMCRemove")
{
if($force -eq $true)
{
# Remove Feature
$isChassisDetailedPresent = chkMPPresence("Dell.Chassis.Detailed")
if ($isChassisDetailedPresent -eq $true)
{
$object = New-Object DeleteOptions("Dell.Chassis.Detailed",$true)
$fmpactions += $object
}
$isCBCMPPresent=chkMPPresence("Dell.ChassisModularServer.Correlation")
$is41CMCMPPresent=chkMPPresence("Dell.OutOfBand.CMC")
if ($isCBCMPPresent -eq $true -and $is41CMCMPPresent -eq $true)
{
Write-Info -msg ("INFO: Chassis Blade Correlation is dependent on CMC MP")
Write-Info -msg ("INFO: Chassis monitoring MPs will not be deleted")
Write-Info -msg ("INFO: Re-do this task after Removing Chassis Blade Correlation feature ")
}
elseif ($is41CMCMPPresent -eq $true)
{
$object = New-Object DeleteOptions("Dell.OutOfBand.CMC",$true)
$fmpactions += $object
}
else
{
if($scomenv.IsSCOM2012() -eq $true)
{
$object = New-Object DeleteOptions("Dell.CMC.OM12",$true)
$fmpactions += $object
}
$object = New-Object DeleteOptions("Dell.CMC.OM07",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.View.CMC",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.OperationsLibrary.CMC",$true)
$fmpactions += $object
}

if ($isCBCMPPresent -eq $false)
{
$object = New-Object DeleteOptions("Dell.Model.CMC",$false)
$fmpactions += $object
}
}
else
{
Write-Info -msg ("WARNING: To run this task, Auto Resolve Warnings/Errors should be true")
}
}
elseif ($mpActionType -eq "DRACImport")
{
if($force -eq $true)
{
$DRAC41Present = chkMPPresence("Dell.OutOfBand.DRAC")
$DRACOM07Present = chkMPPresence("Dell.DRAC.OM07")
$DRACOM12Present = chkMPPresence("Dell.DRAC.OM12")
$DRAC_cbcOverrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrdDrac"), $dellMP.GetExportDir("CollectOvrdDracNew"), $false)
if ($DRAC41Present -eq $true)
{
$DRAC_cbcOverrides.CollectOverrideMPsFor("Dell.OutOfBand.DRAC")
}
$fmpactions += $DRAC_cbcOverrides
if ($DRAC41Present -eq $true)
{
Write-Info -msg "INFO: DRAC 4.1 present. Upgrading DRAC 4.1 as well"
# DRAC must be 4.1 version
$object = New-Object DeleteOptions("Dell.OutOfBand.DRAC",$true, $false)
$fmpactions += $object
}


$object = New-Object ImportOptions("Dell.Connections.HardwareLibrary",$dellMP.GetImportDir("Dell.Connections.HardwareLibrary.mp"))
$fmpactions += $object
$object = New-Object PrintMessage("Import DRAC Dependent MPs ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Common",$dellMP.GetImportDir("Dell.OperationsLibrary.Common.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.Model.DRAC",$dellMP.GetImportDir("Dell.Model.DRAC.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.DRAC",$dellMP.GetImportDir("Dell.OperationsLibrary.DRAC.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.DRAC",$dellMP.GetImportDir("Dell.View.DRAC.mp"))
$fmpactions += $object

if($DRAC41Present -eq $true -or $scomenv.IsSCOM2012() -eq $false)
{
$object = New-Object PrintMessage("Import DRAC OM07 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.DRAC.OM07",$dellMP.GetImportDir("Dell.DRAC.OM07.mp"))
$fmpactions += $object
}

if($scomenv.IsSCOM2012() -eq $true)
{
$object = New-Object PrintMessage("Import DRAC OM12 MP ...")
$fmpactions += $object
$object = New-Object ImportOptions("Dell.DRAC.OM12",$dellMP.GetImportDir("Dell.DRAC.OM12.mp"))
$fmpactions += $object
}

if ($DRAC41Present -eq $true)
{
$object = New-Object PrintMessage("Transfering DRAC 4.1 overrides to DRAC 5.x ...")
$fmpactions += $object
$object = New-Object TransferOverrides(3, $DRAC_cbcOverrides)
$fmpactions += $object
}

if ( ($DRAC41Present -eq $true -or $DRACOM07Present -eq $true) -and $scomenv.IsSCOM2012() -eq $true)
{
$om07Overrides = New-Object CollectOverrides($dellMP.GetExportDir("CollectOvrdOld"), $dellMP.GetExportDir("CollectOvrdNew"), $true)
$om07Overrides.CollectOverrideMPsFor("Dell.Model.DRAC")
$om07Overrides.CollectOverrideMPsFor("Dell.DRAC.OM07")
$om07Overrides.CollectOverrideMPsFor("Dell.OperationsLibrary.DRAC")
$object = New-Object PrintMessage("Transfering DRAC 5.x (OM07) overrides to DRAC 5.x (OM12) ...")
$fmpactions += $object
$fmpactions += $om07overrides
$object = New-Object TransferOverrides(4, $om07Overrides)
$fmpactions += $object
}
if (($DRAC41Present -eq $true) -or ($DRACOM07Present -eq $true))
{
Write-Info -msg "INFO: Recreate or verify your instance level overrides and custom groups since it may have been affected during the upgrade operation."
}
if ($DRAC41Present -eq $true)
{
Write-Info -msg "INFO: All the overrides on iDRAC class(4.x) are transferred only to iDRAC6 Monolithic(5.x) and not to iDRAC6 Modular(5.x) class. You may need to replicate them for iDRAC6 Modular (5.x) class."
}
}
else
{
Write-Info -msg "INFO: Close all DRAC related alerts prior to the upgrade operation."
Write-Info -msg "INFO: Consider taking a backup of DRAC override references."
Write-Info -msg "WARNING: During the upgrade operation, note the following: "
Write-Info -msg " 1. You may lose instance level overrides."
Write-Info -msg " 2. You may lose custom groups"
Write-Info -msg " 3. All the overrides on iDRAC class(4.x) will be transferred only to iDRAC6 Monolithic(5.x) and not to iDRAC6 Modular(5.x) class. You may need to replicate them for iDRAC6 Modular (5.x) class after the upgrade."
Write-Info -msg "INFO: To proceed, run this task again with the override: Auto Resolve Warnings/Errors set to true."
}
}
elseif ($mpActionType -eq "DRACRemove")
{
if($force -eq $false)
{
Write-Info -msg ("WARNING: To run this task, Auto Resolve Warnings/Errors should be true")
}
else
{
$is41DRACMPPresent=chkMPPresence("Dell.OutOfBand.DRAC")
if ($is41DRACMPPresent -eq $true)
{
$object = New-Object DeleteOptions("Dell.OutOfBand.DRAC",$true)
$fmpactions += $object
}
else
{
if($scomenv.IsSCOM2012() -eq $true)
{
$object = New-Object DeleteOptions("Dell.DRAC.OM12",$true)
$fmpactions += $object
}
$object = New-Object DeleteOptions("Dell.DRAC.OM07",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.View.DRAC",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.OperationsLibrary.DRAC",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Model.DRAC",$true)
$fmpactions += $object
}
}
}
elseif ($mpActionType -eq "EQLRemove")
{
if($force -eq $false)
{
Write-Info -msg ("WARNING: To run this task, Auto Resolve Warnings/Errors should be true")
}
else
{
$is41EQLMPPresent=chkMPPresence("Dell.Storage.EqualLogic")
$is41EQLDetailedMPPresent=chkMPPresence("Dell.Storage.EqualLogic.DetailedMonitoringOn")
$isEQLDetailedMPPresent=chkMPPresence("Dell.EqualLogic.DetailedMonitoringOn")
if ($is41EQLDetailedMPPresent -eq $true)
{
$object = New-Object DeleteOptions("Dell.Storage.EqualLogic.DetailedMonitoringOn",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Storage.EqualLogic",$true)
$fmpactions += $object
}
elseif ($is41EQLMPPresent -eq $true)
{
$object = New-Object DeleteOptions("Dell.Storage.EqualLogic",$true)
$fmpactions += $object
}
else
{
if ($isEQLDetailedMPPresent -eq $true)
{
$object = New-Object DeleteOptions("Dell.EqualLogic.DetailedMonitoringOn",$true)
$fmpactions += $object
}
$object = New-Object DeleteOptions("Dell.EqualLogic.OM12",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.EqualLogic.OM07",$true)
$fmpactions += $object

$object = New-Object DeleteOptions("Dell.EqualLogic.Impl",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.View.EqualLogic",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.OperationsLibrary.EqualLogic",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Model.EqualLogic",$true)
$fmpactions += $object
}
}
}
elseif ($mpActionType -eq "CBCImport")
{
$isCMC41Pre=chkMPPresence("Dell.OutOfBand.CMC")
$isCMCModelPre=chkMPPresence("Dell.Model.CMC")
$isInbandServerPre=chkMPPresence("Dell.WindowsServer.Scalable")
$isModelServerPre=chkMPPresence("Dell.Model.Server")
if($isCMC41Pre -eq $true)
{
Write-Info -msg ("INFO: Chassis Monitoring Feature 4.1 is present.")
Write-Info -msg ("INFO: Chassis Blade Correlation 6.0 requires Chassis Monitoring to be upgraded first to 6.0")
Write-Info -msg ("INFO: Use Feature Monitoring Dashboard to upgrade Chassis Monitoring")
Write-Info -msg ("INFO: and then upgrade Chassis Blade Correlation Feature")
}
else
{
if($isCMCModelPre -eq $false)
{
Write-Info -msg ("INFO: Chassis Blade Correlation 6.0 requires Chassis Monitoring 6.0")
Write-Info -msg ("INFO: Chassis Models will be imported.")
$object = New-Object ImportOptions("Dell.Model.CMC",$dellMP.GetImportDir("Dell.Model.CMC.mp"))
$fmpactions += $object
}

if($isCMCModelPre -eq $true)
{
$MPLocRegKeyPath = "HKLM:\software\Dell\Dell Server Management Pack Suites";
$mpLoc = $null;
$mpLoc = Get-ItemProperty -path:$MPLocRegKeyPath -name:$KeyToFind -ErrorAction:SilentlyContinue;
$ServerRegistryVersion = $mpLoc.CurrentVersion;
$mpDetails = GetMPDetails("Dell.Model.CMC")
if( $ServerRegistryVersion.Length -eq 3 ){
$mpVer=([string]$mpDetails.Version).Substring(0,3);
}
if( $ServerRegistryVersion.Length -eq 5){
$mpVer=([string]$mpDetails.Version).Substring(0,5);
}
if($mpVer.CompareTo($ServerRegistryVersion) -ne 0){
Write-Info -msg ("INFO: Chassis Blade Correlation 6.0 requires Chassis Model 6.0")
Write-Info -msg ("INFO: upgrading Chassis Model to latest version")
$object = New-Object ImportOptions("Dell.Model.CMC",$dellMP.GetImportDir("Dell.Model.CMC.mp"))
$fmpactions += $object
}
}

if ($isModelServerPre -eq $false)
{
Write-Info -msg ("INFO: Chassis Blade Correlation 6.0 requires Server Agent-free Monitoring 6.0")
Write-Info -msg ("INFO: Server Models will be imported.")
$object = New-Object ImportOptions("Dell.Model.Server",$dellMP.GetImportDir("Dell.Model.Server.mp"))
$fmpactions += $object
}

if ($isInbandServerPre -eq $false)
{
Write-Info -msg ("INFO: Chassis Blade Correlation 6.0 requires Server Agent-based Monitoring 6.0")
Write-Info -msg ("INFO: Server Agent-based Management Pack will be imported.")
$object = New-Object ImportOptions("Dell.OperationsLibrary.Common",$dellMP.GetImportDir("Dell.OperationsLibrary.Common.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.OperationsLibrary.Server",$dellMP.GetImportDir("Dell.OperationsLibrary.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.View.Server",$dellMP.GetImportDir("Dell.View.Server.mp"))
$fmpactions += $object
$object = New-Object ImportOptions("Dell.WindowsServer.Scalable",$dellMP.GetImportDir("Dell.WindowsServer.Scalable.mp"))
$fmpactions += $object
}
$object = New-Object ImportOptions("Dell.ChassisModularServer.Correlation",$dellMP.GetImportDir("Dell.ChassisModularServer.Correlation.mp"))
$fmpactions += $object
if ($isCMCModelPre -eq $false)
{
$object = New-Object PrintMessage("INFO: Only Chassis Models will be imported.")
$fmpactions += $object
$object = New-Object PrintMessage("INFO: Import Chassis Monitoring 6.0 to discover Chassis")
$fmpactions += $object
}
if ($isModelServerPre -eq $false)
{
$object = New-Object PrintMessage("INFO: Only Server OOB Models will been imported.")
$fmpactions += $object
$object = New-Object PrintMessage("INFO: Import Server OOB Monitoring 6.0 to discover Servers via Agent-free Monitoring")
$fmpactions += $object
}
}
}
elseif ($mpActionType -eq "CBCRemove")
{
# Remove Feature
$object = New-Object DeleteOptions("Dell.ChassisModularServer.Correlation",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Model.Server",$false)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Model.CMC",$false)
$fmpactions += $object
}
elseif ($mpActionType -eq "InfoAlertsOn")
{
# Turn on Info Alerts
$object = New-Object ImportOptions("Dell.WindowsServer.InformationAlertsOn",$dellMP.GetImportDir("Dell.WindowsServer.InformationAlertsOn.mp"))
$fmpactions += $object
}
elseif ($mpActionType -eq "InfoAlertsOff")
{
if($force -eq $true)
{
# Turn off Info Alerts
$object = New-Object DeleteOptions("Dell.WindowsServer.InformationAlertsOn",$true)
$fmpactions += $object
}
else
{
Write-Info -msg ("WARNING: To run this task, Auto Resolve Warnings/Errors should be true")
}
}
elseif ($mpActionType -eq "ServerIBRemove")
{
if($force -eq $true)
{
$isOOBPresent=chkMPPresence("Dell.Server.OOB")
$isCBCMPPresent=chkMPPresence("Dell.ChassisModularServer.Correlation")

if ($isCBCMPPresent -eq $false)
{
# Remove Feature
$object = New-Object DeleteOptions("Dell.WindowsServer.InformationAlertsOn",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.WindowsServer.Detailed",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.WindowsServer.Scalable",$true)
$fmpactions += $object

if ($isOOBPresent -eq $false)
{
$object = New-Object DeleteOptions("Dell.View.Server",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.OperationsLibrary.Server",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Model.Server",$false)
$fmpactions += $object
}
}
else
{
Write-Info -msg ("INFO: Chassis Blade Correlation is dependent on Server Agent-based MP")
Write-Info -msg ("INFO: Server Agent-based monitoring MPs will not be deleted")
Write-Info -msg ("INFO: Re-do this task after Removing Chassis Blade Correlation feature ")
}
}
else
{
Write-Info -msg ("WARNING: To run this task, Auto Resolve Warnings/Errors should be true")
}
}
elseif ($mpActionType -eq "ServerIBEnableProxying")
{
$scomenv.EnableProyxingForInBandServers()
}
elseif ($mpActionType -eq "ServerOOBRemove")
{
if($force -eq $true)
{
# Remove Feature
$isMPPresent=chkMPPresence("Dell.WindowsServer.Scalable")
$isCBCMPPresent=chkMPPresence("Dell.ChassisModularServer.Correlation")
$isChassisDetailedPresent=chkMPPresence("Dell.Chassis.Detailed")

$object = New-Object DeleteOptions("Dell.Server.OOB.DetailedMonitoringOn",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.Server.OOB",$true)
$fmpactions += $object
if($isMPPresent -eq $false)
{
$object = New-Object DeleteOptions("Dell.View.Server",$true)
$fmpactions += $object
$object = New-Object DeleteOptions("Dell.OperationsLibrary.Server",$true)
$fmpactions += $object
if($isCBCMPPresent -eq $false)
{
$object = New-Object DeleteOptions("Dell.Model.Server",$false)
$fmpactions += $object
}
}

}
else
{
Write-Info -msg ("WARNING: To run this task, Auto Resolve Warnings/Errors should be true")
}
}
elseif ($mpActionType -eq "SetPreferredMonitoringTask")
{
$object = new-object SetPreferredMonitoringTask($PreferredMethod)
$fmpactions += New-Object DeleteOptions($object.mpname,$true)
$fmpactions += $object
Write-Info -msg ("Configured the Set Preferred Monitoring Discovery")
}
elseif ($mpActionType -eq "RefreshFMPDashboard")
{
#This Refresh task is called only to update the FMP dash board. As by default every task will trigger the event 398 the refresh t ask also triggers 398
#and goes away. When event is triggered the triggered discovery will run and update the FMP dash board suitably
Write-Info -msg ("Generating event in windows event log in order to refresh the dashboard...")
}
elseif ($mpActionType -eq "RefreshNodeCount")
{
#This Refresh task is called only to update the FMP dash board. As by default every task will trigger the event 398 the refresh t ask also triggers 398
#and goes away. When event is triggered the triggered discovery will run and update the FMP dash board suitably
Write-Info -msg ("Generating event in windows event log in order to refresh the node count...")
}
elseif ($mpActionType -eq "AssociateRunAsAccount")
{
Write-Info -msg ("Starting Run AS Account association...")
AssociateRunasAccount
}

#### END CODE LOGIC GOES HERE


foreach ($f in $fmpactions)
{
$ovrdMP = $null
if ($f.RequiresOverrideMP)
{
############################################################################
# Retrieve the Override Management Pack. If not found, create it
############################################################################
$mpStore = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackFileStore;
$mpStore.AddDirectory($dellMP.GetExportDir($f.mpname));
$ovrdMP = $scomenv.GetManagementPacks() | where-object { $f.mpname -eq $_.Name }
if ($ovrdMP -eq $null)
{
# Create a new management pack, if not present
$ovrdMP = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPack($f.mpname, $f.mpdesc, (New-Object Version(1, 0, 0)), $mpStore);
$mgmtGroup.ImportManagementPack($ovrdMP);
Write-Info -msg ("Creating Override MP: " + $f.mpname)
}
else
{
Write-Info -msg ("Modifying Override MP: " + $f.mpname)
}

############################################################################
# Add/update the required MP References into override MP
############################################################################
foreach ($mpRef in $f.mprefs.Keys)
{
if ($ovrdMP.References.Contains($mpref) -eq $false)
{
# Override MP does not contain the requested MP. Add it to reference list.
$refmp = $scomenv.GetManagementPacks() | where { $_.Name -eq $f.mprefs[$mpRef] }
$mprefcons = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackReference($refmp, $refmp.Name, $refmp.KeyToken, $refmp.Version);
$ovrdMP.References.Add($mpref, $mprefcons)
Write-Info -msg "Adding: $mpref"
} elseif ($ovrdMP.References[$mpref].Version -lt $refmp.Version) {
# Override MP contains the requested MP, but the reference is less than required version. Update
$refmp = $scomenv.GetManagementPacks() | where { $_.Name -eq $f.mprefs[$mpRef] }
$mprefcons = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackReference($refmp, $refmp.Name, $refmp.KeyToken, $refmp.Version);
$ovrdMP.References.Remove($mpref)
$ovrdMP.References.Add($mpref, $mprefcons)
Write-Info -msg "Adding: $mpref"
}
}
}
switch($f.type)
{
'Export' {
$mpXmlWriter = New-Object Microsoft.EnterpriseManagement.Configuration.IO.ManagementPackXmlWriter($f.exportdir);

$exportMP = $scomenv.GetManagementPacks() | where-object { $f.mp -eq $_.Name }
if($exportMP -ne $null)
{
if ($f.recurse -eq $true)
{
$scomenv.GetManagementPacks() | ForEach-Object {
$scommp = $_
$scommp.References | ForEach-Object {
if ($_.Name -eq $f.mp)
{
Write-Output( "Export Management Pack (dep)" + $scomm.Name)
$mpXmlWriter.WriteManagementPack($scommp)
}
}
}
}
Write-Output("Export Management Pack " + $exportMP.Name)
$mpXmlWriter.WriteManagementPack($exportMP)
}
}

'CollectOverridesAction' {
DoCollectOverrides -collectoverrides $f
}
'Delete' {
DoDeleteMP -mptodelete $f.mp -recursedelete $f.recurse -collectoverrides $f.ovrds -noexecute $f.noexecute
}
'DiscoveryRuleOverride' {
$discRuleOverrideStatus = $true
$discRuleOverrideMessage = 'Done'
############################################################################
# Find the Discovery Rule
############################################################################
$discoveryTgtClassCriteria = New-Object Microsoft.EnterpriseManagement.Configuration.MonitoringClassCriteria($("Name='{0}'" -f $f.ruleTarget));
$retVal = $mgmtGroup.GetMonitoringClasses($discoveryTgtClassCriteria)
if ($retVal -eq $null -or $retVal.Count -le 0)
{
# Do Error Condition Return
$discRuleOverrideStatus = $false
$discRuleOverrideMessage = 'Discovery Target Class ' + $f.ruleTarget + ' not found.'
}
else
{
$discoveryTgtClass = $retVal[0]
}

if ($discRuleOverrideStatus -eq $true)
{
$discoveryCriteria = New-Object Microsoft.EnterpriseManagement.Configuration.MonitoringDiscoveryCriteria($("Name='{0}'" -f $f.discovery))
$retVal = $discoveryTgtClass.GetMonitoringDiscoveries($discoveryCriteria)
if ($retVal -eq $null -or $retVal.Count -le 0)
{
# Do Error Condition Return
$discRuleOverrideStatus = $false
$discRuleOverrideMessage = 'Discovery Rule ' + $f.discovery + ' not found.'
}
else
{
$discoveryRef = $retVal[0]
}
}

if ($discRuleOverrideStatus -eq $true)
{
###################################################################################
# Check if the override already exists. If yes, update it. Otherwise, create one
###################################################################################
$overrideDisplayName = $f.overrideName
$override = $overrideDisplayName.Replace(" ", [String]::Empty);

$discOverride = $ovrdMP.GetOverrides() | where { $_.Name -eq $override }
if ($discOverride -eq $null)
{
$discOverride = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackDiscoveryConfigurationOverride($ovrdMP, $override);
}
$discOverride.Discovery = $discoveryRef
$discOverride.Context = $discoveryTgtClass
$discOverride.DisplayName= $overrideDisplayName
$discOverride.Parameter= $f.overrideParameter
$discOverride.Value = $f.overrideParameterValue
$discOverride.Module= $f.overrideModule

$overrideDisplayName = $f.overrideName + "_Enabled"
$override = $overrideDisplayName.Replace(" ", [String]::Empty);

$discOverride = $ovrdMP.GetOverrides() | where { $_.Name -eq $override }
if ($discOverride -eq $null)
{
$discOverride = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackDiscoveryPropertyOverride($ovrdMP, $override);
}
$discOverride.Discovery = $discoveryRef
$discOverride.Context = $discoveryTgtClass
$discOverride.DisplayName= $overrideDisplayName
$discOverride.Property = "Enabled"
$discOverride.Value = 'true'

}
else
{
Write-Info -msg ("ERROR: Discovery Rule Override creation failed!")
Write-Info -msg ("ERROR: " + $discRuleOverrideMessage)
}
}
'AddConsoleTask' {
###################################################################################
# Add console task, if not found. Update the latest URL
###################################################################################
$ctaskAddStatus = $true
$ctaskAddMessage = 'Done'
$ConsoleTaskTargetClassCriteria = New-Object Microsoft.EnterpriseManagement.Configuration.MonitoringClassCriteria($("Name='{0}'" -f $f.taskTarget));
$retVal = $mgmtGroup.GetMonitoringClasses($ConsoleTaskTargetClassCriteria)
if ($retVal -eq $null -or $retVal.Count -le 0)
{
# Do Error Condition Return
$ctaskAddStatus = $false
$ctaskAddMessage = ('Could not find the Console Task Target: ' + $f.taskTarget)
}
else
{
$ConsoleTaskTargetClass = $retVal[0]
}

if ($ctaskAddStatus -eq $false)
{
Write-Info -msg ("ERROR: Console Task Creation failed!")
Write-Info -msg ("ERROR: " + $ctaskAddMessage)
}
elseif ($scomenv.IsSCOM2012() -eq $false)
{
$ovrdConsoleTask = $ovrdMP.GetConsoleTasks() | where { $_.Name -eq $f.taskID }
if ($ovrdConsoleTask -eq $null)
{
$ovrdConsoleTask = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackConsoleTask($ovrdMP, $f.taskID, "Public")
}
$ovrdConsoleTask.Application = $f.application
$ovrdConsoleTask.Category = $f.category
$ovrdConsoleTask.DisplayName = $f.taskName
$ovrdConsoleTask.ParameterCollection.Add($f.parameters)
$ovrdConsoleTask.RequireOutput = $f.requireOutput
$ovrdConsoleTask.Target = $ConsoleTaskTargetClass
$ovrdConsoleTask.WorkingDirectory=$f.workDirectory
Write-Info -msg ("Created the Console Task")
}
}
'PrintMessage' {
Write-Info -msg ($f.message)
}
'TransferOverrides' {

for ($cntr = 0; $cntr -lt $f.ovrds.mps.Count; $cntr++)
{
$mpfile = $f.ovrds.mps[$cntr]
$mpoutfile = $f.ovrds.outmps[$cntr]
switch ($f.Operation)
{
1 {
# Transfer Overrides of 4.1 to 5.0
TransferMPOverrides -fileContentPath $mpfile -outputFile $mpoutfile -inputs @(
@{ 'command' = 'SetDefaultMP'; id = 'Dell.OutOfBand.CMC' }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.OutOfBand.CMC' }
@{ 'command' = 'RenameManifestReference';
'id' = "Dell.OutOfBand.CMC";
'newid' = "Dell.Model.CMC"; 'version' = "5.0.0.1"; 'publickey' = "f5205f5754b55108" }
@{ 'command' = 'RenameManifestReference';
'id' = "Dell.ChassisModularServer.Correlation";
'newid' = "Dell.ChassisModularServer.Correlation";
'version' = "5.0.0.1";
'publickey' = "f5205f5754b55108" }
@{ 'command' = 'CreateReferenceIfNotExists'
'newid' = "Dell.CMC.OM07"; 'version' = "5.0.0.1";'publickey' = "f5205f5754b55108" }
@{ 'command' = 'CreateReferenceIfNotExists'
'newid' = "Dell.OperationsLibrary.CMC"; 'version' = "5.0.0.1"; 'publickey' = "f5205f5754b55108" }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.Model.CMC' }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.CMC.OM07' }
@{ 'command' = 'ProcessOverrides';
'UseNetworkStack' = 'SCOM07';
'ChangeTargetIds' = $CMC_ChangeTargetIds;
'ChangeMatchingTargetIds' = $CMC_ChangeMatchingTargetIds;
'RemoveOverrideParameters' = $CMC_RemoveOverrideParameters
'RemoveWorkflows' = $CMC_RemoveWorkflows
'RenameWorkflows' = $CMC_RenameWorkflows }
)
}

2 {

$autogens = ($f.ovrds.autogensuffix + "AutoGeneratedByFMP")
$mpoutfile = $f.ovrds.GetNewOutputFile($f.ovrds.mpnames[$cntr] + "_" + $autogens)
$f.ovrds.outmps[$cntr] = $mpoutfile
$f.ovrds.depoutmps[$f.ovrds.mpnames[$cntr]] = $mpoutfile
# Transfer Overrides of OM07 to OM12
TransferMPOverrides -fileContentPath $mpfile -outputFile $mpoutfile -inputs @(
@{ 'command' = 'RenameManifestReference';
'id' = "Dell.CMC.OM07";
'newid' = "Dell.CMC.OM12";
'version' = "5.0.0.1";
'publickey' = "f5205f5754b55108" }
@{ 'command' = 'RenameMPID';
'id' = $f.ovrds.mpnames[$cntr];
'newid' = $f.ovrds.mpnames[$cntr] + "_" + $autogens; }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.SystemCenter.NetworkDevice.Library";
'newid' = "System.NetworkManagement.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Snmp.Library";
'newid' = "System.Snmp.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.SystemCenter.Library";
'newid' = "Microsoft.SystemCenter.Library";
'version' = "7.0.8427.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.Windows.Library";
'newid' = "Microsoft.Windows.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Library";
'newid' = "System.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Health.Library";
'newid' = "System.Health.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }

@{ 'command' = 'ProcessOverrides';
'UseNetworkStack' = 'SCOM12';
'ChangeTargetIds' = @{} ;
'ChangeMatchingTargetIds' = @{}
'RemoveOverrideParameters' = @{}
'RemoveWorkflows' = @{}
'RenameWorkflows' = @{}
}
)
}

3 {
# Transfer Overrides of 4.1 to 5.0
TransferMPOverrides -fileContentPath $mpfile -outputFile $mpoutfile -inputs @(
@{ 'command' = 'SetDefaultMP'; id = 'Dell.OutOfBand.DRAC' }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.OutOfBand.DRAC' }
@{ 'command' = 'RenameManifestReference';
'id' = "Dell.OutOfBand.DRAC";
'newid' = "Dell.Model.DRAC"; 'version' = "5.0.0.1"; 'publickey' = "f5205f5754b55108" }
@{ 'command' = 'CreateReferenceIfNotExists'
'newid' = "Dell.DRAC.OM07"; 'version' = "5.0.0.1";'publickey' = "f5205f5754b55108" }
@{ 'command' = 'CreateReferenceIfNotExists'
'newid' = "Dell.OperationsLibrary.DRAC"; 'version' = "5.0.0.1"; 'publickey' = "f5205f5754b55108" }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.Model.DRAC' }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.DRAC.OM07' }
@{ 'command' = 'ProcessOverrides';
'UseNetworkStack' = 'SCOM07';
'ChangeTargetIds' = $DRAC_ChangeTargetIds;
'ChangeMatchingTargetIds' = $DRAC_ChangeMatchingTargetIds;
'RemoveOverrideParameters' = $DRAC_RemoveOverrideParameters
'RemoveWorkflows' = $DRAC_RemoveWorkflows
'RenameWorkflows' = $DRAC_RenameWorkflows }
)
}

4 {

$autogens = ($f.ovrds.autogensuffix + "AutoGeneratedByFMP")
$mpoutfile = $f.ovrds.GetNewOutputFile($f.ovrds.mpnames[$cntr] + "_" + $autogens)
$f.ovrds.outmps[$cntr] = $mpoutfile
$f.ovrds.depoutmps[$f.ovrds.mpnames[$cntr]] = $mpoutfile
# Transfer Overrides of OM07 to OM12
TransferMPOverrides -fileContentPath $mpfile -outputFile $mpoutfile -inputs @(
@{ 'command' = 'RenameManifestReference';
'id' = "Dell.DRAC.OM07";
'newid' = "Dell.DRAC.OM12";
'version' = "5.0.0.1";
'publickey' = "f5205f5754b55108" }
@{ 'command' = 'RenameMPID';
'id' = $f.ovrds.mpnames[$cntr];
'newid' = $f.ovrds.mpnames[$cntr] + "_" + $autogens; }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.SystemCenter.NetworkDevice.Library";
'newid' = "System.NetworkManagement.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Snmp.Library";
'newid' = "System.Snmp.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.SystemCenter.Library";
'newid' = "Microsoft.SystemCenter.Library";
'version' = "7.0.8427.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.Windows.Library";
'newid' = "Microsoft.Windows.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Library";
'newid' = "System.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Health.Library";
'newid' = "System.Health.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'ProcessOverrides';
'UseNetworkStack' = 'SCOM12';
'ChangeTargetIds' = @{} ;
'ChangeMatchingTargetIds' = @{}
'RemoveOverrideParameters' = @{}
'RemoveWorkflows' = @{}
'RenameWorkflows' = @{}
}
)
}
5{
# Transfer Overrides of 4.1 to 5.0
TransferMPOverrides -fileContentPath $mpfile -outputFile $mpoutfile -inputs @(
@{ 'command' = 'SetDefaultMP'; id = 'Dell.Storage.EqualLogic' }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.Storage.EqualLogic' }
@{ 'command' = 'RenameManifestReference';
'id' = "Dell.Storage.EqualLogic";
'newid' = "Dell.Model.EqualLogic"; 'version' = "5.0.0.1"; 'publickey' = "f5205f5754b55108" }
@{ 'command' = 'CreateReferenceIfNotExists'
'newid' = "Dell.EqualLogic.Impl"; 'version' = "5.0.0.1";'publickey' = "f5205f5754b55108" }
@{ 'command' = 'CreateReferenceIfNotExists'
'newid' = "Dell.EqualLogic.OM07"; 'version' = "5.0.0.1";'publickey' = "f5205f5754b55108" }
@{ 'command' = 'CreateReferenceIfNotExists'
'newid' = "Dell.OperationsLibrary.EqualLogic"; 'version' = "5.0.0.1"; 'publickey' = "f5205f5754b55108" }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.Model.EqualLogic' }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.EqualLogic.Impl' }
@{ 'command' = 'GetMPAliasName'; id = 'Dell.EqualLogic.OM07' }
@{ 'command' = 'ProcessOverrides';
'UseNetworkStack' = 'SCOM07';
'ChangeTargetIds' = $EQL_ChangeTargetIds;
'ChangeMatchingTargetIds' = $EQL_ChangeMatchingTargetIds;
'RemoveOverrideParameters' = @{}
'RemoveWorkflows' = @{}
'RenameWorkflows' = @{}
}
)
}
6 {

$autogens = ($f.ovrds.autogensuffix + "AutoGeneratedByFMP")
$mpoutfile = $f.ovrds.GetNewOutputFile($f.ovrds.mpnames[$cntr] + "_" + $autogens)
$f.ovrds.outmps[$cntr] = $mpoutfile
$f.ovrds.depoutmps[$f.ovrds.mpnames[$cntr]] = $mpoutfile
# Transfer Overrides of OM07 to OM12
TransferMPOverrides -fileContentPath $mpfile -outputFile $mpoutfile -inputs @(
@{ 'command' = 'RenameManifestReference';
'id' = "Dell.EqualLogic.OM07";
'newid' = "Dell.EqualLogic.OM12";
'version' = "5.0.0.1";
'publickey' = "f5205f5754b55108" }
@{ 'command' = 'RenameMPID';
'id' = $f.ovrds.mpnames[$cntr];
'newid' = $f.ovrds.mpnames[$cntr] + "_" + $autogens; }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.SystemCenter.NetworkDevice.Library";
'newid' = "System.NetworkManagement.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Snmp.Library";
'newid' = "System.Snmp.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.SystemCenter.Library";
'newid' = "Microsoft.SystemCenter.Library";
'version' = "7.0.8427.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "Microsoft.Windows.Library";
'newid' = "Microsoft.Windows.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Library";
'newid' = "System.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'RenameManifestReference';
'id' = "System.Health.Library";
'newid' = "System.Health.Library";
'version' = "7.0.8560.0";
'publickey' = "31bf3856ad364e35" }
@{ 'command' = 'ProcessOverrides';
'UseNetworkStack' = 'SCOM12';
'ChangeTargetIds' = @{} ;
'ChangeMatchingTargetIds' = @{}
'RemoveOverrideParameters' = @{}
'RemoveWorkflows' = @{}
'RenameWorkflows' = @{}
}
)
}
}
}
DoImportOverrides -collectoverrides $f.ovrds
}
'Import' {
Write-Output("Import Management Pack : " + $f.importdir)
if ($f.importdir)
{
$isMpExists= Test-Path $f.importdir
if($isMpExists -eq $false)
{
Write-Info -msg ("INFO: " + $f.mp + " to be imported is not present in Dell Suite installation directory. ")
}
else
{
$v = $scomenv.InstallManagementPack($f.importdir)
if ($v -eq $null -or $v.Count -eq 0)
{
Write-Info -msg ("INFO: " + $f.mp + " imported successfully")
}
else
{
$msg = getExceptionDetails -except $v
if ($msg -match "already imported")
{
Write-Info -msg ("INFO: " + $f.mp + " is already imported")
}
elseif ($msg -match "timeout period elapsed prior to completion of the operation")
{
Write-Info -msg ("ERROR: SCOM Database timeout occurred. You may need to run the task again.")
}
else
{
Write-Info -msg ("ERROR: There were errors in the command.")
Write-Info -msg ("ERROR: " + $msg)
}
}

}
}
else
{
Write-Output("WARNING: Management Pack missing from Dell Management Suite installed directory.")
Write-Output("WARNING: Reinstall the installation to recover.")
}
}
}
if ($f.RequiresOverrideMP)
{
# verify the changes in the override management pack
try {
$ovrdMP.Verify();
Write-Info -msg ("Management Pack Changes verification successful")
} catch [Exception] {
Write-Info -msg ("Management Pack Changes verification failed")
$_ | fl * -Force
if ($logLevel -ge 1)
{
$_ | fl * -Force | Out-File -FilePath $LogFileLocation
}
}

# save the changes into the override management pack
try {
$ovrdMP.AcceptChanges()
Write-Info -msg ("Management Pack Changes applied successfully")
} catch [Exception] {
Write-Info -msg ("Management Pack Changes could not be applied. Exception Details given below")
$_ | fl * -Force
if ($logLevel -ge 1)
{
$_ | fl * -Force | Out-File -FilePath $LogFileLocation
}
}
}
}

#Updating event in OpsMgrLog which will trigger another Discovery since state view may have changed after the execution of an FMPEngine Task


eventcreate /T Information /L "Operations Manager" /ID 398 /D "Dell Feature Monitoring Pack: Task execution detected. Triggering Dell Monitoring Feature instance update in order to refresh Feature Management dashboard." | Out-Null

CreateFMPDashboardRefreshOverride
psDebugLog -level 1 -message ("End of " + $scriptname + " Discovery script ")
psDebugLog -level 1 -message "----------------------------------------------"


</Script></ScriptBody>
<Parameters>
<Parameter>
<Name>scriptname</Name>
<Value>$Config/ScriptName$</Value>
</Parameter>
<Parameter>
<Name>logLevel</Name>
<Value>$Config/LogLevel$</Value>
</Parameter>
<Parameter>
<Name>mpActionType</Name>
<Value>$Config/MPActionType$</Value>
</Parameter>
<Parameter>
<Name>logDirectory</Name>
<Value>$Config/LogDirectory$</Value>
</Parameter>
<Parameter>
<Name>force</Name>
<Value>$Config/Force$</Value>
</Parameter>
<Parameter>
<Name>addonarg1</Name>
<Value>$Config/addonarg1$</Value>
</Parameter>
<Parameter>
<Name>PreferredMethod</Name>
<Value>$Config/PreferredMethod$</Value>
</Parameter>
</Parameters>
<TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
</ProbeAction>
</MemberModules>
<Composition>
<Node ID="PSP"/>
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>Windows!Microsoft.Windows.SerializedObjectData</OutputType>
<InputType>System!System.BaseData</InputType>
</ProbeActionModuleType>