Azure Automation Runbook to Add Computer to ConfigMgr Collection

Below for reference a quick PowerShell sample for adding a computer to a device collection in System Center Configuration Manager (ConfigMgr) via Azure Automation runook, designed for use on an OMS Hybrid Runbook Worker. It uses WMI, and so does not require the ConfigMgr PowerShell cmdlets. This also means it works for ConfigMgr 2012 and 2016.

It was used as an example in my talk “Evolving your automation strategy with OMS” at MS Ignite 2016. You can get this and the other sample from that session from my Git repo at https://github.com/pzerger/Ignite2016. The runbook is pretty well commented, but post questions beneath this post if anything is unclear.

Param(
[Parameter(Mandatory=$true)][PSCredential]$SCCMCred,
[Parameter(Mandatory=$true)][string]$CollectionName,
[Parameter(Mandatory=$true)][string]$ComputerName
)
#Retrieve SCCM site server name from Azure Automation variable
$SiteServer = Get-AutomationVariable SCCMSiteServer
Write-Verbose "SCCM Site Server: '$SiteServer'"
Write-Verbose "Connecting to SCCM Site server using user name '$($SCCMCred.UserName)'."

#Query site server WMI to get site code and SMS provider computer name
$ProviderLocation = Get-WmiObject -Namespace "Root\SMS" `
-Query "Select * from SMS_ProviderLocation" -Credential $SCCMCred -ComputerName $SiteServer
$SiteCode = $ProviderLocation.SiteCode
$SMSProvider = $ProviderLocation.Machine
Write-Verbose "SCCM Site Code: '$SiteCode'."
Write-Verbose "SMS Provider computer name: '$SMSProvider'."

#Get the collection WMI object
$Collection = Get-WmiObject -Namespace "Root\SMS\Site_$SiteCOde" `
-Query "Select * from SMS_Collection Where Name = '$CollectionName'" -Credential $SCCMCred -ComputerName $SMSProvider
If ($Collection){
$CollectionID = $Collection.CollectionID
Write-Verbose "collection '$CollectionName' ID is: '$CollectionID'"
} else {
throw "Unable to find collection with name '$CollectionName'. Unable to continue"
Exit -1
}

#Get the computer resource
$Resource = Get-WmiObject -ComputerName $SMSProvider -Namespace "Root\SMS\Site_$SiteCode" `
-Class "SMS_R_System" -Filter "Name = '$ComputerName'" -Credential $SCCMCred | select name,resourceid
If ($Resource){
$ResourceID = $Resource.resourceid
Write-Verbose "Resource ID for computer '$ComputerName' is: '$ResourceID'"
} else {
throw "Unable to find computer resource for '$ComputerName'. Unable to continue."
Exit -1
}

#Create static membership rule for collection
Write-Verbose "Adding computer '$ComputerName' to collection '$CollectionName' by creating a new static membership rule."
$ruleClass = Get-WmiObject -List -ComputerName "$SMSProvider" `
-Namespace "Root\SMS\Site_$Sitecode" -Credential $SCCMCred -class "SMS_CollectionRuleDirect"
$newRule = $ruleClass.CreateInstance()
$newRule.RuleName = $($Resource.name)
$newRule.ResourceClassName = "SMS_R_System"
$newRule.ResourceID = $($Resource.resourceid)
$AddResult = ($Collection.AddMembershipRule($newRule)).ReturnValue

If ($AddResult -eq 0)
{
Write-Output "Collection `"$CollectionName`" direct membership rule successfully created for computer `"$ComputerName`", requesting refresh now."
$RefreshResult = ($Collection.RequestRefresh()).ReturnValue
If ($RefreshResult -eq 0)
{
Write-Output "Collection refresh successfully requested for `"$CollectionName`"."
} else {
Write-Error "Failed to request collection refresh for `"$CollectionName`"."
}
} else {
Write-Error "Failed to add computer '$ComputerName' as a direct member for collection `"$CollectionName`"."
}

Questions or comments? Use the comments section below.

Creating ConfigMgr User Collections with PowerShell

Below for reference a quick PowerShell sample for creating a query-based user collection in System Center Configuration Manager (ConfigMgr), along with a demonstration of some of the options you can supply to control collection population and refresh behavior.

You can download the up-to-date ConfigMgr PowerShell cmdlets at https://www.microsoft.com/en-us/download/details.aspx?id=46681.

The ConfigMgr PowerShell cmdlet reference documentation is available at https://technet.microsoft.com/en-us/library/jj821831(v=sc.20).aspx.

Sample script for user collections

# Import ConfigMgr PowerShell module 
Import-Module (Join-Path $(Split-Path $env:SMS_ADMIN_UI_PATH) ConfigurationManager.psd1) 

# Change to ConfigMgr drive, where HOU is your site code
cd ‘c:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin’
Set-Location HOU:

# Create schedules for refreshing collection membership
$MonSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Monday -RecurCount 1
$TueSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Tuesday -RecurCount 1
$WedSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Wednesday -RecurCount 1
$ThuSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Thursday -RecurCount 1
$FriSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Friday -RecurCount 1
$SatSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Saturday -RecurCount 1
$SunSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Sunday -RecurCount 1

# Define user collection we will create 
# If you want to enable incremental updating on the Collections, you can set the –RefreshType to 'Both'. 
New-CMUserCollection -Name "Accounting Users" -LimitingCollectionName "All Users" `
-RefreshSchedule $MonSched -RefreshType Periodic

# Define query rule for my collection 
Add-CMUserCollectionQueryMembershipRule -CollectionName "Accounting Users" `
-QueryExpression "select * from SMS_R_User where SMS_R_User.UserGroupName = 'CONTOSO\\Accounting'" `
-RuleName "AcctingUsersQueryRule"

Questions or comments? Use the comments section below.

Creating ConfigMgr Device Collections with PowerShell

Below for reference a quick PowerShell sample for creating a query-based device collection in System Center Configuration Manager (ConfigMgr), along with a demonstration of some of the options you can supply to control collection population and refresh behavior.

You can download the up-to-date ConfigMgr PowerShell cmdlets at https://www.microsoft.com/en-us/download/details.aspx?id=46681.

The ConfigMgr PowerShell cmdlet reference documentation is available at https://technet.microsoft.com/en-us/library/jj821831(v=sc.20).aspx.

Sample script for device collections

# Import ConfigMgr PowerShell module 
Import-Module (Join-Path $(Split-Path $env:SMS_ADMIN_UI_PATH) ConfigurationManager.psd1) 

# Change to ConfigMgr drive, where HOU is your site code
cd ‘c:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin’
Set-Location HOU:

# Create schedules for refreshing collection membership
$MonSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Monday -RecurCount 1
$TueSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Tuesday -RecurCount 1
$WedSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Wednesday -RecurCount 1
$ThuSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Thursday -RecurCount 1
$FriSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Friday -RecurCount 1
$SatSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Saturday -RecurCount 1
$SunSched = New-CMSchedule -Start "01/01/2017 10:00 PM" -DayOfWeek Sunday -RecurCount 1

# Define device collection we will create 
# If you want to enable incremental updating on the Collections, you can set the –RefreshType to 'Both'. 
New-CMDeviceCollection -Name "Pete Servers" -LimitingCollectionName "All Systems" `
-RefreshSchedule $MonSched -RefreshType Periodic

# Define query rule for my collection 
Add-CMDeviceCollectionQueryMembershipRule -CollectionName "Pete Servers" `
-QueryExpression "select * from SMS_R_System where SMS_R_System.SystemGroupName = 'CONTOSOCORP\\Pete Servers'" `
-RuleName "PeteServerQueryRule"

Questions or comments? Use the comments section below.

Inside System Center 3: Best Free System Center Solutions – Show Notes

In this episode, Dan and Pete talk about some of the more robust free solutions for System Center 2012 R2, including a couple of gems you have not seen before! Links to all the resources discussed (and some we didn’t get to) below!

New Show Updates

To get updates on the latest episodes of Inside System Center and Inside the Microsoft Cloud, follow on twitter (@insidemscloud@insidepodcast) or like us on Facebook at http://facebook.com/insidepodcastnetwork.

Episode Links

Audio editionavailable shortly!

Video edition – https://www.youtube.com/watch?v=tKfoJ-hBv0Y

OpsMgr 2012 R2

While there are thousands of great articles and scripts and related solutions for OpsMgr, here are a few of the more function-rich freebies. A couple of lesson known solutions in here! 

NiCE Log File Monitoring MP

https://www.nice.de/log-file-monitoring-scom-nice-logfile-mp

https://www.nice.de/wp-content/uploads/2015/01/NiCE_LogFileMP_SolutionBrief_2015Q1.pdf

MP Author (Silect Software)

http://www.silect.com/mp-author
OpsMgr Self Maintenance Management Pack (by Tao Yang)

http://blog.tyang.org/2013/03/03/opsmgr-self-maintenance-management-pack/

PKI Certificate Verification MP (by Raphael Burri)

https://rburri.wordpress.com/2015/06/22/pki-certificate-verification-mp-update-1-3-0-0/

Effective Configuration Viewer (Stefan Roth)

https://gallery.technet.microsoft.com/Get-effective-configuration-753e13bd

Adding GUI Authoring Support for PowerShell Monitors in OpsMgr (Wei H Lim)

https://gallery.technet.microsoft.com/Sample-Management-Pack-17b76379

ConFigMgr 2012 R2

While most everyone is familiar with the right click tools, we discussed a couple of other (and in some cases newer)  free solutions.

RegkeyToMof

http://myitforum.com/cs2/files/folders/proddocs/entry152945.aspx

RemoteManage

http://cireson.com/apps/remote-manage/

PowerShell Inventory Script (David O’Brien)

http://www.david-obrien.net/2014/01/update-inventory-script-makes-configmgr-life-easier/

Kent Agerland’s List of Community Tools

http://blog.coretech.dk/kea/community-tools-from-system-center-universe-2014/

Service Manager 2012 R2

Here are a few of our favorites for SCSM.

SCSM Dashboards (by Signature Consultancy)

http://www.signatureconsultancy.com/scsm-dashboard.html

SCSM Entity Explorer

https://gallery.technet.microsoft.com/SCSM-Entity-Explorer-68b86bd2

Free Community Stream (from Cireson Software)

DPM

SCOM DPM Dashboard

http://www.buchatech.com/2014/04/new-scom-dpm-dashboard-download

https://gallery.technet.microsoft.com/SCOM-DPM-Dashboard-8eef9b58

SCO / SMA / AA

Automating Software License Reclamation with System Center 2012 SCCM + Orchestrator

Part 1 – Software Metering Deep Dive and Automation Part 1: Use It Or Lose It – The Basics

This installment has a quick overview of the software metering feature in case you’re not familiar.

Part 2 – Software Metering Deep Dive and Automation Part 2: Use It Or Lose It – The Collections

This installment includes the collections of those systems using an application, and another collection with systems where the application is not being used.

Part 3 – Software Metering Deep Dive and Automation Part 3: Use It Or Lose It – The Orchestrator Runbook Automation

Sample Runbooks – Automation Use Cases

https://gallery.technet.microsoft.com/Sample-Runbooks-Automation-fafd8f13

http://blogs.technet.com/b/privatecloud/archive/2013/08/12/automation-orchestrator-back-to-basics-use-cases-spotlight-1-of-5.aspx

Orchestrator Sample Runbooks: Core Examples, PowerShell Examples, and Scenario E

https://gallery.technet.microsoft.com/Orchestrator-Sample-1bbb04a5

 

Simple Self-Service App Deployment with ConfigMgr, SCOrch and SCSM

At a recent meeting of the Houston Area Systems Management User Group, I presented a strategy for delivering effective self-service application deployment that would be achievable for System Center 2012 Configuration Manager (ConfigMgr) admins could potentially implement. By intention, the solution does not require custom management pack authoring, extending Service Manager (SCSM) classes or custom PowerShell. However, it is flexible and leverages the rich capabilities of SCSM for publishing a Service Catalog. This way, any ConfigMgr admin with basic Orchestrator (SCOrch) skills who can install a basic SCSM deployment (a Management Server, database and portal server) can configure ITIL friendly self-service with System Center 2012, complete with approval routing and documentation of the request in a proper service request.

By request, I am posting the sample runbooks here for the community members.

There is a variation of my approach HERE, but in this sample I have eliminated the need for custom PowerShell script, thereby further simplifying the solution.

NOTE: You do not have to replace your service desk solution to leverage System Center for self-service. The service requests created here can pretty easily be exported with a bit of PowerShell and imported into your target ITSM system of choice.

Solution Components

Components in the solution as demonstrated were:

  • ConfigMgr 2012 R2
  • SCSM 2012 R2
  • Orchestrator 2012 R2
  • Cireson Portal (optional) – This component is 100% optional, though it reduces the required server count by 1, eliminates the need for SharePoint and provides a self-service experience across mobile devices and is much more responsive than the native portal.

What I demonstrated used User Collections in ConfigMgr.  You could tweak the solution to use computer-based collections instead.

High-level Steps

The following are the high-level

  1. Configure deployments in SCCM
  2. Import runbook in SCO
  3. Connect SCSM to SCO and ConfigMgr
  4. Select the software to make available
  5. Configure the Offering in SCSM (For SCSM newbies, see “Automation and Self-Service with SCSM” on MVA)
  6. Publish to the Service Catalog

Sample Runbook #1

In this example, we used to retrieve the user and application (app) object. The app object is represented in the SCSM database by the Package class, which is populated by the ConfigMgr Connector in SCSM, which brings over the applications you have created in ConfigMgr When you look at the last two activities, you will notice that the runbook assumes that the ConfigMgr application (represented by the Package class in SCSM) and ConfigMgr collection have the same name.

I am not going to walk through the detailed configuration steps of either sample, as you can simply download both sample runbooks, import and see for yourself.

AppDeploy

Sample Runbook #2

I was asked if it would possible to extend the solution to allow use of existing packages. The short answer is yes, by simply adding a Map Published Data activity in which you can map the name of your application in ConfigMgr to the name of the collection to populate with the account of the user requesting the software.

AppDeploy_CustomColl
Here is a shot of the properties of the Map Published Data activity in the sample runbook.

Map_Published_Data

Download Runbook Samples

The runbook samples are available in a new GIT repository I setup to store community samples in a single, centralized repository. Both sample runbooks can be found at the URL below.

https://github.com/pzerger/CommunitySamples/tree/master/Runbooks/SCO