Merry x-mas! In today’s December calendar tips & trick I’m going to a post some useful powershell snippets for Service Manager. As we all know, the December 11th is the special day where the Bethlehem-powershell star outshined all the others. 

 

 

 

The scripts here is mostly for administrative purposes. They are of course provided “as-is” so feel free to expand/optimize/ include more error handling etc.

Create Management Pack

UPDATE: Script now works with different windows localization. Default language will now be set according to the console language user preference and not the windows locale

Unfortunately we are not as lucky as the SCOM guys to get their “Create management pack” interface. What SCSM is lacking here is the ability to create internal names and a more readable version number to new Management Packs created via Console. So if you don’t want your management pack to have a file name like ManagementPack.b89e1e6f33ac4e3abf85bb3d2a4466a7.xml  you can either edit the xml code and rename the file, or just create the Management Pack via powershell. I hope to one day create a new console task with the SCOM GUI, but until then this script should do fine.

I have set some default parameters for name convention inspiration.

# //***************************************************************************
# // CREATE MANAGEMENT PACK
# // 
# // Purpose: Will create a new management pack with specified parameters
# //
# // Author:  Morten Meisler, Coretech A/S. https://blog.ctglobalservices.com/mme  
# //***************************************************************************      

Param (
        [string]$InternalName = "CompanyPrefix.Incident.ListCustomizations", 
        [string]$DisplayName = "CompanyPrefix - Incident - ListCustomizations",
        [string]$Description = "This Management Pack contains list values for various Incident enumeration lists", 
        $Version = "1.0.0.0", 
        [string]$Server =       "localhost"
       
         ) 

$ErrorActionPreference = "Stop"
$smdefaultcomputer = $Server

$Error.Clear();
function Get-ConsoleLanguage
{
    $SMReg = "hkcu:/software/microsoft/System Center/2010/Service Manager/Console/User Settings"

    if (Test-Path $SMReg)
    {
        $ConsoleLang = (get-itemproperty  $SMReg).Language

        if ($ConsoleLang)
        {
            $culture = New-Object system.globalization.cultureinfo($ConsoleLang)
        }
        
    }
    if ($culture)
    {
        return $culture.ThreeLetterWindowsLanguageName
    }
}
#Message function
function ShowMessage ([string]$message, [System.ConsoleColor]$messageColor = "Red")
{
    Write-Host $message -ForegroundColor $messageColor
    
    if (!$psISE) #within ps console
    {
        Write-Host "`n`nPress any key to exit..."
        $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 
    }
    
}
#Load module
if (!(Get-Module smlets)) {Import-Module smlets -Force }

#Check if Management Pack exists already
$MP = Get-SCSMManagementPack -Name "$InternalName$"

#Create Management Pack if it does not exist
if (!$MP)
{
    Write-Host "Creating Management Pack: $InternalName on $smdefaultcomputer..."
    Try 
    {
       New-SCSMManagementPack -ManagementPackName $InternalName -FriendlyName $DisplayName -DisplayName $DisplayName -Version $Version -Verify
       Write-Host "Management Pack created. Setting description..."
    }catch {Throw "Management Pack $($MP.Name) could not be created. Error: $($error[0]) at line $($error[0].Exception.Line)"}
    
} else 
{
    Throw "Management Pack $($MP.Name) already exists, delete it and retry"
    
}


#Set Description for new Management Pack
Start-sleep -Milliseconds 500 
$MP = Get-SCSMManagementPack -Name "$InternalName$"
if ($MP)
{
    #Change defaultlanguage to scsm console language if they differ
    $UserConsoleLanguage = Get-ConsoleLanguage
    if ($UserConsoleLanguage -and $MP.DefaultLanguageCode -ne $UserConsoleLanguage)
    {
        $MP.DefaultLanguageCode = $UserConsoleLanguage
        $MP.AcceptChanges()
    }

        $MP.Description = $Description
    Try 
    {
        $MP.AcceptChanges()
    }catch {Throw "Management Pack $($MP.Name) created, but description could not be set. Error: $($error[0])"}
    

}else {Throw "Something went wrong. Management Pack not created. $($error[0])"}

ShowMessage -message "`n`nManagement Pack $InternalName successfully created!" -messageColor Green


Export Management Packs to folders

This script will export management packs into folders with default format: targetfolder\Management pack displayname\version number. E.g. C:\SCSM\Coretech – Incident – ListCustomizations\1.0.0.0\

Set parameters like StartsWith to only export your own management starting with “xxx” in the displayname (like your company prefix).

# //***************************************************************************
# // EXPORT MANAGEMENT PACKS TO FOLDERS
# // 
# // Purpose: Will export management packs to folders according to their name and version.
# //          If a new version is created a new version folder will be created 
# //          in the folder below the old version.
# //
# // Author:  Morten Meisler, Coretech A/S. https://blog.ctglobalservices.com/mme  
# //***************************************************************************          

Param (
        [string]$TargetFolder = "C:\SCSM\", 
        [string]$StartsWith =   "", #E.g. write your custom mps prefix name
        [string]$Server =       "localhost", 
        [bool]$IncludeSealed =  $false, 
        [ValidateSet('DisplayName','Name')]
        [string]$NameType = "DisplayName" #Folder name to export to, default is the mp displayname
       
         ) 

#Specify date format and rootfolder format
$CurrentDate = "{0:dd-MM-yyyy HH.mm}" -f (get-date)
$FolderName = "Management Packs $CurrentDate" 

$smdefaultcomputer = $Server
$ErrorActionPreference = "Stop"

#Load Module
if (!(Get-Module smlets)) {Import-Module smlets -force }


#Make root folder. Create if it doesn't exists
$folder = new-item -Name $FolderName -ItemType directory -Path $TargetFolder -Force 


if (Test-Path $folder)
{
    #Get Management Packs
    if ($IncludeSealed)
    {
        $MPs = Get-SCSMManagementPack | ?{$_.Displayname -like "$StartsWith*"}
    }else
    {
        $MPs = Get-SCSMManagementPack | ?{$_.Displayname -like "$StartsWith*" -and $_.Sealed -eq $false}
    }
    
    $i = 0
    Foreach ($MP in $MPs)
    {
        $i++
        #Make subfolders
        $MPFolder = New-Item -Path $folder -ItemType directory -Name $MP.$NameType -Force
        $MPverFolder = New-Item -Path $MPFolder -ItemType directory -Name $MP.version -Force

        #Export Management Pack to subfolder
        $MP | Export-SCSMManagementPack -TargetDirectory $MPverFolder
        if ($MP.DisplayName)
        {
            Write-Progress -Activity "Exporting MPs..." -Status $MP.DisplayName -PercentComplete (($i / $MPs.count)  * 100)
        }
    }

    $TargetFolder = $TargetFolder.TrimEnd("\")
    Write-host "`nManagement Packs saved to $TargetFolder\$FolderName" -ForegroundColor Green
}

Output:

image image

Clone subscriptions

You can create copy of templates, but not subscriptions. Fortunately this can be done via powershell. This can be useful if you have the exact same type of subscription, but just need to change the recipients for example. The script is very basic, it’s just to give an idea how it can be done, feel free to expand. Notice that this will only work for “Updated” and “Created” subscriptions. You will need some modifcations to make it work for other types, e.g. relationship-subscriptions or periodic subscriptions.

# //***************************************************************************      
# // CLONE SUBSCRIPTIONS
# // OBS! work for Created and Updated subscriptions. Not for period or custom made via xml         
# //***************************************************************************

#Displayname of subscription to copy
$SubscriptionName = "Company - Incident - Send confirmation mail to Affected User"

#Load SMlets module
if (!(Get-Module smlets)) {Import-Module smlets -force -ErrorAction stop}

#get subscription
$subs = Get-SCSMSubscription -DisplayName $SubscriptionName

#copy subscription (without description)
New-SCSMSubscription -Class $subs.TargetClass -Condition $subs.Condition -Criteria $subs.SubscriptionCriteria -ManagementPack $subs.ManagementPack -DisplayName "$($subs.DisplayName) Copy" -Recipient $subs.RecipientUsers -Enable $subs.Enabled -Template $subs.Template

I hope to dig up some more from my collection in the future, until then: HAPPY X-mAZ!