Using Azure DevOps PipeLines to build SCOM management packs

19 Apr

The challenge

 

A short post on a topic that I already wanted to blog about the past 6 years…. For almost 6 year I am using build pipelines to build and release/test the management packs I develop at OpsLogix. I wanted to share a bit of experience on how you can use Azure Devops to help you building a SCOM management pack.

 

The Investigation

 

The goal is to automatically build our management pack and after the build we want it to be tested on a real SCOM environment. For this we need the components below:

  • Azure DevOps

    This is quite straightforward , just active a devops subscription and you will have all tools available. See: https://azure.microsoft.com/en-us/pricing/details/devops/azure-devops-services/

  • Build pipeline

    This part is used to execute the flow of script in a sequence order. When I started using the build pipeline it was all setup in a UI way but the past 2 years you will have to use YAML for this.

  • VSAE installation

    Since we need to have the msbuild package to merge / parse and build the management pack we need to install the VSAE software. This part was the most difficult one because just simple installing the VSAE msi package wasn’t the solution (that time).

  • Release Pipeline

    After we have build the management pack we want to test it. So what would be better to install the MP on a real SCOM environment and run test scenarios. To be Azure credits cost efficient we used a on premise build agent that would create or reuse a SCOM server to install the management pack. After it installed it would run a PowerShell script that tests any monitor by feeding the SCOM workflow with the correct value to trigger.

  • Automated Labs

    Oho I love this project! Using this PowerShell module you can instantly create any lab you want. From exchange to IIS / AD or even a fresh SCOM environment. See: https://github.com/AutomatedLab/AutomatedLab

  • On premise agent

    As mentioned above. This is only for cost efficiency . You can also do it using a Azure virtual machine. Even automated Labs lets you simple switch between Cloud or on premise based deploys.

 

The solution

 

Below I will summarise the global steps I did, to keep it simple I will not go into every step and assume you have most of the knowledge already:

Azure DevOps ————————————————————————-

 

After you have activated the Azure DevOps account you create a new project. Next you create a Git Repro. This repo is used to store your management pack code.

 

 

Now that you have created the DevOps project and Repo we get the Repo URL that we will use later. Go to the Repos page and press at the right top ‘Clone Repository’ and copy the URL

 

Next is to add the MP code to the Repo. I assume you already have locally installed Visual Studio 2019 with the VSAE extensions and already have a working management pack solution in place. So now we have to add the MP source code to the DevOps repo we created above. If you are using Visual Studio 2019 you can easily connect it to the git repo by the steps below:

Add the Azure DevOps environment by pasting the DevOps Repo URL and applying the credentials. Now you will see your code connected to the repo as below:

 

The last step what we now have to do is commit and push the local code into the remote DevOps Repo.

Simply go to the ‘Team Explorer’ and select ‘changes’ and select ‘Commit all an Sync’. After this all you local code will be on the remote devops repo.

 

 

Build pipeline ————————————————————————-

 

Now we have all our code in the remote repo next step is to make a build pipeline. Simply go in DevOps Portal to the ‘Pipelines’ and press ‘New pipeline’

On the ‘Where is your code’ page you select ‘Azure Repos Git’ and on the ‘Select a repository’ page you select the Repo you created above. On the ‘Configure your pipeline’ page you select ‘Starter Pipeline’

After you have hit ‘Save’ your pipeline will be ready … just joking of course now the journey just starts….

Below I will focus on the steps you will have to do to get the MP code compiled to a Management Pack:

  1. Since we have to build using a Windows environment we have to change the pool vmImage to ‘windows-2019’
  2. We have to add a PowerShell step that copy’s the VSAE software to the correct place on the windows build image
  3. We have to change the msbuild step with some extra parameters

Step 1:

Change line

pool:

  vmImage: ubuntu-latest

 

to

pool:

  vmImage: Windows-2019

 

Step 2:

We have to add the VSAE bits. We can do this several ways. You can make an NUGET package or make a separate project or just add the files to the solution repo. I currently use a NUGET package that I have built. But for this blog I will use the local repo copy method. All steps have to be done on the server where you have VS 2019 and the VSAE software installed. (Visual Studio 2022 will also work but needs some target directory changes)

  • To start create a new folder called ‘SysCtr-VSAE’ in your repo root directory. Just go using file explorer to the root of the project repo and create the directory.
  • Next we need to copy the directory’s below into the new VSAE folder. So including all files and sub directories.

    C:\Program Files (x86)\System Center Visual Studio Authoring Extensions\

    C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VSAC

    C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Xml\Schemas\SystemCenter

     

    The total package would for example look like this:

Step 3:

So after we have copied the VSAE files to the repo directory we can continue to add some file copy steps below. Of course you can do this in one PowerShell step but I used the file copy task for clearness.

See below for the build pipeline so far:

# Starter pipeline

# Start with a minimal pipeline that you can customize to build and deploy your code.

# Add steps that build, run tests, deploy, and more:

# https://aka.ms/yaml

 

trigger:

– develop

 

pool:

  vmImage: windows-2019

 

steps:

 

– task: CopyFiles@2

  name: ”

  displayName: Copy Tools VSAE Files

  inputs:

     SourceFolder: $(Build.Repository.LocalPath)/SysCtr-VSAE/System Center Visual Studio Authoring Extensions

     TargetFolder: C:\Program Files (x86)\System Center Visual Studio Authoring Extensions

     OverWrite: true

– task: CopyFiles@2

  name: ”

  displayName: Copy MSbuild VSAE Files

  inputs:

    SourceFolder: $(Build.Repository.LocalPath)/SysCtr-VSAE/MSBuild

    TargetFolder: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft

    OverWrite: true

– task: CopyFiles@2

  name: ”

  displayName: Copy XML Schema VSAE Files

  inputs:

    SourceFolder: $(Build.Repository.LocalPath)/SysCtr-VSAE/Schemas

    TargetFolder: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Xml\Schemas

    OverWrite: true

 

Now we have all VSAE files in place. And we continue to add the build task. For this step we need to add some arguments first that will point to the correct VSAE files

 msbuildArgs: /IgnoreProjectExtensions:aiproj /p:VsaeMSBuildTargets=”$(Build.Repository.LocalPath)\SysCtr-VSAE\System Center Visual Studio Authoring Extensions\MSBuild\VSAC” /p:FragmentSchemaDir=”$(Build.Repository.LocalPath)\SysCtr-VSAE\Schemas\SystemCenter\\” /p:MpFrameworkPath=”$(Build.Repository.LocalPath)\SysCtr-VSAE\System Center Visual Studio Authoring Extensions\References\OM2012SP1″ /p:VSACInstallDir=”$(Build.Repository.LocalPath)\SysCtr-VSAE\System Center Visual Studio Authoring Extensions\\”

 

Total pipeline will now look like this:

 

# Starter pipeline

# Start with a minimal pipeline that you can customize to build and deploy your code.

# Add steps that build, run tests, deploy, and more:

# https://aka.ms/yaml

 

trigger:

– master

 

pool:

  vmImage: windows-2019

 

steps:

 

– task: CopyFiles@2

  name: ”

  displayName: Copy Tools VSAE Files

  inputs:

     SourceFolder: $(Build.Repository.LocalPath)/SysCtr-VSAE/System Center Visual Studio Authoring Extensions

     TargetFolder: C:\Program Files (x86)\System Center Visual Studio Authoring Extensions

     OverWrite: true

– task: CopyFiles@2

  name: ”

  displayName: Copy MSbuild VSAE Files

  inputs:

    SourceFolder: $(Build.Repository.LocalPath)/SysCtr-VSAE/MSBuild

    TargetFolder: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft

    OverWrite: true

– task: CopyFiles@2

  name: ”

  displayName: Copy XML Schema VSAE Files

  inputs:

    SourceFolder: $(Build.Repository.LocalPath)/SysCtr-VSAE/Schemas

    TargetFolder: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Xml\Schemas

    OverWrite: true

– task: VSBuild@1

  name: ”

  displayName: Build solution

  inputs:

    solution: ‘**\*.sln’

    vsVersion: ‘16.0‘

    msbuildArgs: /IgnoreProjectExtensions:aiproj /p:VsaeMSBuildTargets=”$(Build.Repository.LocalPath)\SysCtr-VSAE\System Center Visual Studio Authoring Extensions\MSBuild\VSAC” /p:FragmentSchemaDir=”$(Build.Repository.LocalPath)\SysCtr-VSAE\Schemas\SystemCenter\\” /p:MpFrameworkPath=”$(Build.Repository.LocalPath)\SysCtr-VSAE\System Center Visual Studio Authoring Extensions\References\OM2016″ /p:VSACInstallDir=”$(Build.Repository.LocalPath)\SysCtr-VSAE\System Center Visual Studio Authoring Extensions\\”

    platform: Any CPU

    configuration: ‘Release’

 

 

At this point we are ready to run the build pipeline. Don’t forget to commit and push the repo changes else the build will fail due to missing VSAE files.

 

The End

 

I hope this gave some hint and insight on how to automate the build of your SCOM management pack. Of course I left out a lot for other steps as building the binary probe modules or applying versioning to the management packs / binary probes etc…

Also the automated testing I will continue to put in a new blog to keep this one short.

 

Happy SCOMOPS’ing

 

Michel Kamp

Upload complete directory with files recursively to Teams/Sharepoint

20 Apr

Challenge

 

Currently I am working on an automated documentation generation project. I use DocFX to generate the documentation and after this I upload it to a Microsoft Teams channel document library. After this the generated documentation is visible for the end users as html pages.

One of the steps was uploading the generated files to the Teams SharePoint document library. Of course using the PnP.Powershell module is the best solution for this. But the documentation is what unclear on how to copy files recursively. So I did what try-outs and it ended up quite simple to do. So I let you save some time ……

Solution

 

Install-Module
PnP.Powershell

Import-Module
PnP.Powershell

 

# —– Connect to PnP Online

 

# Of course you will need to use a keystore or keyvault to handle the user and password.

# For example use Microsoft secretmanagement: https://devblogs.microsoft.com/powershell/secretmanagement-and-secretstore-are-generally-available/

$siteURL=“https://OrganizationHere.sharepoint.com/sites/DocumentationTeam”

Connect-PnPOnline
-Url
$SiteURL
-Credentials (Get-Credential
-Message
“login”
-UserName
uploaduser@OrganizationHere.onmicrosoft.com)

 

# —- Copy the directory and files

 

# The root directory of the files to upload

$source_path
=
“C:\Data\DocFx\_site\”

 

# The destination document library path

$destionation_path
=“Shared Documents/Documentation”

 

# get all files with full path as string array so the will be sorted automatically

$files_to_upload
=
Get-ChildItem
-Recurse
-Path
$source_path
-File
-Name

 

# upload each file.

# No need to create a directory folder first with Add-PnPFolder and adding recursively code the PnP-File will handle this too !

foreach ($file
in
$files_to_upload )

{


# get path name


$parent_dir
=
Split-Path
$file


# get file name


$dest_file
=
Split-Path
$file
-Leaf


# upload the file


Add-PnPFile
-Path
“$source_path\$file“
-NewFileName $dest_file

-Folder “$destionation_path/$parent_dir“

}

# done

 

 

Happy Teaming!

Michel Kamp

 

 

 

A better place to handle your KQL queries.

5 Aug

This time a short post on creating Kusto KQL queries.

If you are into Azure monitoring you probably have used the log query editor webpage a lot in the azure portal. And you noticed that sometimes its hard to edit the query and that is could be slow or even crash….

Also one of the main disadvantage is that you can’t attach a Git repo to it. So you end up in copy and pasting the final query into a Git connected repro..

To solve this I use the Kusto.Explorer.

You have 2 flavours of this tool: A web and a native version. (https://docs.microsoft.com/en-us/azure/data-explorer/kusto/tools/kusto-explorer)

I this example I use the native version (since I want to use a Git repro and want to avoid web apps) , you can download it here : Kusto.Explorer tool

After installing the tool and starting it you will have to add a connection. As below:

Step 1 and 2 i am not going to explain

At step 3 you enter the connection string. How do we get this connection string ?

  • Be sure you are logged on to the azure portal using the correct tenant.
  • Construct the connection string as : https://ade.loganalytics.io/subscriptions/<subscription GUID>/resourcegroups/<resource group name>/providers/microsoft.operationalinsights/workspaces/<workspace name>

    Use the Azure portal to lookup the to be replaced values.

For example it looks like: https://ade.loganalytics.io/subscriptions/b63b6221-4a46-4fc1-c192-a8f6549d6d11/resourcegroups/kustotest/providers/microsoft.operationalinsights/workspaces/LogAnalyticsTest

  • Tip: use a Alias to provide some meaning full name to this connection like Production or Test

At step 4 we set it to use AAD credentials. Important is that the account that you are using at your workstation is joined to an local AD that is synced with the AAD in azure. (aka Federated)

At step 5 you will be able to press Ok to connect to the Log analytics workspace.

If the connection was successful you will see under the alias you used the log tables. See picture below:

 

And at this step you are ready to open a new work book and edit your query

And you can even do graphs

 

Connection troubleshooting

If you are having issues connecting to the log analytics workspace it could be that your AAD account is not part of the tenant were the workspace is placed.

So for example you have a AAD account in tenant A and the workspace is in tenant B . You check the access and it looks fine since you have the correct permissions setup to access tenant B by opening the workspace in the azure portal of tenant B.

In this case you will have to add a special tag “Authority Id” to the connection string as below and provide the tenant ADD guid:

Authority Id=<tenant AAD guid>

Use the advanced option to specify it.

 

Happy KQL’ing !!

Michel Kamp

 

Failed VSAE build with message: Could not load management pack System.AdminItem.Library

4 Nov

Again a new addition to the VSAE build errors KB.

Problem

You compile a VSAE project and you get the compile error below:

Severity    Code    Description    Project    File    Line    Suppression State

Error        Verification of Monitor Configuration with MonitorType schema for Monitor OpsLogix.IMP.VMWare.VirtualMachine.Monitoring.Monitor.VM.CPUUsage failed.

: Could not load management pack [ID=System.AdminItem.Library, KeyToken=31bf3856ad364e35, Version=7.5.8500.0]. The management pack was not found in the store.

An object of class ManagementPack with name System.AdminItem.Library was not found. (Path = OpsLogix.IMP.VMWare.VirtualMachine.Monitoring.Monitor.VM.CPUUsage)    OpsLogix.IMP.VMWare.VirtualMachine.Monitoring    Monitoring\Monitors\OpsLogix.IMP.VMWare.VirtualMachine.Monitoring.Monitor.VM.CPUUsage.mpx    4    

 

Investigation

 

Hue ? Could not load management pack System.AdminItem.Library ?

But I don’t use this one at all. So you could add this MP to the references and end up with a new error saying :

Verification of Monitor Configuration with MonitorType schema for Monitor OpsLogix.IMP.VMWare.VirtualMachine.Monitoring.Monitor.VM.CPUUsage failed.: Could not load management pack [ID=System.Software.Library, KeyToken=31bf3856ad364e35, Version=7.5.8501.0]. The management pack was not found in the store.An object of class ManagementPack with name System.Software.Library was not found. (Path = OpsLogix.IMP.VMWare.VirtualMachine.Monitoring.Monitor.VM.CPUUsage)

 

Again we add the missing MP : System.Software.Library

And now we get

Verification of Monitor Configuration with MonitorType schema for Monitor OpsLogix.IMP.VMWare.VirtualMachine.Monitoring.Monitor.VM.CPUUsage failed.

: Could not load management pack [ID=Microsoft.SystemCenter.NTService.Library, KeyToken=31bf3856ad364e35, Version=7.0.9538.0]. The management pack was not found in the store.

An object of class ManagementPack with name Microsoft.SystemCenter.NTService.Library was not found. (Path = OpsLogix.IMP.VMWare.VirtualMachine.Monitoring.Monitor.VM.CPUUsage)    OpsLogix.IMP.VMWare.VirtualMachine.Monitoring    Monitoring\Monitors\OpsLogix.IMP.VMWare.VirtualMachine.Monitoring.Monitor.VM.CPUUsage.mpx

 

So again we could add the MP ref but I can tell you now already that this won’t help at all. The compiler is just trying to search through known types to see if it can map a property.

Just jump to the solution because it very simple….

Solution

 

Just double check if the class properties you refer are correctly spelled (case sensitive!) . In this case the names were not correct.

Also it could be that it couldn’t find the property at all. Same error is displayed.

 

Hope this helps.

Happy Scomming

Michel Kamp

Computer property Organizational Unit is Empty

30 Oct

 

The problem:

 

For a show case I had to make a group based on the computer OU. I ‘m using SCOM 2016 and had installed only the basic out of the box MPs.

I noticed that the Organizational Unit property was empty. Hmm why ? do I miss a MP doing this ??


 

The investigation:

 

So first I searched for a discovery filling this property. It is internal id is named : Microsoft.SystemCenter.DiscoverWindowsComputerProperties

See here : https://systemcenter.wiki/?GetElement=Microsoft.SystemCenter.DiscoverWindowsComputerProperties&Type=Discovery&ManagementPack=Microsoft.SystemCenter.Internal&Version=7.0.8443.6

Next I had a look at the datasource and took out the PS script part.

See here : https://systemcenter.wiki/?GetElement=Microsoft.SystemCenter.WindowsComputerPropertyDiscovery&Type=DataSourceModuleType&ManagementPack=Microsoft.SystemCenter.Internal&Version=7.0.8443.6

I opened a ISE on that server and copied the script into the editor.

Changed the initial params as :

#param($SourceType, $SourceId, $ManagedEntityId, $ComputerIdentity)

 

$SourceType=0

$SourceId=
[guid]::newguid()

$ManagedEntityId
=
[guid]::newguid()

$ComputerIdentity=“SCOMADMIN11.contoso.com”

 

And executed the script. And I got a error indicating that the $computer was empty. Searched and i noticed that the $ADSISearcher.Filter  is incorrect so the computer object isn’t populated from LDAP.

 

it is  

$ADSISearcher.Filter = ‘(&amp;(DNSHostName=’ + $strDNSComputerName + ‘)(Name=’ + $strNetBIOSComputerName + ‘)(objectClass=computer))’;

but should be 

$ADSISearcher.Filter = ‘(&(DNSHostName=’ + $strDNSComputerName + ‘)(Name=’ + $strNetBIOSComputerName + ‘)(objectClass=computer))’;
    

So it’s a bug 😉

Solution:

 

Till the responsible Microsoft team isn’t going to fix this you will have to make you own discovery workflow to fill this property.

Hope this helps

Happy SCOMMING.

VSAE malicious compiling challenges

25 Oct
Below a memory dump for myself.

The challenge

During compiling your management Pack in VSAE you get this nice blurry error message:
Detected malicious verification code when verifying element of type Microsoft.EnterpriseManagement.Configuration.ManagementPackRule with inner exception: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at Microsoft.EnterpriseManagement.Configuration.ManagementPackRule.VerifyDataTypes(Dictionary`2 moduletypes) at Microsoft.EnterpriseManagement.Configuration.ManagementPackRule.Verify(VerificationContext context) at Microsoft.EnterpriseManagement.Configuration.Verification.VerificationEngine.VerifyCollectionItems(Object context) (Path = OpsLogix.IMP.VMWare.VirtualMachine.Monitoring)

The Investigation

Out of my almost 13 years for MP authoring experience I know most of the time this error above is due to a missing end tag $ of a property reference or a misspelled property name. For example
<License>$Target/Property[Type="OpsLogix.IMP.VMWare.VirtualMachine"]/LicenseKey</License>
Should be
<License>$Target/Property[Type="OpsLogix.IMP.VMWare.VirtualMachine"]/LicenseKey$</License>
But this time it’s different … after doing some investigations by setting the management fragments “Build Action” to “None” in the VSAE project I found out that it was due to the external referenced datatasource Accessibility property.

The solution

So after I changed the Accessibility property of the external referenced datasource from :
<DataSourceModuleType
ID="OpsLogix.IMP.VMware.Collector.DataSource.LicenseActions"
Accessibility="Internal"
Batching="false">
 To..
<DataSourceModuleType
ID="OpsLogix.IMP.VMware.Collector.DataSource.LicenseActions"
Accessibility="Public"
Batching="false">
… my project compiled fine. What makes of course sense and if I was using the autocomplete in VSAE this was never happened since the autocomplete will not provide you any Internal references at all…. But of course to be faster I copied it over manually , so my bad … at the end I lost my time due to investigations anyway hope you won’t.

The end

Hope I saved you some time. Happy scomming

Debugging SCOM Workflows using PowerShell

22 Oct

Hi,

As promised during one of the SCOM MP authoring trainings I gave, here’s a short post about how to debug your SCOM Management Pack workflows. ( So Patrick you can stop spamming me (lol) )

Currently we have 5 options for debugging your workflows:

  1. Eventlog
  2. WFAnalyzer
  3. Trace by PowerShell
  4. TraceConfig ETW Tracer
  5. Microsoft Message Analyzer ** will make a separate post this this soon **

Some short explanations:

1.Eventlog

Trace by looking at healthservice events or log messages that you have put into your PS/VBS probes. However this doesn’t provide any information on if a condition connection fails or the PB passed ect.

Look the Operationsmanager eventlog for the following event ids , note there are a lot more id but this ones will give you a first detection:

ID Description
1103 Summary: xxxx rule(s)/monitor(s) failed and got unloaded, 1 of them reached the failure limit that prevents automatic reload. Management group “xxx”. This is summary only event, please see other events with descriptions of unloaded rule(s)/monitor(s).
1102 Rule/Monitor “%4” running for instance “%3″ with id:”%2” cannot be initialized and will not be loaded. Management group “%1”    
1101 Host reference in workflow “%4”, running for instance “%3″ with id:”%2” cannot be resolved. Workflow will not be loaded. Management group “%1”   
1206 Rule/Monitor “%2”, running for instance “%3″ with id:”%4” failed, got unloaded and reached the failure limit that prevents automatic reload. Management group “%1”.  
4510 The Health Service encountered an error %5 causing the rule “%2” running for instance “%3″ with id:”%4” in management group “%1”.   
5412 Converting data batch to XML failed with error “%6” (%5) in rule “%2” running for instance “%3″ with id:”%4” in management group “%1”.%n  %n  The rule will be unloaded.    
5401 Failed to replace parameter while creating the alert for monitor state change.

2.WFAnalyzer

This is a tool provided by Microsoft. You will have to copy it from the VSAE installation media to the scom server installation directory since it needs some extra dlls. See for VSAE here: https://www.microsoft.com/en-us/download/details.aspx?id=30169

When you start the program you will be asked to apply a MS server and the Agent to trace. After this you will see a running workflows table. Pick one workflow you want to trace and right click -> Trace. Now a new trace window will be started with the formatted output of the trace.

I must say that using this tool is a must have for SCOM MP authors…. If it works … since SCOM 2012 R2 and above most of the time it fails to start a trace.

If it crashes you could try to do this:

  1. Open as administrator a CMD
  2. Execute : “C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\StopTracing.cmd”
  3. Execute: “C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\StartTracing.cmd”
  4. Execute : “C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\StopTracing.cmd”
  5. Execute: “C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\FormatTracing.cmd”

This will build new CAB/tmf files in the Tools (all.tmf) and Tools\TMF directory that is used to translate the ETW ids to readable messages.

And with a bit of luck it works. If it works, also have a look at the filter menu. Changing it to None will give you some more details if a WF fails.

Also keep in mind that this tool needs a SDK connection to execute the ‘get running workflows’ task and also to get WF/instance information from that task results. This information is used to provide you the UI table so you can select the WF to trace. So can I use it on a normal agent ? yes you can but as stated it needs a SDK connection to a MS server. Why ? When you start the WFanalyzer it will show you a box were you provide the SDK MS server and the Agent to debug. With this information it will trigger the task ‘get running workflows’ on that agent. The results are used to build a WF table. But again this is only for providing you the nice UI. Also I have rewritten the WFanalyzer UI a long time ago to fix this bugs and requirements as far I remember it was due to an invalid GUID that lets the UI table component crash when it updates the WF running states and also I changed the SDK connection mechanism to make it run on a agent. But due to MSFT copyright I can’t share it with you , sorry. (If someone from the MSFT SCOM team (Kevin ? ) reads this I am happy to share the issues I have fixed.)

But no worry , in the part below I explain how to do this using PowerShell so you don’t have this issues.

3.Trace by PowerShell

So If you can’t run the WFanalyzer as above. You could use the PowerShell scripts below.

What it will do:

  • Get the Workflow and Instance Id to trace
  • Create the TraceEnbled override and import the override MP
  • Start up a trace listener
  • Format real time the ETW messages to readable content and filter out some irrelevant strings
  • Stop the trace
  • Remove the override MP

If you run step 1,2 on a MS server to get the IDs you could use it to start the trace on a GW or Agent too.

Step 5 and 6 you should only run if you are done with tracing.

I have separate scripts for Rule , Monitor and Discovery WF tracing. See below:

Rule tracing

import-module operationsmanager

## monitor and target to debug
$targetName=”Target1″
$ruleName=”OpsLogix.IMP.Rule.Ping.WMIPingCheck”

## create override
$rule=Get-SCOMRule-name $ruleName
$ruleClass=get-scomclass -id $($rule.Target).Id
$ruleTarget=Get-SCOMMonitoringObject -Class
$ruleClass | ?{$_.Name -like $targetName}

$ruleoverride=”<Overrides> <RulePropertyOverride ID=””DebugOverrideForRule$($rule.Name)”” Context=””$($ruleClass.Id)”” ContextInstance=””$($ruleTarget.Id)”” Enforced=””false”” Rule=””$($rule.Id)”” Property=””TraceEnabled””> <Value>true</Value> </RulePropertyOverride> </Overrides>”
$RuleMP=$rule.GetManagementPack()
$RuleMP.KeyToken

$mp=@”
<?xml version=”1.0″ encoding=”utf-8″?>
<ManagementPack ContentReadable=”true” SchemaVersion=”2.0″ OriginalSchemaVersion=”1.1″ xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”&gt;
<Manifest>
<Identity>
<ID>WorkflowTraceOverrideMP</ID>
<Version>1.0.0.0</Version>
</Identity>
<Name>WorkflowTraceOverrideMP</Name>
<References>
<Reference Alias=”$($RuleMP.Name)”>
<ID>$($RuleMP.Name)</ID>
<Version>$($RuleMP.Version)</Version>
<PublicKeyToken>$($RuleMP.KeyToken)</PublicKeyToken>
</Reference>
</References>
</Manifest>
<Monitoring>
<Overrides>
<RulePropertyOverride ID=”DebugOverrideForRule$($rule.Name)” Context=”$($RuleMP.Name)!$($ruleClass.Name)” ContextInstance=”$($ruleTarget.Id)” Enforced=”false” Rule=”$($RuleMP.Name)!$($rule.Name)” Property=”TraceEnabled”>
<Value>true</Value>
</RulePropertyOverride>
</Overrides>
</Monitoring>
<LanguagePacks>
<LanguagePack ID=”ENU” IsDefault=”false”>
<DisplayStrings>
<DisplayString ElementID=”DebugOverrideForRule$($rule.Name)”>
<Name>Workflow Trace Override used by the WorkflowDebugger</Name>
</DisplayString>
</DisplayStrings>
</LanguagePack>
</LanguagePacks>
</ManagementPack>
“@

$mpfile=”c:\temp\WorkflowTraceOverrideMP.xml”

$mp | Out-File -Encoding ascii $mpfile

Import-SCOMManagementPack $mpfile

# start trace

&”C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\TraceLogSM.exe” -start “CustomWorkflowTrace” -flag 0xFF -level 5 -ft 1 -rt -guid “#c85ab4ed-7f0f-42c7-8421-995da9810fdd” -b 1024

&”C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\tracefmtsm.exe” -rt “CustomWorkflowTrace” -display -nosummary -o “C:\temp\WorkflowTrace.log” -tmf “C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\All.tmf” | select-string -Pattern “ModuleDebug” -NotMatch

# stop trace

&”C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\TraceLogSM.exe” -stop “CustomWorkflowTrace”

# remove MP

Get-SCOMManagementPack -name “WorkflowTraceOverrideMP” | Remove-SCOMManagementPack

Monitor tracing

import-module operationsmanager

## monitor and target to debug
$targetName=”Target1″
$monitorName=”OpsLogix.IMP.Monitor.Ping.WMIPingCheck”

## create override
$monitor=Get-SCOMMonitor -name $monitorName
$monitorClass=get-scomclass -id $($monitor.Target).Id
$monitorTarget=Get-SCOMMonitoringObject -Class
$monitorClass | ?{$_.Name -like $targetName}

$monitoroverride=”<Overrides> <MonitorPropertyOverride ID=””DebugOverrideForMonitor$($monitor.Name)”” Context=””$($monitorClass.Id)”” ContextInstance=””$($monitorTarget.Id)”” Enforced=””false”” Monitor=””$($monitor.Id)”” Property=””TraceEnabled””> <Value>true</Value> </MonitorPropertyOverride> </Overrides>”

$monitoMP=$monitor.GetManagementPack()
$monitoMP.KeyToken
$mp=@”
<?xml version=”1.0″ encoding=”utf-8″?>
<ManagementPack ContentReadable=”true” SchemaVersion=”2.0″ OriginalSchemaVersion=”1.1″ xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”&gt;
<Manifest>
<Identity>
<ID>WorkflowTraceOverrideMP</ID>
<Version>1.0.0.0</Version>
</Identity>
<Name>WorkflowTraceOverrideMP</Name>
<References>
<Reference Alias=”$($monitoMP.Name)”>
<ID>$($monitoMP.Name)</ID>
<Version>$($monitoMP.Version)</Version>
<PublicKeyToken>$($monitoMP.KeyToken)</PublicKeyToken>
</Reference>
</References>
</Manifest>
<Monitoring>
<Overrides>
<MonitorPropertyOverride ID=”DebugOverrideForMonitor$($monitor.Name)” Context=”$($monitoMP.Name)!$($monitorClass.Name)” ContextInstance=”$($monitorTarget.Id)” Enforced=”false” Monitor=”$($monitoMP.Name)!$($monitor.Name)” Property=”TraceEnabled”>
<Value>true</Value>
</MonitorPropertyOverride>
</Overrides>
</Monitoring>
<LanguagePacks>
<LanguagePack ID=”ENU” IsDefault=”false”>
<DisplayStrings>
<DisplayString ElementID=”DebugOverrideForMonitor$($monitor.Name)”>
<Name>Workflow Trace Override used by the WorkflowDebugger</Name>
</DisplayString>
</DisplayStrings>
</LanguagePack>
</LanguagePacks>
</ManagementPack>
“@

$mpfile=”c:\temp\WorkflowTraceOverrideMP.xml”

$mp | Out-File -Encoding ascii $mpfile

Import-SCOMManagementPack $mpfile

# start trace

&”C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\TraceLogSM.exe” -start “CustomWorkflowTrace” -flag 0xFF -level 5 -ft 1 -rt -guid “#c85ab4ed-7f0f-42c7-8421-995da9810fdd” -b 1024

&”C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\tracefmtsm.exe” -rt “CustomWorkflowTrace” -display -nosummary -o “C:\temp\WorkflowTrace.log” -tmf “C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\All.tmf” | select-string -Pattern “ModuleDebug” -NotMatch

# stop trace

&”C:\Program Files\Microsoft System Center 2016\Operations Manager\Server\Tools\TraceLogSM.exe” -stop “CustomWorkflowTrace”

# remove MP

Get-SCOMManagementPack -name “WorkflowTraceOverrideMP” | Remove-SCOMManagementPack

Discovery tracing

# debug SCOM WF
# if need to run on agent
# execute code below on MS server
# and execute code below “# execute on AGENT or MS server” on the agent server

# ————————————-
# execute on MS server
# ————————————-

import-module operationsmanager
## monitor and target to debug

$targetName=”Sharepoint Office Online Server”
$discoveryName=”Microsoft.SharePoint.OnlineOfficeServices.Discovery.OOS.Server.Properties”

## create override

$discovery=Get-SCOMDiscovery -name $discoveryName
$discoveryClass=get-scomclass -id $($discovery.Target).Id
$discoveryTarget=Get-SCOMMonitoringObject -Class $discoveryClass # | ?{$_.Name -like $targetName}
$discoveryMP=$discovery.GetManagementPack()
$mp= @”
<?xml version=”1.0″ encoding=”utf-8″?><ManagementPack ContentReadable=”true” SchemaVersion=”2.0″ OriginalSchemaVersion=”1.1″ xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”&gt;
<Manifest>
<Identity>
<ID>WorkflowTraceOverrideMP</ID>
<Version>1.0.0.0</Version>
</Identity>
<Name>WorkflowTraceOverrideMP</Name>
<References>
<Reference Alias=”$($discoveryMP.Name)”>
<ID>$($discoveryMP.Name)</ID>
<Version>$($discoveryMP.Version)</Version>
<PublicKeyToken>$($discoveryMP.KeyToken)</PublicKeyToken>
</Reference>
</References>
</Manifest>
<Monitoring>
<Overrides>
<DiscoveryPropertyOverride ID=”DebugOverrideForDiscovery$($discovery.Name)” Context=”$($discoveryMP.Name)!$($discoveryClass.Name)” ContextInstance=”$($discoveryTarget.Id)” Enforced=”false” Discovery=”$($discoveryMP.Name)!$($discovery.Name)” Property=”TraceEnabled”>
<Value>true</Value>
</DiscoveryPropertyOverride>
</Overrides>
</Monitoring>
<LanguagePacks>
<LanguagePack ID=”ENU” IsDefault=”false”>
<DisplayStrings>
<DisplayString ElementID=”DebugOverrideForDiscovery$($discovery.Name)”>
<Name>Workflow Trace Override used by the WorkflowDebugger</Name>
</DisplayString>
</DisplayStrings>
</LanguagePack>
</LanguagePacks>
</ManagementPack>
“@

md c:\temp -Force
$mpfile=”c:\temp\WorkflowTraceOverrideMP.xml”
$mp | Out-File -Encoding ascii $mpfile

Import-SCOMManagementPack $mpfile

# ————————————-
# execute on AGENT or MS server below
# ————————————-

# change path to agent ot MS installation
$AGENTTOOLPATH=”C:\Program Files\Microsoft Monitoring Agent\Agent\Tools”
#$AGENTTOOLPATH=”C:\Program Files\Microsoft System Center\Operations Manager\Server\Tools”

# start trace
md c:\temp -Force
&”$AGENTTOOLPATH\TraceLogSM.exe” -start “CustomWorkflowTrace” -flag 0xFF -level 6 -ft 1 -rt -guid “#c85ab4ed-7f0f-42c7-8421-995da9810fdd” -b 1024
&”$AGENTTOOLPATH\tracefmtsm.exe” -rt “CustomWorkflowTrace” -display -nosummary -o “C:\temp\WorkflowTrace.log” -tmf “$AGENTTOOLPATH\All.tmf” | select-string -Pattern “ModuleDebug” -NotMatch # | Select-Object Line | Out-StringNoWrap

# stop trace
&”$AGENTTOOLPATH\TraceLogSM.exe” -stop “CustomWorkflowTrace”

# remove MP
Get-SCOMManagementPack -name “WorkflowTraceOverrideMP” | Remove-SCOMManagementPack

4.TraceConfig ETW Tracer

So if nothing above did help you getting a clue why your workflows are not working you a doomed to use the ETW tracer and go through tons of log lines….

For example you used 3 state monitor moduletype but specified only 2 state in the monitor…

To trace what is happening follow the steps below:

  1. Start a OpsMgrtrace using C:\Program Files\ Microsoft System Center 2016\Operations Manager\Server\Tools\TraceConfig.exe
  2. Select all trace providers from Trace Area: Healthservice and Modules
  3. Set the trace level to DEBUG
  4. Start the tracing
  5. After restarting the SCOM agent wait till you get the 1102 error
  6. Now stop the Trace
  7. Format the trace file to a log file . Use as Admin CMD and execute C:\Program Files\ Microsoft System Center 2016\Operations Manager\Server\Tools\FormatTracing.cmd
  8. Open the log file at : C:\Windows\Logs\OpsMgrTrace\OpsMgrCustom.log (tip VsCode is excellent for this)
  9. Look for the workflow name or
  10. Look for text : [ConfigurationManager] [] [Error] :CMonitoringResolver

For example:

[1]11632.15896::09/28/2017-14:45:27.661 [ConfigurationManager] [] [Error] :CMonitoringResolver::LookupHealth{MEMonitoringResolver_cpp2945}Cannot resolve operational state. [1]11632.15896::09/28/2017-14:45:27.661 [Common] [] [Error] :Common::ParameterReplacement::ReplaceCommon{ParameterReplacement_cpp615}`hr` failed, returning ERROR: {hr= 0x8000ffff(E_UNEXPECTED)}[1]11632.15896::09/28/2017-14:45:27.661 [ConfigurationManager] [] [Error] :CMonitoringResolver::ResolveOperationalStates{MEMonitoringResolver_cpp1022}Common::ParameterReplacement::Replace failed with code 0x8000ffff(E_UNEXPECTED).

[1]11632.15896::09/28/2017-14:45:27.661 [ConfigurationManager] [] [Error] :CMonitoringResolver::ResolveOperationalStates{MEMonitoringResolver_cpp960}ResolveOperationalState failed with code -2147418113(E_UNEXPECTED).

[1]11632.15896::09/28/2017-14:45:27.661 [ConfigurationManager] [] [Error] :CMonitoringResolver::ResolveMonitorModules{MEMonitoringResolver_cpp425}ResolveOperationalStates failed with code -2147418113(E_UNEXPECTED).

[1]11632.15896::09/28/2017-14:45:27.661 [ConfigurationManager] [] [Error] :CWorkflowsLoader::LoadUnitMonitor{MEWorkflowsLoader_cpp2877}ResolveMonitorModules for ‘OpsLogix.IMP.Oracle.Backup.ARCHIVELOG.Monitor’ failed with code -2147418113(E_UNEXPECTED).

[1]11632.15896::09/28/2017-14:45:27.661 [ConfigurationManager] [] [Error] :CWorkflowsLoader::LoadUnitMonitor{MEWorkflowsLoader_cpp2877}ResolveMonitorModules for ‘OpsLogix.IMP.Oracle.Backup.ARCHIVELOG.Monitor’ failed with code -2147418113(E_UNEXPECTED).

[0]11632.15896::09/28/2017-14:45:15.632 [HealthServiceCommon] [] [Error] :EventLogUtil::LogEvent{EventLogUtil_cpp379}Logging event 1102 from source “HealthService” with severity Error and description “Rule/Monitor “OpsLogix.IMP.Oracle.Backup.ARCHIVELOG.Monitor” running for instance “Backup state for DB11G07″ with id:”{7F1A7474-5A4F-6856-32D7-7FAA6022EC73}” cannot be initialized and will not be loaded. Management group “OM2012SP1Grp01″”.

Solution found to fix this :

Check the <operationalStates> it should match the 2 or 3 states defined the monitormoduletype.

For example the error above missed the Warning state.

<OperationalStates>

<OperationalState ID=”UIGeneratedOpStateIda836de3b0d3645dca0ecdc3b6374c3e4″ MonitorTypeStateID=”Healthy” HealthState=”Success” />

<OperationalState ID=”UIGeneratedOpStateIdaaa73a3abd5144eaa6bff6d72e1d3aaa” MonitorTypeStateID=”Warning” HealthState=”Warning” />

<OperationalState ID=”UIGeneratedOpStateIdc415176391694409926e21afb666c532″ MonitorTypeStateID=”Critical” HealthState=”Error” />

</OperationalStates>

The End

So hope this helps you getting to know why a workflow is not running OR what data a workflow is passing in a PropertyBag.

When I have some time left (and that’s spare) I will finish my post on using Microsoft Message Analyzer for SCOM WF tracing.

Happy SCOMMING

SCOM console could not load Scheduled Reports Subscriptions

8 Aug

 

 

A quick note since I could not find it on the web.

 

Today I had a call with a customer. He had a issue with opening the Scheduled Reports view in the SCOM console.


 

He got the error below:

 


 

The error was as cryptic as we are used to known form MSFT :

 

System.NullReferenceException: Object reference not set to an instance of an object.

 

Note:  The following information was gathered when the operation was attempted.  The information may appear cryptic but provides context for the error.  The application will continue to run.

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.EnterpriseManagement.Mom.Internal.UI.Reporting.ManagementGroupReporting.GetSubscriptions(String owner)
   at Microsoft.EnterpriseManagement.Mom.Internal.UI.Reporting.Views.ReportSubscriptionsView.ReportSubscriptionsView.LoadSubscriptionsJob(Object sender, ConsoleJobEventArgs args)

 

So I looked at the subscriptions table in the reporting database where the subscriptions are stored:

SELECT
*
FROM [ReportServer].[dbo].[Subscriptions]

And all the 40 subscriptions where there.

So what could be the issue ?

After some digging it seems that the delivery option EMAIL was missing .


 

So by running the Reporting Services Configuration Manager and configure the email settings again it all started to work again

 

 

So happy SCOMMING again

 

Michel

 

 

Using PowerShell to add update and delete Class instances in SCOM

29 Nov

Challenge

This short post will provide some PowerShell scripting to let you play with class instances in SCOM. Since there’s not much information on the web on this topic and I had a request from a partner I will provide some code below how to handle this.

In the examples below I will use a class from the OpsLogix VMware management pack, but you can use any (public) class you want. All code just be run on a SCOM MS server. All examples are separate runnable.

Add a class instance

In the example below, I will add a new VMWare ESX host to a datacenter belonging to a vCenter connection. As below:

Before we run the script, we will have to know the Key properties so we can configure the parent child relationship. In this case the we have the following relationship:

vCenter01:7443 -> Datacenter01 -> My_ESX_Host

In this case the Host we want to add is called “My_ESX_Host” and we set the “AssetTag” to “unkown” .

## ======================================================================

## example script how to add a class instance in SCOM

## ======================================================================

## Michel Kamp

## ======================================================================

New-SCOMManagementGroupConnection
-ComputerName
“localhost”

$mg
=
Get-SCOMManagementGroup

$ClassInstanceDisplayName=
“My_ESX_Host”

$Class
=
Get-SCOMClass
-Name
OpsLogix.IMP.VMWare.ESXHost

##================= create/add class instance

$ClassObject
=
New-Object
Microsoft.EnterpriseManagement.Common.CreatableEnterpriseManagementObject($mg,$class)

# set the KEY props

$ClassObject[$Class.FindHostClass().FindHostClass(),“vCenterHostName”].Value = “vCenter01:7443”

$ClassObject[$Class.FindHostClass(),“DatacenterName”].Value = “Datacenter01”

$ClassObject[$Class,“ESXServerName”].Value =
$ClassInstanceDisplayName

# Set NON key props

$ClassObject[$Class,“AssetTag”].Value = “unkown”

# add and write back to scom

$discovery
=
New-Object
Microsoft.EnterpriseManagement.ConnectorFramework.IncrementalDiscoveryData

$discovery.Add($ClassObject)

$discovery.Overwrite($mg)

##================= END ================================================

Change a property of a class instance

Below we change a property called “AssetTag” to “test tag 123” of the ESXHost class instance “My_ESX_Host”. Keep in mind that only NON-Key properties can be changed.

See script below:

## ======================================================================

## example script how to change a class instance in SCOM

## ======================================================================

## Michel Kamp

## ======================================================================

New-SCOMManagementGroupConnection
-ComputerName
“localhost”

$mg
=
Get-SCOMManagementGroup

$ClassInstanceDisplayName=
“My_ESX_Host”

$Class
=
Get-SCOMClass
-Name
OpsLogix.IMP.VMWare.ESXHost

##================= change property of class instance

## get the just created class

$ClassInstance
=
Get-SCOMMonitoringObject
-Class
$Class
|
where { $_.DisplayName -eq $ClassInstanceDisplayName}

# change the properties

# only NON-KEY props can be changed

$ClassInstance[$Class,“AssetTag”].Value = “test tag 123”

# write it to scom

$ClassInstance.Overwrite()

##================= END ================================================

Delete a Class Instance

In this example we delete the ESXHost class instance “My_ESX_Host”.

## ======================================================================

## example script how to delete a class instance in SCOM

## ======================================================================

## Michel Kamp

## ======================================================================

New-SCOMManagementGroupConnection
-ComputerName
“localhost”

$mg
=
Get-SCOMManagementGroup

$ClassInstanceDisplayName=
“My_ESX_Host”

$Class
=
Get-SCOMClass
-Name
OpsLogix.IMP.VMWare.ESXHost

##============== remove a class instance

## get the class instance to remove

$ClassInstance
=
Get-SCOMMonitoringObject
-Class
$Class
|
where { $_.DisplayName -eq $ClassInstanceDisplayName}

# add the class instance to delete

$discovery
=
New-Object
Microsoft.EnterpriseManagement.ConnectorFramework.IncrementalDiscoveryData

$discovery.RemoveInternal($ClassInstance,$ClassInstance.GetClasses()[0])

## execute the delete

$discovery.Commit($mg)

##================= END ================================================

Happy SCOM’ing

Michel Kamp

TOUCHING SCOM

https://michelkamp.wordpress.com/

Calling HTTPS on self-hosted C# service using PowerShell gives 404 error

1 Aug

 

A short post on something that was making me bold. So maybe I save you some hears 😉

 

Problem (no challenge this time)

 

You have a Self Hosted C# webservice. This web service is configured to listen to base address https://host.domain.com:8733

  1. You have created a selfsigned certificate as example below:

New-SelfSignedCertificate -DnsName host.domain.com -NotAfter “2020/01/01” -FriendlyName “Test Cert” -CertStoreLocation Cert:\LocalMachine\My

  1. You added the certificate also to the Trusted Root Certification Authorities on the server. So the cert chain will be valid !

     

  2. You have configured the binding and listener for example as below: (certhash should be replaced by the hash from the cert above)

netsh http add urlacl url=https://*:8733/Config_Service user=EVERYONE delegate=yes

netsh http add sslcert ipport=0.0.0.0:8733 certhash=‎aaaaaaaaaaaaaaaaaaaaaa appid={3a1d638b-1b51-482a-dddd-218a589c2e69}

  1. Now on the host it selfs you call the webservice from out your browser as :

     

    https://host.domain.com:8733/Config_Service/ConfigService/api/list/configuration

     

    You will get a 404

     

  2. Now you go to external workstation and open a web browser and go to:

    https://host.domain.com:8733/Config_Service/ConfigService/api/list/configuration

     

    And succeed! You get the expected results.

     

  3. Now you open a PowerShell on the server and execute:

     

    Invoke-RestMethod
    -Uri “https://host.domain.com:8733/Config_Service/ConfigService/api/list/configuration&#8221;
    -Method
    Get

     

    And you will get again the 404 as

    Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

     

    If you get this error below you didn’t setup the certificate correctly, see step 1 and 2

    Invoke-RestMethod : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

     

  4. You try the same PowerShell on the external workstation. And it works …..

 

 

So local it looks not working …… Hmmmm

 

Solution

 

It’s very simple, but took me some time to find … Just disable the DisableLoopbackCheck on the server 😉

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\DisableLoopbackCheck = 1 (as dword)

No restart needed.

 

Hope this helps you,

Michel Kamp

 

 

Create your own website, free on WordPress.com.Create your own website.
Start free