.Net Frameworks – Installed Products

Background

Wanted to get a list of Microsoft .Net Frameworks installed on a machine.

Windows Management Interface ( WMI )

Introduction

In this post, we will use Windows Management Interface, WMI.

 

Powershell

Outline

  1. Get-WmiObject
    • Class :- Win32_Product
    • Filter :- Microsoft .Net Framework
    • Columns :-
      • Name
      • Version

Code


[char] $CHAR_WILDCARD="*"

$computer=$env:computername

$filter="Microsoft .Net Framework"

$filterWildcard= $filter + $CHAR_WILDCARD

Get-WmiObject -Class Win32_Product -Computer $computer | `

	Select @{"Name"="Name"; "Expression"={($_.Name.trim())}}, Version | `

	Where-Object -FilterScript {$_.Name -like $filterWildcard} | `

	Sort-Object Name, Version -Descending

Images

getVersionNumber_self_20181207_1209PM

Powershell

Outline

  1. Get-WmiObject
    • Class :- Win32_Product
    • Filter :- Microsoft .Net Framework
    • Columns :-
      • Name
      • Version

Code


set "_wildcard=%%"

wmic product where "Name like 'Microsoft .Net %_wildcard%' " get Name, Version

Images

MSWindowsBatch.20181207.1229PM

WMI – Error – “0x8004100E”

Background

Trying to steal and use someone else’s code does not do well for me.

Here I am having stolen a code, but stuck with bad characters and an error message.

Code ( Original )


OPTION EXPLICIT

Dim strComputer
Dim URL
Dim objWMIService
Dim colItems
Dim objItem


strComputer = "."

URL="winmgmts:\\" & strComputer & "\root\Microsoft\SqlServer\ComputerManagement10"

Wscript.Echo "URL is "& URL

set objWMIService = GetObject(URL)

Set colItems = objWMIService.ExecQuery("SELECT * FROM SecurityCertificate",,48)

For Each objItem in colItems

	Wscript.Echo ""

	Wscript.Echo "SecurityCertificate instance"
	Wscript.Echo ""
	Wscript.Echo "ExpirationDate: " & objItem.ExpirationDate
	Wscript.Echo "FriendlyName: " & objItem.FriendlyName
	Wscript.Echo "IssuedBy: " & objItem.IssuedBy
	Wscript.Echo "IssuedTo: " & objItem.IssuedTo
	Wscript.Echo "Name: " & objItem.Name
	Wscript.Echo "SHA: " & objItem.SHA
	Wscript.Echo "StartDate: " & objItem.StartDate
	Wscript.Echo "SystemStore: " & objItem.SystemStore


Next

 

Error

Error Image

Error Message


(null): 0x8004100E

Trouble Shooting

WMI Code Creator

Download WMI Code Creator from here.

Extract

Extract the compressed ( zip) file.

Run

Run the file.

Namespace

Looked at the NameSpaces…

They are version specific.

The one I want is root\Microsoft\SqlServer\ComputerManagement12.

But, the one referenced in the code is root\Microsoft\SqlServer\ComputerManagement10.

On this particular box I am on SQL Server v2014.

And, so ComputerManagement12 is SQL 2014.

While ComputerManagement10 is SQL Server 2008.

 

Code ( Revised )

Code revised for v2014.

 

OPTION EXPLICIT
On error resume next

Dim strComputer
Dim baseURL
Dim sqlServerVersion
Dim URL
Dim objWMIService
Dim colItems
Dim objItem
Dim query

strComputer = "."

baseURL="winmgmts:\\" & strComputer & "\root\Microsoft\SqlServer\"
rem comment out version information
rem sqlServerVersion="ComputerManagement10"
sqlServerVersion="ComputerManagement12"

URL=baseURL & sqlServerVersion

set objWMIService = GetObject(URL)

if (Err.Number <> 0) then

	Wscript.Echo "GetObject failed on " & URL
	Wscript.Echo "Error Number is " & CSTR(Err.Number)
	Wscript.Echo "Error Description is " & Err.Description

	Wscript.Quit
	
end if

query = "SELECT * FROM SecurityCertificate"

Set colItems = objWMIService.ExecQuery(query,,48)


if (Err.Number <> 0) then

	Wscript.Echo "ExecQuery failed on " & query
	Wscript.Echo "Error Number is " & CSTR(Err.Number)
	Wscript.Echo "Error Description is " & Err.Description

	Wscript.Quit
	
end if

For Each objItem in colItems

	Wscript.Echo ""

	Wscript.Echo "SecurityCertificate instance"
	Wscript.Echo ""
	Wscript.Echo "ExpirationDate: " & objItem.ExpirationDate
	Wscript.Echo "FriendlyName: " & objItem.FriendlyName
	Wscript.Echo "IssuedBy: " & objItem.IssuedBy
	Wscript.Echo "IssuedTo: " & objItem.IssuedTo
	Wscript.Echo "Name: " & objItem.Name
	Wscript.Echo "SHA: " & objItem.SHA
	Wscript.Echo "StartDate: " & objItem.StartDate
	Wscript.Echo "SystemStore: " & objItem.SystemStore


Next

Sapien – WMI Explorer – Reporting Services Configuration Manager

Background

Wanted to utilize another WMI Query tool in addition to Microsoft’s own WMI tools.

 

Lineage

Posts

SQL Server Reporting Services (SSRS) – Error – “Invalid Class”

In the “SQL Server Reporting Services (SSRS) – Error – Invalid Class” post, we bemoaned the difficulty of fully espousing our wilderness experience based on screenshots from a single tool; that tool being Microsoft WMI Explorer.

The post is here.

Microsoft’s WMI Explorer is available at Codeplex and here is the specific URL.

 

Sapien

We wanted to try out one more tool and the one we chose is Sapien WMI Explorer.

Download

Please download WMI Explorer from here.

The current version is 2.2.74.

Requirements

  1. OS Version
    • Desktop :- Windows 7 / Windows 8 / Windows 8.1 / Windows 10
    • Server :- Windows Server 2008 R2 / Windows Server 2012 / Windows Server 2012 R2
  2. OS Bitness
    • 32 and 64 bit
  3. Powershell
    • Version :- Powershell Version 3.0
  4. Visual Studio 2012 Runtime

 

Install

Installation is straightforward.

Register

Connect to the Vendor’s web site and request a trial key.

 

Usage

Launch Sapien’s WMI Explorer and navigate the Class Browser tree.

As one chooses a specific Namespace, the classes and corresponding properties and methods for that class are shown in the right window.

We are interested in SQL Server Namespace and specifically the ReportServer space.

Please click on the Query button on the Ribbon Tab to view and edit queries.

Image

Pasted below are the images captured from our journey.

Hierarchy

Hierarchy – \\<Host>\ROOT\Microsoft\SqlServer

Hierarchy – \\<Host>\ROOT\Microsoft\SqlServer\ReportServer

Hierarchy – \\<Host>\ROOT\Microsoft\SqlServer\ReportServer\<Instance>
Instance – Default

Instance – DATACAP

 

Hierarchy – \\<Host>\ROOT\Microsoft\SqlServer\ReportServer\<Instance>\<Version>
Instance – {RS_DATACAP }\ Version {v12}

Instance – {RS_DATACAP }\ Version {v12} – Custom Query

Instance – {RS_DATACAP }\ Version {v12} – Query Results

Hierarchy – \\<Host>\ROOT\Microsoft\SqlServer\ReportServer\<Instance>\<Version>\Admin
Instance – {RS_DATACAP }\ Version {v12} \ Admin – Custom Query

Instance – {RS_DATACAP }\ Version {v12} \ Admin – Query Results

 

WMI – Reporting Services Configuration Manager – Event Viewer

Background

When troubleshooting Reporting Services Configuration Manager WMI calls it can be useful to see whether WMI activities are occurring.

 

TroubleShooting

Event Viewer

Enable Log

WMI calls are logable in the Event Viewer.

But, they are not logged by default.

To enable logging please follow the steps listed below:

Obtaining WMI Events Through Event Viewer
Link

  1. Open Event Viewer. On the View menu, click Show Analytic and Debug Logs
  2. Locate the Trace channel log for WMI under Applications and Service Logs | Microsoft | Windows | WMI Activity
  3. Right-click the Trace log and select Log Properties. Click the Enable Logging check box to start the WMI event tracing
  4. WMI events appear in the event window for WMI-Activity. Double-click an event in the list to see the detailed information. You can view an event in XML View or in Friendly View format.

Logged Events

Tabulate

# Event
1 GroupOperationId = 159602; OperationId = 159602; Operation = IWbemServices::Connect; ClientMachine = QADB; User = dadeniji.adeniji; ClientProcessId = 5024; NamespaceName = \\QA\root\Microsoft\SqlServer\ReportServer
2 GroupOperationId = 159603; OperationId = 159604; Operation = Start IWbemServices::CreateInstanceEnum – __NAMESPACE; ClientMachine = QADB; User = daniel.adeniji; ClientProcessId = 5024; NamespaceName = \\.\root\Microsoft\SqlServer\ReportServer
3 GroupOperationId = 159605; OperationId = 159605; Operation = IWbemServices::Connect; ClientMachine = QADB; User = daniel.adeniji; ClientProcessId = 5024; NamespaceName = \\QADB\root\Microsoft\SqlServer\ReportServer\RS_DATACAP\v12\Admin
4 GroupOperationId = 159606; OperationId = 159607; Operation = Start IWbemServices::CreateInstanceEnum – MSReportServer_ConfigurationSetting; ClientMachine = QADB; User = daniel.adeniji; ClientProcessId = 5024; NamespaceName = \\.\root\Microsoft\SqlServer\ReportServer\RS_DATACAP\v12\Admin
5 ProviderInfo for GroupOperationId = 159606; Operation = Provider::CreateInstanceEnum – MSReportServer_ConfigurationSetting; ProviderName = ReportingServicesWMIProvider; ProviderGuid = {0A0B6A3E-DAA2-4ED9-A603-B1C4ED9515FF}; Path = C:\Program Files (x86)\Microsoft SQL Server\120\Shared\reportingserviceswmiprovider.dll

 

Explanation

  1. Event #1 :- IWebServices Create Instance Enum
    • NamespaceName :- \\QA\root\Microsoft\SqlServer\ReportServer
  2. Event #2 :- IWebServices Create Instance Enum
    • NamespaceName :- \\.\root\Microsoft\SqlServer\ReportServer
  3. Event #3 :- IWebServices Connect
    • NamespaceName :- \\.\root\Microsoft\SqlServer\ReportServer\RS_DATACAP\v12\Admin
  4. Event #4 :- IWebServices Instance Enumerate
    • NamespaceName :- \\.\root\Microsoft\SqlServer\ReportServer\RS_DATACAP\v12\Admin
  5. Event #5 :- Com Object Instantiated
    • COM Object ID :- 0A0B6A3E-DAA2-4ED9-A603-B1C4ED9515FF
    • COM File :- C:\Program Files (x86)\Microsoft SQL Server\120\Shared\reportingserviceswmiprovider.dll

 

Summary

From logging WMI Calls we are able to see the inner workings of the WMI Provider class and IWbemServices interface.

In the case of Sql Server Reporting Services (SSRS) it is an version specific dll ( C:\Program Files (x86)\Microsoft SQL Server\120\Shared\reportingserviceswmiprovider.dll ).

SQL Server – Reporting Services – Administrating Using SSMS – WMI Network Port – Requirements

Background

We are experiencing errors connecting to a remote SQL Server Reporting Services Instance over SQL Server Management Studio.

 

Error Message

Here is the error message that we were getting.

Error Image

connecttoserver-20170105-0351pmwireshark-netshfw-20170105-0349pm-clipped

Error Text


TITLE: Connect to Server
------------------------------

Cannot connect to DBSERVER.

------------------------------
ADDITIONAL INFORMATION:

An unexpected error has occurred. Details:

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) (Microsoft.SqlServer.Management.UI.RSClient)

------------------------------

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) (mscorlib)

------------------------------
BUTTONS:

OK
------------------------------


 

TroubleShooting

Client

Netstat

Netstat Command


netstat -an | find "SYN"

Netstat Output

netstat-syn-20170105-0217pm-cleanedup

Explanation

  1. Trying to connect to port 49154

 

Server

WireShark

WireShark Trace

reportingservices-sharedinterface-20170105-0339pm-clipped

 

Remediation

Windows Management Interface (WMI)

Specific Network Port Number

Netsh firewall add – Using netsh firewall

Code

winmgmt -standalonehost

net stop winmgmt /y

netsh firewall add portopening TCP 24158 WMIFixedPort

net start winmgmt /y

 

Output
Output – Textual
>winmgmt -standalonehost
Service configuration changes succeeded.

Please stop and restart Winmgmt service for changes to take effect.

>net stop winmgmt /y
The Windows Management Instrumentation service is stopping.
The Windows Management Instrumentation service was stopped successfully.


>netsh firewall add portopening TCP 24158 WMIFixedPort

IMPORTANT: Command executed successfully.
However, "netsh firewall" is deprecated;
use "netsh advfirewall firewall" instead.
For more information on using "netsh advfirewall firewall" commands
instead of "netsh firewall", see KB article 947709
at http://go.microsoft.com/fwlink/?linkid=121488 .

Ok.


>net start winmgmt /y
The Windows Management Instrumentation service is starting.
The Windows Management Instrumentation service was started successfully.


 

Output – Image

netsh-firewall-20170105-0246pm

Wireshark
Wireshark -01

wireshark-netshfw-20170105-0349pm-clipped

 

Wireshark -02

wireshark-netshfw-20170105-0416pm-clipped

 

Explanation
  1. Image-01
    • Cannot identify specific error messages
  2. Image-02
    • Upon waiting a little while, noticed errors
      • The red ones
        • Ephemeral Port +135

Netsh firewall add – Using netsh advfirewall

Goal

We need to rid ourselves of the warning message that reads “netsh firewall” is deprecated.

We will thus replace “netsh firewall” with “netsh advfirewall

Code

winmgmt -standalonehost

net stop winmgmt /y

rem Setting up a Remote WMI Connection
rem https://msdn.microsoft.com/en-us/library/aa822854(v=vs.85).aspx
rem netsh firewall add portopening TCP 24158 WMIFixedPort
netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes

net start winmgmt /y

Output
Output – Textual


>winmgmt -standalonehost
Service configuration changes succeeded.

Please stop and restart Winmgmt service for changes to take effect.

>net stop winmgmt /y
The Windows Management Instrumentation service is stopping.
The Windows Management Instrumentation service was stopped successfully.


>rem Setting up a Remote WMI Connection

>rem https://msdn.microsoft.com/en-us/library/aa822854(v=vs.85).aspx

>rem netsh firewall add portopening TCP 24158 WMIFixedPort

>netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes

Updated 4 rule(s).
Ok.


>net start winmgmt /y
The Windows Management Instrumentation service is starting.
The Windows Management Instrumentation service was started successfully.



Output – Image

netsh-advfirewall-20170105-0256pm

 

Wireshark

reportingservices-20170105-0300pm-clipped

 

Explanation
  1. We are redded at 51840+135
    • The network adds up the ephemeral port (58140) to the DCOM Port (135)

 

Resource Monitor

Unfortunately, it appears that through the “netsh firewall” and “netsh advfirewall“, WMI will be using ephemeral ports.

To test this out, start a Reporting Services connection request…

Netstat  / find “SYN”

On connecting client, issue Netstat /find “SYN” request

netstat-syn-20170105-0431pm-cleaned-up

Explanation

We see that netstat is seeing SYN_SENT on port 50917.

 

Resource Monitor

On server, review svchost listening ports via “Resource Monitor”

resoucemonitor-svchost-20170105-0426pm

 

Explanation

We see that svchost (winmgmt) is waiting on 50917; and ephemeral port.

 

Set Specific Port for WMI

Explicitly Set Port for WMI Component

Using Component Services, let us designate a specific port for Windows Management (WMI)

  1. Launch Component Services
  2. Navigate to Windows Management
  3. Edit the component’s property
    • Set DCOM Endpoint
      • Options includes
        • Use default endpoints
          • Not the one we want ( in this case), as it is ephemeral
        • Use static endpoint
          • Yes, as want to be explicit that we rely on one opened via the Firewall
        • Internet & Intranet
          • Can be considered, if you have codified ones for all DCOM Components

componentservices-wmi-staticendpoint-usestaticendpoint

 

Restart WMI Services

net stop winmgmt /y

net start winmgmt

 

Resource Monitor ( 2nd Time )

Post WMI Service restart, the previously assigned ports for WMI goes away

resoucemonitor-svchost-20170105-0446pm

 

Re-initiate Reporting Services Connection via SSMS

SSMS

We connected

connected-20170105-0451pm

WireShark

wireshark-compsvc-20170105-0449pm-brushed-up

 

Cleanup Changes

If this is just a test, please take upon the following clean-up tasks

Revert


@echo off
winmgmt -sharedhost

net stop winmgmt /y

net start winmgmt /y

:complete
echo completed

 

 

Technical: Microsoft – Map Processes to Command Line Parameters

Technical: Microsoft – Map Processes to Command Line Parameters

We had a little problem associating high CPU processes to their associated command line parameters.

Historically, the Task Manager only shows each process’s executable name.  It does not even reveal the process’s full path name.

Sometimes with spawned processes such as cmd.exe or cscript.exe it is difficult to differentiate one process from another.  The ability to tell one process from another becomes important as one is trying to measure each payload’s resource uptake.

Here is a command shell \ batch file script that can be used:

Command File


@echo off
rem Creating and editing formats in WMIC
rem http://technet.microsoft.com/en-us/library/cc757287(WS.10).aspx
rem Examples of WMIC commands for Windows .NET SERVER Family
rem http://support.microsoft.com/servicedesks/webcasts/wc072402/listofsampleusage.asp
If not exist C:\Temp md C:\temp
WMIC /OUTPUT:C:\Temp\ProcessList.txt path win32_process get Caption,Processid,Commandline
WMIC /OUTPUT:C:\Temp\processList.xml path win32_process get Caption,Processid,Commandline   /format:rawxml
WMIC /OUTPUT:C:\Temp\processList.html path win32_process get Caption,Processid,Commandline   /format:hform

Explanation:

  • Uses WMI to query the process table
  • Three files containing the same extracted data are placed in C:\Temp
  • The format are txt (plain text), xml, and html

PowerShell File


###################################################################################################
# Use
#
#    A] List processes along with command line parameters#
#
#   Parameters:
#
#      Name :- $ProcessName
#            Mandatory - No
#            Default - Empty
#
#
#   To list all processes:
#      .\listProcesses.ps1
#
#   To list all cscript processes:
#      .\listProcesses.ps1 -ProcessName cscript
#
#   To list all Google's Chrome processes:
#      .\listProcesses.ps1 -ProcessName chrome
#      -- by the way you will be surely suprised as to what 
#         Chrome does with command line paramters
###################################################################################################

[CmdletBinding()]
param
(
	  [Parameter(Mandatory=$False)]
	  [string]$ProcessName

)

# set computer name
[String] $computerName = ".";

[String] $namespace = "root\cimv2";

if ($ProcessName)
{
  $ProcessNameClause = "*" + $ProcessName + "*";

  $objListofProcesses = Get-WmiObject
                            -Namespace $namespace 
                            -Class Win32_Process 
                          | where-Object  
                            {$_.name -like $ProcessNameClause}
}
else
{

   $objListofProcesses = Get-WmiObject 
                             -Namespace $namespace 
                             -Class Win32_Process
}

if (!$objListofProcesses)
{
	return;
}

$iNumberofProcesses = 0;

$strFormatProcess = "Process Name: {0}  ID:{1} CommandLine: {2}";

Foreach ($objProcess in $objListofProcesses)
{

 	$iNumberofProcesses = $iNumberofProcesses + 1;

	#How to format in PowerShell
	$strProcess = [String]::Format(
					  $strFormatProcess
					, $objProcess.Name
					, $objProcess.ProcessId
					, $objProcess.CommandLine
				       );

	$strProcess;

}

Explanation:

  • Uses WMI to query the process table
  • Result is displayed on the console

References

Microsoft – WMI – Query Tool (Ben Colemen)

In the last couple of months, I have played a bit with WMI and PowerShell.

It helps to have a good & reliable Query Tool.  And, I found Ben Coleman’s WMI Query Tool to work well.

But, lately, I have had problems getting it to connect to other namespaces (such as root\Microsoft\SqlServer\ComputerManagement).

So fought it with it a bit.

But, as always gave up.

That is till today when I visited Ben’s Blog @ http://www.bencoleman.co.uk/wmi-query-tool and read through other people’s comment (OPC).

One of the posters had the same problem back in Jan 10 2010.

Here is the question:

Hi Ben,
this served my well in the past for CIMv2 namespace.
Remotely On local machine
Query: works works
Class Viewer: works works
I’m trying with the MicrosoftIISv2 namespace and I get the following:
Remotely On local machine
Query: does not work does not work
Class Viewer: does not work works
Someone else writing about it validated my problems and somehow made me feel \ know that I was not just entering the data (namespace or query) correctly.

Anyways the fix is to:

  1. Click on the “Connect Menu”
  2. Select “Connect to Remote Machine”
  3. On the HostName entry field “Enter the Server’s name”
  4. On the NameSpace, enter NameSpace such as Root\Microsoft\SqlServer\ComputerManagement