Code from my Session at the Northwest System Center User Group

Big thanks to the Northwest System Center User Group for hosting me at their March meeting. We had a great demo session to show how to use PowerShell with ConfigMgr.

To enable ease of search, I’m posting the PowerShell code into this post. If you want all the code, you can download here.

Demo 1 – Samples of using PowerShell to quickly pull info from ConfigMgr, and to see the ‘guts’ behind a ConfigMgr cmdlet (see the WMI that is being called):

#http://www.gregramsey.net
#Test, test, test  - test everything you - safety First!
#general overview of using Powershell with configMgr - examples of show-command, debug, etc.

#region Import CM Module
$CMModulePath = `
    $Env:SMS_ADMIN_UI_PATH.ToString().SubString(0,$Env:SMS_ADMIN_UI_PATH.Length - 5) `
    + "\ConfigurationManager.psd1" 
Import-Module $CMModulePath -force
cd GMR:
#endregion

#get CM cmdlets
get-command -Module ConfigurationManager | Out-GridView

#show commands for set-cmapplication
show-command Set-CMApplication

#Show Devices
Get-CMDevice | Out-GridView

#List all members
Get-CMDevice | Get-Member

#select Specific Objects
Get-CMDevice | Select-Object Name, SiteCode, ADSiteName, DeviceOS, 
    Domain, IsActive, LastActiveTime, LastClientCheckTime, LastDDR, 
    LastHardwareScan, LastMPName, LastPolicyReqeust | Out-GridView
#Group-By
Get-CMDevice | Select-Object Name, SiteCode, ADSiteName, DeviceOS, 
    Domain, IsActive, LastActiveTime, LastClientCheckTime, LastDDR, 
    LastHardwareScan, LastMPName, LastPolicyReqeust | Group-Object DeviceOS | Out-GridView

#Show Debug
Get-CMDevice -Debug | Out-GridView

#grab wmi query and run it.

Demo 2 – Samples of manipulating collecftions, handling lazy properties, etc.

#http://www.gregramsey.net
#Samples of manipulating collecftions, handling lazy properties, etc.


#region Import CM Module
$CMModulePath = `
    $Env:SMS_ADMIN_UI_PATH.ToString().SubString(0,$Env:SMS_ADMIN_UI_PATH.Length - 5) `
    + "\ConfigurationManager.psd1" 
Import-Module $CMModulePath -force
cd GMR:
#endregion

#quick display of Client info for a collection
get-cmdevice -CollectionName "Test Coll" | select Name, ADLastLogonTime, ADSiteName, `
    ClientVersion, DeviceOwner,Domain,LastActiveTime,LastHardwareScan, LastMPServerName, `
    SiteCode | Out-GridView

#write to .csv
get-cmdevice -CollectionName "Test Coll" | select Name, ADLastLogonTime, ADSiteName, `
    ClientVersion, DeviceOwner,Domain,LastActiveTime,LastHardwareScan, LastMPServerName, `
    SiteCode | export-csv c:\logs\ClientInfo.csv -NoTypeInformation
notepad c:\logs\ClientInfo.csv

#View Collection info
get-cmdevicecollection -name "Test Coll"

#look at schedule
show-command New-CMSchedule

#create a collection, with schedule
$Sched = New-CMSchedule -DayOfWeek Saturday
$MyColl = New-CMDeviceCollection -Name "Test Coll2" -LimitingCollectionName `
    "All Desktop and Server Clients" -RefreshSchedule $Sched -RefreshType Periodic

#Add rule to exclude my "All DCs Collection"
Add-CMDeviceCollectionExcludeMembershipRule -CollectionName "Test Coll2" `
    -ExcludeCollectionName "All DCs"

#now, update the schedule (dipping into wmi) - #Chris Mosby Special 🙂
$Sched = New-CMSchedule -RecurCount 7 -RecurInterval Days -Start ([datetime] "2/27/2015 02:00")
$Coll = Get-WmiObject -Class SMS_Collection -Namespace "Root\SMS\Site_gmr" `
    -Filter "Name='Test Coll2'"
$Coll.RefreshType = 6  #1=manual, 2=periodic, 4=constant, 6=periodic+constant
$Coll.RefreshSchedule = $Sched.psbase.ManagedObject
$Coll.Put()

#look at the schedule with gwmi
$Coll = Get-WmiObject -Class SMS_Collection -Namespace "Root\SMS\Site_gmr" `
    -Filter "Name='Test Coll2'"
$Coll.refreshschedule    # (Refreshschedule is blank...)

#you see refreshschedule info here:
$coll = Get-CMDeviceCollection -name "Test Coll2"
$coll.RefreshSchedule

#why is refreshschedule missing when get-wmiobject?

#need to handle lazy property..... (check sms_collection Class for lazy props)
$Coll = Get-WmiObject -Class SMS_Collection -Namespace "Root\SMS\Site_gmr" `
    -Filter "Name='Test Coll2'"
$coll.__path
$coll2 = [wmi]$coll.__path  #get specific instance using the [wmi] and __Path 
$coll2.RefreshSchedule

#Create new Maintenance Window
#Create new MW Schedule - every Saturday at 2:00AM for 3 Hours
$mwSched = New-CMSchedule -DayOfWeek Saturday -Start ([datetime]"2:00 am") `
    -End ([datetime]"2:00 am").addhours(3) 
$CollID = (Get-CMDeviceCollection -name "Test Coll2").CollectionID
New-CMMaintenanceWindow -CollectionID $CollID -ApplyToSoftwareUpdateOnly `
    -Name "Test Coll2 MW" -Schedule $mwsched

#show existing mw
Get-CMMaintenanceWindow -CollectionID $CollID

#Add Direct Membership Rule
Add-CMDeviceCollectionDirectMembershipRule -CollectionName $Coll2.Name `
    -ResourceId (get-CMDevice -name CM2012R2).ResourceID

#Add Multiple Direct Membership Rules
notepad c:\logs\systems.txt
get-content c:\logs\systems.txt | foreach-object {
    Add-CMDeviceCollectionDirectMembershipRule -CollectionName $Coll2.Name `
        -ResourceId (get-CMDevice -name $PSItem).ResourceID
}

#Create Query Rule
$WQLQuery = `
    "select * from sms_r_system Where OperatingSystemNameAndVersion like '%Workstation%'"
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $Coll.Name `
    -RuleName "All Workstations" -QueryExpression $WQLQuery


#perform surgery - remove one rule
Remove-CMDeviceCollectionDirectMembershipRule -CollectionName "Test Coll2" `
    -ResourceName "W81x64"  #use -force toskip confirmation

#Remove all direct membership rules
$CollectionName = "Test Coll2"
$coll = Get-CMDeviceCollection -name $CollectionName 
$coll.CollectionRules | where-object {$PSItem.ObjectClass -eq "SMS_CollectionRuleDirect"} |
    foreach-object { 
        Remove-CMDeviceCollectionDirectMembershipRule -collectionname $CollectionName `
        -resourceID $_.ResourceID -force
    }

#Update Collection membership now
Invoke-CMDeviceCollectionUpdate -Name "Test Coll2"

#Remove Collection use -force to not get prompted
Remove-CMDeviceCollection -name "Test Coll2" -force

Demo 3 – examples of manipulating packages, programs, programflags, etc.

#http://www.gregramsey.net
#examples of manipulating packages, programs, programflags, etc.


#region Import CM Module
$CMModulePath = `
    $Env:SMS_ADMIN_UI_PATH.ToString().SubString(0,$Env:SMS_ADMIN_UI_PATH.Length - 5) `
    + "\ConfigurationManager.psd1" 
Import-Module $CMModulePath -force
cd GMR:
#endregion

Get-CMPackage | select Manufacturer, Name, PackageID, LastRefreshTime, PkgSourcePath | Out-GridView
Get-CMPackage | export-csv c:\logs\Allpackages.csv -NoTypeInformation


#Explore Program
$Program = Get-CMProgram -ProgramName "Cumulative update 1 - console update install" `
    -PackageId "GMR00006"
#Look at ProgramFlags
$Program
$Program.ProgramFlags  # should be 135307264
$oldPFlag = $Program.ProgramFlags
$oldbinary = [Convert]::ToString($Program.ProgramFlags, 2)
$oldbinary

#now manually change it in the gui - 'allow this program to install...'
$Program = Get-CMProgram -ProgramName "Cumulative update 1 - console update install" `
    -PackageId "GMR00006"
$Program.ProgramFlags  # should be 135307265
$binary = [Convert]::ToString($Program.ProgramFlags, 2)
$binary
$oldbinary

# List all Programs with this enabled:
# "Allow this program to be installed from the Install 
#  Package task sequence action without being deployed."
Get-CMProgram | foreach {
    if ($_.ProgramFlags -band 0x1) {
    "{0} {1} {2}" -f $_.ProgramName, $_.PackageID, "Enabled"
    }
}

#Enable this setting on all Programs
Get-CMProgram | foreach {
    if  ($_.ProgramFlags -band 0x1) {
        #Already Enabled
    }
    else {
        #currently disabled, enable now
        "{0} {1} {2}" -f $_.ProgramName, $_.PackageID, "Enabling"
        $_.ProgramFlags = $_.ProgramFlags -bxor 0x1
        $_.Put()
    }
}

#Disable this setting on all Programs
Get-CMProgram | foreach {
    if  ($_.ProgramFlags -band 0x1) {
        #currently enabled, disable now
        "{0} {1} {2}" -f $_.ProgramName, $_.PackageID, "Disabling"
        $_.ProgramFlags = $_.ProgramFlags -bxor 0x1
        $_.Put()
    }
    else {
        #Already Disabled
    }
}


#List all disabled programs   
Get-CMProgram | foreach {
    if  ($_.ProgramFlags -band 0x1000) {
        #disabled
        "{0} {1} {2}" -f $_.ProgramName, $_.PackageID, "Disabled"
    }
    else {
        #enabled
    }
}

#Update Supported OperatingSystems - Need to step into WMI
$prg = gwmi sms_program -namespace root\sms\site_gmr `
    -filter "ProgramName='Fake Program' and PackageID='GMR00017'"
$prg = [wmi]$prg.__PATH
$prg.SupportedOperatingSystems

#look at example supported OS (to make sure correct min/max version
$pkgID = (Get-CMPackage -name "MDT Settings").PackageID
$prg = Get-CMProgram -ProgramName "fp2" -PackageId $pkgID
$prg.SupportedOperatingSystems

#use WMI to grab the program
$prg = gwmi sms_program -namespace root\sms\site_gmr -filter "ProgramName='Fake Program' and PackageID='GMR00017'"
#neet to getinstance to pull the lazy properties
$prg = [wmi]$prg.__PATH
$prg.SupportedOperatingSystems

#create a new instance of SMS_OS_Details, so we can add it to Supported OS (Win8.1 x64)
$OS = ([wmiclass]"\\CM2012R2.GMR.net\root\sms\site_GMR:SMS_OS_Details").Createinstance()
$OS.MaxVersion = "6.30.9999.9999"
$OS.MinVersion = "6.30.0000.0"
$OS.Name = "Win NT"
$OS.Platform = "x64"
$OS

$prg.SupportedOperatingSystems = $prg.SupportedOperatingSystems + $OS
$prg.Put()

#List all packages configured to "Copy the content in this package 
# to a package share on distribution points"
#PackageFlag = 0x80
Get-CMPackage | foreach {
   if  ($_.PkgFlags -band 0x80) {
        #Enabled
        $_.Packageid + " - " + $_.Name

    }
    else {
        #disabled
    }

}

Demo 4 – add 8.1 support to all package/programs that currently have support for 8.0.

#http://www.gregramsey.net
#add 8.1 support to all package/programs that currently have support for 8.0.

#create a new instance of SMS_OS_Details, so we can add it to Supported OS (Win8.1 x64)
$OS = ([wmiclass]"\\CM2012R2.GMR.net\root\sms\site_GMR:SMS_OS_Details").Createinstance()
$OS.MaxVersion = "6.30.9999.9999"
$OS.MinVersion = "6.30.0000.0"
$OS.Name = "Win NT"
$OS.Platform = "x64"

Get-WmiObject sms_program -Namespace root\sms\site_gmr | foreach-object {
    $prg = [wmi]$PSItem.__Path
    #supported platform is set, and Win8x64 is supported platform
    if (($prg.ProgramFlags -band 0x8000000) -eq 0 -and `
        ($prg.SupportedOperatingSystems.minversion -contains "6.20.0000.0") ) { 
            #check if Win81x64 is a supported platform
            if ($prg.SupportedOperatingSystems.minversion -notcontains "6.30.0000.0") {
                #no. .so add it
                "Updating {0}" -f $prg.programname
                $prg.SupportedOperatingSystems = $prg.SupportedOperatingSystems + $OS
                $prg.Put()
            }
        }
    #}
}

Happy Scripting!

Greg

ramseyg@hotmail.com

This post first appeared on http://www.gregramsey.net

Action-Packed CTSMUG meeting on February 5th – Registration is Open!

We have a great meeting planned for February 5th – register now!

Here are 3 days of System Center that you need to attend:

February 4thSystem Center Universe – You can register in person for attending in Dallas, or join us at the Microsoft office (in the arboretum) for the simulcast. We will have two rooms (one for each simulcast stream). Join us for lots of discussion, food, and swag. Take a look at the agenda. http://systemcenteruniverse.com/agenda.htm

February 5thCTSMUG February meeting, it will also be at the Microsoft office, and sponsored by SoftwareOne. (See our agenda below)

February 6thSAASMUG – Road Trip to San Antonio!  Featuring Wally Mead and Kent Agerlund!

Here’s our February 5th Agenda (we will be at Microsoft Austin Office):

10:00 – Understand the Enterprise mobility challenges today or get left behind – Kent Agerlund
11:15 – Service Management Automation – The path to the future Charles Joy
12:30 – Lunch – Sponsored by Software One
1:30 – OSD Tips and Tricks – Bill Moore
2:30 – Moderated Discussion – Donnie or Warren

Understand the Enterprise mobility challenges today or get left behind – According to a recent Gartner study more than 20% of all Enterprises will fail the attempt to implement a BYOD/CYOD solution. In this session we will cover how you can address the Enterprise Mobility challenges using System Center Configuration Manager and Microsoft Enterprise Mobility Suite. You learn about the new mobile device management features and how to manage Windows/iOS and Android devices via both System Center Configuration Manager and Microsoft Intune. You will learn how to setup the infrastructure needed, the new features, how to work with identity management, corporate data, and how to enroll and manage devices.

OSD Tips and Tricks – I/T professionals spend substantial time automating processes so that they have time to direct their attention to more important things. There are some processes however that will always be time consuming, like system imaging for example. In this session we will discuss an often overlooked Configuration Manager feature, prestaged media. Used not for OEM media, but as part of the daily support function. You will learn how to create and deploy multi-wim task sequences and standalone media, create generic PowerShell forms for managing OS deployment in a multi-wim configuration, and configure your images for rapid deployment. We will also discuss tips and tricks for using standalone media as a single mechanism to fine tuning your operating system deployment scripts.

Service Management Automation – The Path to the Future – Charles will discuss System Center Orchestrator, but focus on moving toward SMA, and give examples of how SMA should be used. SMA is a pretty new topic/app to most of us, and we all know we need to dive into it a bit further. This first session with Charles will help you understand better for where SMA will fit in your environment, and will demonstrate several scenarios and runbooks.

Book Exchange! – We introduced the concept at our December meeting. Do you have some old tech books that you no longer need, that may benefit someone else? Bring them to our next meeting, to give others the opportunity to take your old books (for free), and maybe you’ll find one in the pile that will help you too! (Please, if no one takes your book, take it home with you. Also, let’s keep it to tech–no romance novels please. .)

 

Greg