Browsed by
Category: PowerShell

Windows Azure Pack PowerShell sample commands – Add Commands

Windows Azure Pack PowerShell sample commands – Add Commands

To follow on from my last post where I detailed the process of obtaining the basic details from Azure Pack, for this post I will detail the process to Add objects into Azure Pack, for example new user’s, plans & subscriptions.

In the PowerShell script below, you’ll note that the 33 lines are identical to the first 33 lines of the previous post, this ensures that all of the variables we are using will be accessible, as always with WordPress sites make sure that you check the quotation makes when copying and pasting into the ISE. The last 13 lines we create a user object, the email account supplied does not need to exist when using the native Azure Pack tenant portal authentication, this should be swapped out to ADFS or equivalent authentication solutions when in production.

You will also note that when creating the subscription we obtain a variable called $Plan which we then use the ID from for the new Subscription, this saves us the requirement of remembering the ID which looks something like this: 1fc6dc79 which isn’t very easy to recall.

# query SQL function

function Invoke-SQL {

param([string] $connstring,[string] $sqlCommand)

$connectionString = $connstring

$connection = new-object system.data.SqlClient.SQLConnection($connectionString)

$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)

$connection.Open()

$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command

$dataset = New-Object System.Data.DataSet

$adapter.Fill($dataSet) | Out-Null

$connection.Close()

$dataSet.Tables

}

 

# get WAP connection string

$connstring = (Get-MgmtSvcSetting -Namespace adminsite | where {$_.name -eq ‘ApplicationServicesConnectionstring’}).value

$connstring = $connstring.Split(‘;’)[0] + ‘;’ + $connstring.Split(‘;’)[1] + “; Integrated Security=SSPI”

 

# get WAP websites

$adminsite = (Invoke-SQL -sqlCommand “SELECT value FROM [Config].[Settings] where Namespace = ‘AdminSite’ and Name = ‘Authentication.Fqdn'” -connstring $connstring).value

$TenantSite = (Invoke-SQL -sqlCommand “SELECT value FROM [Config].[Settings] where Namespace = ‘TenantSite’ and Name = ‘Authentication.Fqdn'” -connstring $connstring).value

$AuthSite = (Invoke-SQL -sqlCommand “SELECT value FROM [Config].[Settings] where Namespace = ‘AuthSite’ and Name = ‘Authentication.Fqdn'” -connstring $connstring).value

$windowsauthsite = (Invoke-SQL -sqlCommand “SELECT value FROM [Config].[Settings] where Namespace = ‘WindowsAuthSite’ and Name = ‘Authentication.Fqdn'” -connstring $connstring).value

$AdminAPI = (Invoke-SQL -sqlCommand “SELECT value FROM [Config].[Settings] where Namespace = ‘AdminSite’ and Name = ‘Microsoft.Azure.Portal.Configuration.OnPremPortalConfiguration.RdfeAdminUri'” -connstring $connstring).value

$TenantAPI = (Invoke-SQL -sqlCommand “SELECT value FROM [Config].[Settings] where Namespace = ‘TenantSite’ and Name = ‘Microsoft.Azure.Portal.Configuration.AppManagementConfiguration.RdfeUnifiedManagementServiceUri'” -connstring $connstring).value

$ClientRealm = (Invoke-SQL -sqlCommand “SELECT value FROM [Config].[Settings] where Namespace = ‘AdminSite’ and Name = ‘Authentication.RelyingParty'” -connstring $connstring).value.Split(‘,’)[1].replace(‘”Realm”:”‘,).replace(‘”‘,)

 

# Check is cert is signed

$admin = $adminsite.Split(‘:’)

$cert = !(New-Object System.Net.Security.SslStream((New-Object System.Net.Sockets.TcpClient($admin[1].Replace(‘/’,),$admin[2])).GetStream())).IsSigned

 

# get token

$token = Get-MgmtSvcToken -AuthenticationSite $windowsauthsite -ClientRealm $ClientRealm -Type Windows -DisableCertificateValidation:$cert

 

# Add new User

$Email = ‘steve@laptop.com’ #user email address

$name = ‘Steve’ # Name of user

Add-MgmtSvcUser -AdminUri $AdminAPI -Email $Email -name $name -Token $token -DisableCertificateValidation:$cert

 

# Add Plan

$displayname = ‘steve’ # Name of the Plan

Add-MgmtSvcPlan -AdminUri $adminapi -Token $token -DisableCertificateValidation:$cert -DisplayName $displayname

 

# Add Subscription

$SubscriptionName = ‘Steve’ # Name of the Subscription

$PlanName = ‘Steve’ # Name of the Plan

$Email = ‘steve@laptop.com’ #user email address

$uname = ‘Steve’ # Name of user

$plan = get-MgmtSvcPlan -AdminUri $adminapi -Token $token -DisableCertificateValidation:$cert -DisplayName $Planname

Add-MgmtSvcSubscription -AdminUri $AdminAPI -Token $token -DisableCertificateValidation:$cert -AccountAdminLiveEmailId $Email -AccountAdminLivePuid $uname -PlanId $plan.id -FriendlyName $SubscriptionName

 

Like previously this isn’t an exhaustive list of commands but a starting point.

Good Luck Steve

Automated updates of Devolution’s Remote Desktop Manager using SCCM

Automated updates of Devolution’s Remote Desktop Manager using SCCM

Recently I have been spending time going back to basic’s around automation in SCCM with PowerShell to brush up on my skills. As part of this I spent a few days playing around with migrating to use Visual Studio as my development space for PowerShell with Adam Driscoll’s PowerShell Tools for Visual Studio add in, which I can’t recommend highly enough when tied to TFS online, Version becomes a super simple task of checking your code in rather than saving different versions.

So I have my Dev space all setup, and went to connect to my Lab Servers Via Devolutions Remote Desktop Manager and got this Prompt

Which annoyed me to no end as I only installed it 3 weeks ago and it appears there had already been 2 version changes. So rather than just disabling the prompt to check for updates as I would normally do on RDM, I started investigating how I can auto mate the updates of RDM without paying for a Third Party tool, and still have the latest version available from my SCCM Server.

So first things first we need to find out how the Application checks to see if there are any updated versions available, for this we can use Fiddler which is a great tool that allows to capture the Http/Https traffic leaving your computer.

Which presented us with these links:

http://remotedesktopmanager.com/products.htm

http://remotedesktopmanager.com/data/RdmChangeHistoryUpdate.htm

From here we browse to each and can see that http://remotedesktopmanager.com/products.htm returns this:

Which we can obtain the current version for each of the versions of RDM, along with where to download the application exe file from. Right about now I was thinking this is going to be a cake walk we can just step through each of the lines in the htm file and select only the ones which we need.

So we grab the web address and use the following script to obtain the htm page into a PowerShell Variable:

$wc = New-Object Net.WebClient

$srdm = $wc.DownloadString(“http://remotedesktopmanager.com/products.htm”)

And when we run $srdm in the ISE to see the list is looks like this:

This should be super easy, I’m still thinking we can use a simple foreach on $srdm like I would on a normal multi line string. I try it, and I get the all of the information back, which I must say threw me for a minute, so I tried

$srdm.count

With the following result:

I dig deeper into $srdm and find that the end of the line is a line break rather than a carriage Return as I was expecting, so after some quick research found that we can split $srdm using $srdm.Split(“`r`n”) which will separate it on the line break’s rather than the carriage returns. You can see if we now run the following command $srdm.Split(“`r`n”).count that the number is vastly larger than 1 which was the previous result

So we can now use the simple foreach to step through each line in the variable, which will look like this:

$RDMVerChk = “RDMEnterprise”

$wc = New-Object Net.WebClient

$srdm = $wc.DownloadString(“http://remotedesktopmanager.com/products.htm”)

$out = @()

foreach($rdm in $srdm.Split(“`r`n”).count)

{

$obj = New-Object PSObject

if ($rdm -like “*$RDMVerChk*”)

{

$s = $rdm.Split(“=”)

$obj | Add-Member Noteproperty Name $s[0].split(“.”)[1]

$obj | Add-Member Noteproperty Value $s[1]

$out += $obj

}

}

You will see that I have also added a check only return the strings which contain RDMEnterprise as this is the version of RDM we use, you can change the $RDMVerChk variable to the required version. The next step is to create new PSobject to capture the results into a simple Array for use later in the script.

Now the next step is to check in SCCM to check if the version available from the RDM website is currently available, and if it isn’t to publish it.

To start we need to import the Configuration Manager PowerShell module with the following command:

Import-Module $env:SMS_ADMIN_UI_PATH.Replace(“i386”,“ConfigurationManager.psd1”) -Force

Once imported we need to set the current PowerShell location to the SCCM SIteCode for this example P01

Set-Location “P01:”

Now we can completed a simple Get-CMApplication to see if the RDM Version exists, we will use the expected name of the application we create during running this script which is “Remote_Desktop_Manager-$rdmver where $rdmver is the RDM version from the Website.

$rdmver = $out | ForEach-Object {if ($_.Name -eq “Version”){$_.Value}}

if((Get-CMApplication -Name “Remote_Desktop_Manager-$rdmver))

{

write-output “Already Available”

}

else

{

write-output “Needs to be created”

}

Great now we just need to add the application to SCCM, and make it available to users via the Application Catalog. To do this we use the following script:

#download File

$wc.DownloadFile(($out | ForEach-Object {if ($_.Name -eq “exe”){$_.Value}}), $path\RDM.exe”)

#Create RDM folder and Extract MSI from exe

if(!(Test-Path -path $Path\RDM”)){New-Item -Path $Path\RDM” -Force -ItemType Directory | Out-Null}

Start-Process -FilePath $path\RDM.exe” -ArgumentList “/extract:$path\RDM” -Wait

# Extract .ico file from the RDM.exe

[System.Drawing.Icon]::ExtractAssociatedIcon($path\RDM.exe”).ToBitmap().save($path\RDM\RDM.ico”)

$path = $path\RDM”

$InstallFile = (Get-ChildItem -Path $path | where {$_.name -Like “*.msi”}).name

# Create Folders and move files around

if(!(Test-Path -path $DestPath\applications”)){New-Item -Path $DestPath\applications” -Force -ItemType Directory | Out-Null}

if(!(Test-Path -path $DestPath\applications\$prodman)){New-Item -Path $DestPath\applications\$prodman -Force -ItemType Directory | Out-Null}

if(!(Test-Path -path $DestPath\applications\$prodman\$prodname$rdmver)){New-Item -Path $DestPath\applications\$prodman\$prodname$rdmver -Force -ItemType Directory | Out-Null}

Copy-Item $path\*” $DestPath\applications\$prodman\$prodname$rdmver

# Create SCCM Application

Set-Location $Sitecode`:”

# get existing Deployment Types to be SuperSeeded

$oldappdt = Get-CMDeploymentType -ApplicationName $prodname*”

$newapp = New-CMApplication -Name $prodname$rdmver -Publisher ($prodman.replace(” “,“_”)) -SoftwareVersion $rdmver -IconLocationFile $path\rdm.ico” -LocalizedApplicationName ($prodname.replace(” “,“_”))

Add-CMDeploymentType -MsiInstaller -InstallationFileLocation $DestPath\applications\$prodman\$prodname$rdmver\$installfile -Application $newapp -ForceForUnknownPublisher:$true

# Create SuperSeedence for each existing Deployment Type

foreach ($dt in $oldappdt)

{

# You need to get the new Deployment Type each time as it changes when new SuperSeedences are added.

$appdt = Get-CMDeploymentType -ApplicationName $prodname$rdmver

Add-CMDeploymentTypeSupersedence -SupersedingDeploymentType $dt -IsUninstall $true -SupersededDeploymentType $appdt

}

# Disribution Content to a DP (this can be changed to DP Group as needed)

Start-CMContentDistribution -Application $newapp -DistributionPointName $DP

# Create New User collection for deployment, defineing the limiting collection and the collection to include (Can be changed to Query As required)

$newcol = New-CMUserCollection -Name “Install $ProdMan $Prodname $rdmver -LimitingCollectionName $LimitingCol

Add-CMUserCollectionIncludeMembershipRule -Collection $newcol -IncludeCollectionName $IncCol

# deploy New Application to New Collection

Start-CMApplicationDeployment -CollectionName ($newcol.Name) -Name ($newapp.LocalizedDisplayName)

As you can see it is pretty much broken up into 3 phases, Download & Prepare the file, Confirm if folders exist on Media Store & copy extracted files up to the new folders, And create SCCM Application, Supersede old versions & deploy the new application to a New Collection. I will focus on the first 2 phase’s as they contain the interesting parts, while the last phase is using the default create collection & deployment commands for SCCM.

Download phase, we obtain a copy of the file using this command:

$wc.DownloadFile(($out | ForEach-Object {if ($_.Name -eq “exe”){$_.Value}}), $path\RDM.exe”)

Where $wc & $out still exist from earlier use scripts

The next step is to create a scratch folder to target the exe’s /Extract command at, this will give us the following 2 files

The next step is to create the .ico we can use in the Application Catalog to make it look pretty for the end user

[System.Drawing.Icon]::ExtractAssociatedIcon($path\RDM.exe”).ToBitmap().save($path\RDM\RDM.ico”)

Which we are saving into the scratch folder to copy up to the SCCM server. We also define $InstallFile

From the MSI that exists in the scratch folder rather than using assuming that Devolutions will continue to use the same naming convention for the msi file.

The creation of the folders is pretty self-explanatory.

The next phase is to create the SCCM Applications & supersede the old versions.

We obtain the list of existing Application Deployment Types as the first step to ensure it doesn’t include the application we are creating.

With New-CMApplication in addition to the mandatory parameters we also see -LocalizedApplicationName & -IconLocationFile these are used to define the appearance of the application when published in the Application Catalog, the IconLocationFile parameter have the requirement of either a .ico or image file to work, while LocalizedApplicationName is a free text field.

With Add-CMDeploymentType we have included the following parameter -ForceForUnknownPublisher:$true which ensure that if the MSI file is not signed it will still add the deployment type, You should only use this on MSI’s you know & trust the origin of.

To Supersede the existing versions of Remote Desktop Manager we are using the Add-CMDeploymentTypeSupersedence command, as noted above, every time you add a new Superseded deployment type to the new Deployment type you will need reload the variable as it has changed.

So that’s the breakdown, the Whole script looks like this (Make sure you fix the Quotes when copying from the internet when not using PowerShell 5):

Set-Location “c:”

$Sitecode = “” #SCCM SiteCode

$path = “C:\data”

$Destpath = “” #Path to Central media store eg: \\<servername>\Source$

$dp = “” #FQDN of DP to deploy too (single DP at this point)

$LimitingCol = “” # name of limiting Collection

$IncCol = “” # name of collection to include

$RDMVerChk = “RDMEnterprise” # version of RDM

Import-Module $env:SMS_ADMIN_UI_PATH.Replace(“i386”,“ConfigurationManager.psd1”) -Force | Out-Null

$curdrv = (Get-Location).path

$wc = New-Object Net.WebClient

$srdm = $wc.DownloadString(“http://remotedesktopmanager.com/products.htm”)

$out = @()

foreach($rdm in $srdm.Split(“`r`n”))

{

$obj = New-Object PSObject

if ($rdm -like “*$RDMVerChk*”)

{

$s = $rdm.Split(“=”)

$obj | Add-Member Noteproperty Name $s[0].split(“.”)[1]

$obj | Add-Member Noteproperty Value $s[1]

$out += $obj

}

}

$rdmver = $out | ForEach-Object {if ($_.Name -eq “Version”){$_.Value}}

Set-Location $Sitecode`:”

if((Get-CMApplication -Name “Remote_Desktop_Manager-$rdmver))

{

Set-Location $curdrv

}

else

{

Set-Location $curdrv

#download File

$wc.DownloadFile(($out | ForEach-Object {if ($_.Name -eq “exe”){$_.Value}}), $path\RDM.exe”)

#Create RDM folder and Extract MSI from exe

if(!(Test-Path -path $Path\RDM”)){New-Item -Path $Path\RDM” -Force -ItemType Directory | Out-Null}

Start-Process -FilePath $path\RDM.exe” -ArgumentList “/extract:$path\RDM” -Wait

# Extract .ico file from the RDM.exe

[System.Drawing.Icon]::ExtractAssociatedIcon($path\RDM.exe”).ToBitmap().save($path\RDM\RDM.ico”)

$path = $path\RDM”

$InstallFile = (Get-ChildItem -Path $path | where {$_.name -Like “*.msi”}).name

# Create Folders and move files around

if(!(Test-Path -path $DestPath\applications”)){New-Item -Path $DestPath\applications” -Force -ItemType Directory | Out-Null}

if(!(Test-Path -path $DestPath\applications\$prodman)){New-Item -Path $DestPath\applications\$prodman -Force -ItemType Directory | Out-Null}

if(!(Test-Path -path $DestPath\applications\$prodman\$prodname$rdmver)){New-Item -Path $DestPath\applications\$prodman\$prodname$rdmver -Force -ItemType Directory | Out-Null}

Copy-Item $path\*” $DestPath\applications\$prodman\$prodname$rdmver

# Create SCCM Application

Set-Location $Sitecode`:”

# get existing Deployment Types to be SuperSeeded

$oldappdt = Get-CMDeploymentType -ApplicationName $prodname*”

$newapp = New-CMApplication -Name $prodname$rdmver -Publisher ($prodman.replace(“_”,” “)) -SoftwareVersion $rdmver -IconLocationFile $path\rdm.ico” -LocalizedApplicationName ($prodname.replace(“_”,” “))

Add-CMDeploymentType -MsiInstaller -InstallationFileLocation $DestPath\applications\$prodman\$prodname$rdmver\$installfile -Application $newapp -ForceForUnknownPublisher:$true

# Create SuperSeedence for each existing Deployment Type

foreach ($dt in $oldappdt)

{

# You need to get the new Deployment Type each time as it changes when new SuperSeedences are added.

}

# Disribution Content to a DP (this can be changed to DP Group as needed)

Start-CMContentDistribution -Application $newapp -DistributionPointName $DP

# Create New User collection for deployment, defineing the limiting collection and the collection to include (Can be changed to Query As required)

$newcol = New-CMUserCollection -Name “Install $ProdMan $Prodname $rdmver -LimitingCollectionName $LimitingCol

Add-CMUserCollectionIncludeMembershipRule -Collection $newcol -IncludeCollectionName $IncCol

# deploy New Application to New Collection

Start-CMApplicationDeployment -CollectionName ($newcol.Name) -Name ($newapp.LocalizedDisplayName)

# return to original Path

Set-Location $curdrv

}

Good Luck

Steve

Capturing installed Windows Features from Client OS into SCCM without touching the MOF

Capturing installed Windows Features from Client OS into SCCM without touching the MOF

Recently I was asked how to capture the Enabled Windows features from client machines, to help identify the crazy cats who have Hyper-V turned on just so they can run an extra OS or 2 on there Surface Pro 3. So this one was an interesting question in the server OS there is the Win32_ServerFeatures WMI class which is great on servers, but doesn’t exist on client OS’s. All of the information is captured in DSIM right, but how do you turn that into a WMI Class for reporting purposes.

I started off by creating a PowerShell Script with plans to run it in DCM to create the Registry keys which we have traditionally used to capture the information in SCCM, which looks like this:

$f = “”

$feature = dism /online /get-features

foreach ($svc in $feature)

{

if ($svc -like “*Feature Name *”)

{

$f = $f + $svc.Replace(“Feature Name : “, “”) + “,”

}

elseif ($svc -like “*State : *”)

{

$f = $f + $svc.Replace(“State : “,“”) + “;”

}

}

 

Push-Location

Set-Location HKLM:

if ((Test-Path .\software\clientFeatures) -eq $false){New-Item -Path .\software -name clientFeatures | out-null}

foreach ($r in $f.Split(“;”))

{

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

New-ItemProperty .\software\clientFeatures -Name $feat -Value $featset -PropertyType “string” -Force | Out-Null

$feat = “”

$featset = “”

}

}

Pop-Location

So let’s breakdown the script and explain what each of the sections are doing

$feature = dism /online /get-features

This puts the default DISM result into the $feature variable

I know your sitting there like me and wondering how you can turn that into a registry entry.

Well that’s where the next phase of the script comes in and creates a single string

foreach ($svc in $feature)

{

if ($svc -like “*Feature Name *”)

{

$f = $f + $svc.Replace(“Feature Name : “, “”) + “,”

}

elseif ($svc -like “*State : *”)

{

$f = $f + $svc.Replace(“State : “,“”) + “;”

}

}

Which steps through each of the lines in the result of the DISM command, and finds the lines which have “Feature Names” and “State” then writes into string called $f which we will use later. As we have put the , after the Feature name and the ; after the state, we can then split these in the next phase of the script. Which I will now explain what we are doing there:

Push-Location

Set-Location HKLM:

if ((Test-Path .\software\clientFeatures) -eq $false){New-Item -Path .\software -name clientFeatures | out-null}

foreach ($r in $f.Split(“;”))

{

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

New-ItemProperty .\software\clientFeatures -Name $feat -Value $featset -PropertyType “string” -Force | Out-Null

$feat = “”

$featset = “”

}

}

Pop-Location

At a high level we are connecting to HKEY_LOCAL_MACHINE and created a new Key called ClientFeatures under the Software key, then creating a new REG_SZ for each of the features with the states as the value of the key. At this point I was really happy I had all of the features in the registry in a format I could then create a MOF from, this was short lived as I noticed I had over 100 features in the client OS which would create a heartache when creating the MOF file as it would be around 300 lines of boring code. So I went to myself, self why don’t you just create the WMI class with PowerShell then you don’t have to worry about getting the MOF file right, which I responded to self with that’s a great idea I’m amazed I didn’t think of it myself. Below you will see the resulting script:

if ((Get-WmiObject -Class Win32_ClientFeatures -ErrorAction SilentlyContinue).__PROPERTY_COUNT -lt 1)

{

$newClass = New-Object System.Management.ManagementClass(“root\cimv2”, [String]::Empty, $null)

$newClass[“__CLASS”] = “Win32_ClientFeatures”

$newClass.Qualifiers.Add(“Static”, $true)

$newClass.Properties.Add(“key”,[System.Management.CimType]::String, $false)

$newClass.Properties[“key”].Qualifiers.Add(“Key”, $true)

foreach ($r in $f.Split(“;”))

{

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

$newClass.Properties.Add($feat,[System.Management.CimType]::String, $false)

$newClass.Put() | Out-Null

$feat = “”

$featset = “”

}

}

}

if ((Get-WmiObject -Class Win32_ClientFeatures).__path -eq $null){$new = $true} else {$inst = (Get-WmiObject -Class Win32_ClientFeatures).key}

if ($new) {$classinstance = $newClass.CreateInstance()}

foreach ($r in $f.Split(“;”))

{

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

if ($new)

{

$classinstance.$feat = $featset

$classinstance.put() | Out-Null

}

else

{

$fe = Get-WmiObject -Class Win32_clientFeatures

$fe.$feat = $featset

$fe.put() | Out-Null

}

$feat = “”

$featset = “”

}

}

Let’s dive into the breakdown of the slab of code,

if ((Get-WmiObject -Class Win32_ClientFeatures -ErrorAction SilentlyContinue).__PROPERTY_COUNT -lt 1)

This if statement is checking to see if the WMI Class called Win32_ClientFeatures has any properties assigned to it, if the count is less than 1 then we will go ahead and create the WMI Class and create a Property for each of the Windows Features which is this slab of code:

{

$newClass = New-Object System.Management.ManagementClass(“root\cimv2”, [String]::Empty, $null)

$newClass[“__CLASS”] = “Win32_ClientFeatures”

$newClass.Qualifiers.Add(“Static”, $true)

$newClass.Properties.Add(“key”,[System.Management.CimType]::String, $false)

$newClass.Properties[“key”].Qualifiers.Add(“Key”, $true)

foreach ($r in $f.Split(“;”))

{

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

$newClass.Properties.Add($feat,[System.Management.CimType]::String, $false)

$newClass.Put() | Out-Null

$feat = “”

$featset = “”

}

}

}

We have also created a key called “key” inventive I know, but it works. So we now have a WMI Class with all of the properties the next step is to create a WMI instance of the state of each of the Windows Features like so:

if ((Get-WmiObject -Class Win32_ClientFeatures).__path -eq $null){$new = $true} else {$inst = (Get-WmiObject -Class Win32_ClientFeatures).key}

if ($new) {$classinstance = $newClass.CreateInstance()}

foreach ($r in $f.Split(“;”))

{

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

if ($new)

{

$classinstance.$feat = $featset

$classinstance.put() | Out-Null

}

else

{

$fe = Get-WmiObject -Class Win32_clientFeatures

$fe.$feat = $featset

$fe.put() | Out-Null

}

$feat = “”

$featset = “”

}

}

The if statement is checking to see if the there is an existing instance in the WMI object and selects that instance to update, otherwise we will go ahead and create a new instance. As you can see in the script these are 2 different groups of code.

So I now have a great WMI class which I can query with PowerShell and it returns like so:

We are now sitting there really happy with our new WMI class which captures all of the Windows Features settings for the computer great. The next step is to import the new WMI class into SCCM Hardware Inventory, and this is where it became interesting, as I got this error message:

I started doing some digging into this and found that the Remote Server Administration Tools features all started the same along with the language packs, so I tweaked the script to handle this and is still didn’t correct the issue. At about this point I came to the realisation that as easy as it would be from a reporting point of view I would be next to impossible to maintain as each OS version has different features, and then you need to include the RSAT features, and Language packs, which would result of in hundreds of properties required in WMI for each OS just to capture the information.

To get around this we then need to change the WMI class to have 2 properties called Feature which we will make as the Key for the instances, and value which will contain the state for the Feature. To complete this we run the following script:

$f = “”

$new = $true

$feature = dism /online /get-features

foreach ($svc in $feature)

{

if ($svc -like “*Feature Name *”)

{

$f = $f + $svc.Replace(“Feature Name : “, “”) + “,”

}

elseif ($svc -like “*State : *”)

{

$f = $f + $svc.Replace(“State : “,“”) + “;”

}

}

if ((Get-WmiObject -Class ClientFeatures -ErrorAction SilentlyContinue).__PROPERTY_COUNT -lt 1)

{

$newClass = New-Object System.Management.ManagementClass(“root\cimv2”, [String]::Empty, $null)

$newClass[“__CLASS”] = “Win32_ClientFeatures”

$newClass.Qualifiers.Add(“Static”, $true)

$newClass.Properties.Add(“Feature”,[System.Management.CimType]::String, $false)

$newClass.Properties[“Feature”].Qualifiers.Add(“Key”, $true)

$newClass.Properties.Add(“value”,[System.Management.CimType]::String, $false)

$newClass.Put() | out-null

}

 

foreach ($r in $f.Split(“;”))

{

 

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

if ((Get-WmiObject -Class Win32_ClientFeatures).feature -eq $feat)

{

$fe = Get-WmiObject -query “select * from win32_clientFeatures where feature = ‘$feat‘”

$fe.value = $featset

$fe.put() | Out-Null

}

else

{

$classinstance = $newClass.CreateInstance()

$classinstance.feature = $feat

$classinstance.value = $featset

$classinstance.put() | Out-Null

}

$feat = “”

$featset = “”

}

}

The first part is the same as above, but once we get to defining the WMI class it changes a little, now rather than stepping through each of windows features and creating a property for each feature we are now just creating 2 properties called “Feature” and “Value”, only if the WMI class doesn’t exist, as defined in the below script:

if ((Get-WmiObject -Class ClientFeatures -ErrorAction SilentlyContinue).__PROPERTY_COUNT -lt 1)

{

$newClass = New-Object System.Management.ManagementClass(“root\cimv2”, [String]::Empty, $null)

$newClass[“__CLASS”] = “Win32_ClientFeatures”

$newClass.Qualifiers.Add(“Static”, $true)

$newClass.Properties.Add(“Feature”,[System.Management.CimType]::String, $false)

$newClass.Properties[“Feature”].Qualifiers.Add(“Key”, $true)

$newClass.Properties.Add(“value”,[System.Management.CimType]::String, $false)

$newClass.Put() | out-null

}

The next step is to create a new instance for each features, defining the feature name and the state like so:

foreach ($r in $f.Split(“;”))

{

 

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

if ((Get-WmiObject -Class Win32_ClientFeatures).feature -eq $feat)

{

$fe = Get-WmiObject -query “select * from win32_clientFeatures where feature = ‘$feat‘”

$fe.value = $featset

$fe.put() | Out-Null

}

else

{

$classinstance = $newClass.CreateInstance()

$classinstance.feature = $feat

$classinstance.value = $featset

$classinstance.put() | Out-Null

}

$feat = “”

$featset = “”

}

}

We are also checking to see if the instance already exists for the feature, if it does exist, we will need to update the value, otherwise we create a new class instance.

Now when we import the WMI class into the SCCM console it doesn’t throw an error, and we can see the v_GS_ClientFeatures in SQL Reporting Services as an option to report upon now, so how do I get the list of computers which have Hyper-V Enabled, well you create a SQL Report with the following query:

select rsys.Name0

from v_R_System as rsys join

v_GS_CLIENT_FEATURES as feat on rsys.ResourceID = feat.ResourceID

where Feature0 = ‘Microsoft-Hyper-V’ and

value0 = ‘enabled’

And the WMI Query for a collection looks like this:

select * from SMS_R_System inner join SMS_G_System_CLIENT_FEATURES on SMS_G_System_CLIENT_FEATURES.ResourceId = SMS_R_System.ResourceId where SMS_G_System_CLIENT_FEATURES.Feature = “Microsoft-Hyper-V” and SMS_G_System_CLIENT_FEATURES.value = “Enabled”

The DCM detection PowerShell script looks like this:

$compliance = “Compliant”

$f = “”

$feature = dism /online /get-features

foreach ($svc in $feature)

{

if ($svc -like “*Feature Name *”)

{

$f = $f + $svc.Replace(“Feature Name : “, “”) + “,”

}

elseif ($svc -like “*State : *”)

{

$f = $f + $svc.Replace(“State : “,“”) + “;”

}

}

if ((Get-WmiObject -Class win32_ClientFeatures -ErrorAction SilentlyContinue).__PROPERTY_COUNT -eq 2)

{

foreach ($r in $f.Split(“;”))

{

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

$cls = Get-WmiObject -query “select * from win32_clientFeatures where feature = ‘$feat‘”

if ($cls.value -ne $featset) {$compliance = “Non-Compliant”}

$feat = “”

$featset = “”

}

}

}

else

{

$compliance = “Non-Compliant”

}

$compliance

And the DCM remediation PowerShell script looks like this:

$f = “”

$new = $true

$feature = dism /online /get-features

foreach ($svc in $feature)

{

if ($svc -like “*Feature Name *”)

{

$f = $f + $svc.Replace(“Feature Name : “, “”) + “,”

}

elseif ($svc -like “*State : *”)

{

$f = $f + $svc.Replace(“State : “,“”) + “;”

}

}

if ((Get-WmiObject -Class ClientFeatures -ErrorAction SilentlyContinue).__PROPERTY_COUNT -lt 1)

{

$newClass = New-Object System.Management.ManagementClass(“root\cimv2”, [String]::Empty, $null)

$newClass[“__CLASS”] = “Win32_ClientFeatures”

$newClass.Qualifiers.Add(“Static”, $true)

$newClass.Properties.Add(“Feature”,[System.Management.CimType]::String, $false)

$newClass.Properties[“Feature”].Qualifiers.Add(“Key”, $true)

$newClass.Properties.Add(“value”,[System.Management.CimType]::String, $false)

$newClass.Put() | out-null

}

 

foreach ($r in $f.Split(“;”))

{

 

if ($r -ne “”)

{

$feat = $r.Split(“,”)[0].ToString()

$featset = $r.Split(“,”)[1].ToString()

if ((Get-WmiObject -Class Win32_ClientFeatures).feature -eq $feat)

{

$fe = Get-WmiObject -query “select * from win32_clientFeatures where feature = ‘$feat‘”

$fe.value = $featset

$fe.put() | Out-Null

}

else

{

$classinstance = $newClass.CreateInstance()

$classinstance.feature = $feat

$classinstance.value = $featset

$classinstance.put() | Out-Null

}

$feat = “”

$featset = “”

}

}

$compliance = “Compliant”

$compliance

For the DCM you will need to do a detection on a string that equals “Compliant” and remediate if it not.

As an recap of the whole blog, you can see there is a couple of ways to capture the information, depending upon the amount of properties it might make sense to have a single WMI instance in the WMI class, but in other cases it might make sense to have a large number of WMI instances in the WMI class, each have their advantages and disadvantages for the methods. The nice part of this solution is we don’t need to worry about making any changes to the MOF which makes life so much easier.

Good Luck

Steve

WMI and PowerShell v4 a match made in heaven

WMI and PowerShell v4 a match made in heaven

Natively Windows has a tool to access and view the WMI Namespaces, called WBEMtest.exe. In my opinion it can be quite clunky to use, especially when you are starting to learn WMI. There are multiple WMI Explorer’s out there that do a much better job of presenting the NameSpaces, Classes, Properties & Methods (personally, I use WMI Explorer from Sapien).

Another option is to use Window’s PowerShell to access the WMI objects.

You ask, why would I move from a GUI to a CLI for something like this? Answer: Because it is quicker, especially if it is something you query, quite often you can just simply save the query. It’s hard to save where you need to go in a GUI.

For this blog I’m going to discuss the 2 primary PowerShell cmdlets for WMI which are Get-WmiObject and Invoke-WmiMethod.

Get-WmiObject is used to get a WMIObject be it a NameSpace or a Class. You can also run a WQL Query using this same CmdLet.

An example would be Get-WmiObject -Class win32_bios which will return the following:

Again I hear well that’s great Steve you know to get that information you need to grab the win32_bios class, how the heck do I find what I’m looking for in PowerShell?

Well since PowerShell 3.0 there is a great parameter added to the Out-GridView cmdlet called PassThru. What this allows us to do is select the result we want from the gridview, and do something with it. As a script you could do something like this;

$wmi = Get-WmiObject -List | Out-GridView -passthru
Get-WmiObject -Class $wmi.Name 

 When we run the Script a box will appear like below, in the filter box you can treat this like a search;

When we search for Bios the list will be filtered down to only objects which contain BIOS, we can then select Win32_bios and click ok which places the whole Win32_BIOS object as $WMI;

And the final line is to get the WMI object we have selected;

Invoke-WmiMethod is used to invoke a method that is attached to a Class or Namespace, this one has a little bit more of a niche use case, but is very powerful.

For example we can use the following line to start an application like WBEMTest.exe;

Invoke-WmiMethod -class win32_process -name create -ArgumentList “wbemtest.exe”

As you can see WBEMTest will then appear on the screen.

You can find methods out the same way as you find classes with the following line of code;

$wmi = Get-WmiObject -List | Out-GridView -passthru
Get-WmiObject -Class $wmi.Name | Get-Member -MemberType Methods

 

So the same box as earlier will appear when we run the above lines;


In this example we have searched for Win32_process as it has Methods attached as you can see in the list

Once you select win32_process and Ok you will get the below results.

Ok so we have now used the Get-WmiObject and Invoke-WmiMethod
commandlets separately, let’s join them together and show how there is 2 ways to invoke the methods.

So in this example we are going to start WBEMTest.exe again and then close it by using the Win32_process Methods, the script looks like this;

$wbem = Invoke-WmiMethod -class win32_process -name create -ArgumentList
“wbemtest.exe”
$procid = $wbem.ProcessID
$res = Get-WmiObject -Query “Select * from win32_process where ProcessID = $procid
$res
$res.Terminate() 

 

So as you can see we are defining $wbem
with the result of Invoke-WmiMethod
which is creating a process for WBEMTest.exe, this allows us to capture the ProcessID which we then define as $procid on the next line.

From here we are querying the WMIObject Win32_Process where ProcessID = $procid, which will return the results of the process we just created into the $res variable.

We then return the $res
variable onto the screen to show that the script is doing something.

And the last line we actually close the WBEMtext.exe process we created in the first line. Which as you can see from the list of methods for Win32_process Terminate exists there.

Good Luck

Steve