Trevor Sullivan's Tech Room

Minding the gap between administration and development

Archive for the ‘wmi’ Category

PowerShell: Move ConfigMgr Collections

Posted by Trevor Sullivan on 2012/01/12


Introduction

If you work with Microsoft System Center Configuration Manager (SCCM / ConfigMgr) 2007 in any capacity, you probably are familiar with the concept of "collections" and how painful they can be to work with sometimes. The ConfigMgr console does not provide any method of moving a collection from one parent to another, and the GUI is pretty slow to work with.

image

So what’s the solution here? PowerShell, of course!

PowerShell Code

Here is a PowerShell function that will allow you to move a ConfigMgr collection either by name or by collection ID.

Note: Select all of the function text top-to-bottom, and you can retrieve the text that is cut off towards the right.

<#
    .Synopsis
    This function allows you to re-assing the parent for a ConfigMgr collection to a new collection ID

    .Author
    Trevor Sullivan (pcgeek86@gmail.com)

    .Example
    c:\PS> Move-SccmCollection -SccmServer sccm01 -SiteCode LAB -CollectionID LAB00159 -ParentCollectionID LAB000150;

    Description
    -----------

    This command moves the ConfigMgr collection with ID "LAB000159" to being a child of collection ID "LAB000150".

    .Example
    c:\PS> Move-SccmCollection -SccmServer sccm01 -SiteCode LAB -CollectionName 'Visual Studio' -ParentCollectionID Microsoft;

    Description
    -----------

    This command moves the ConfigMgr collection named "Visual Studio" to being a child of the collection named "Microsoft". Note that you do not need to specify quotes around the parameter value if it does not contain spaces.

    .Notes
    This function is untested with collection links. It is not known whether or not this will remove existing collection links.
#>
function Move-SccmCollection {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)] [string] ${SccmServer}
        , [Parameter(Mandatory = $true)] [string] ${SiteCode}
        , [Parameter(ParameterSetName = "ByCollectionID", Mandatory = $true)] [string] ${CollectionID}
        , [Parameter(ParameterSetName = "ByCollectionID", Mandatory = $true)] [string] ${ParentCollectionID}
        , [Parameter(ParameterSetName = "ByCollectionName", Mandatory = $true)] [string] ${CollectionName}
        , [Parameter(ParameterSetName = "ByCollectionName", Mandatory = $true)] [string] ${ParentCollectionName}
    )

    # Set-PSDebug -Strict;

    # Ensure that ConfigMgr site server is available
    if (-not (Test-Connection -ComputerName $SccmServer -Count 1)) {
        return;
    }

    # Obtain references to collection and parent collection
    switch ($PSCmdlet.ParameterSetName) {
        # Use the "ByCollectionID" PowerShell parameter set to retrieve collection references by ID
        'ByCollectionID' {
            ${CollectionRelationship} = @(Get-WmiObject -ComputerName $SccmServer -Namespace root\sms\site_$SiteCode -Class SMS_CollectToSubCollect -Filter "subCollectionID = '$CollectionID'")[0];
            ${Collection} = @([wmi]("\\{0}\root\sms\site_{1}:SMS_Collection.CollectionID='{2}'" -f ${SccmServer}, ${SiteCode}, ${CollectionID}))[0];
            ${ParentCollection} = @([wmi]("\\{0}\root\sms\site_{1}:SMS_Collection.CollectionID='{2}'" -f ${SccmServer}, ${SiteCode}, ${ParentCollectionID}))[0];
        }
        # Use the "ByCollectionName" PowerShell parameter set to retrieve collection references by name
        'ByCollectionName' {
            ${Collection} = [wmi](@(Get-WmiObject -ComputerName $SccmServer -Namespace root\sms\site_$SiteCode -Class SMS_Collection -Filter ("Name = '{0}'" -f ${CollectionName}))[0].__PATH);
            ${ParentCollection} = [wmi](@(Get-WmiObject -ComputerName $SccmServer -Namespace root\sms\site_$SiteCode -Class SMS_Collection -Filter ("Name = '{0}'" -f ${ParentCollectionName}))[0].__PATH);
            ${CollectionRelationship} = @(Get-WmiObject -ComputerName $SccmServer -Namespace root\sms\site_$SiteCode -Class SMS_CollectToSubCollect -Filter ("subCollectionID = '{0}'" -f ${Collection}.CollectionID))[0];
        }
    } 
    
    # If references to both the child and [new] parent collection were obtained, then move on
    if (${Collection} -and ${ParentCollection}) {
        Write-Verbose -Message ('Setting parent collection for {0}:{1} to {2}:{3}' -f `
            ${Collection}.CollectionID `
            , ${Collection}.Name `
            , ${ParentCollection}.CollectionID `
            , ${ParentCollection}.Name);
        ${CollectionRelationship}.parentCollectionID = ${ParentCollection}.CollectionID;
        # Create the new collection relationship (this [oddly] spawns a NEW instance of SMS_CollectToSubCollect), so we have to clean up the original one
        ${CollectionRelationship}.Put();

        # Clean up all other collection relantionships for this collection
        ${OldCollectionRelationshipList} = @(Get-WmiObject -ComputerName $SccmServer -Namespace root\sms\site_$SiteCode -Class SMS_CollectToSubCollect -Filter ("subCollectionID = '{0}' and parentCollectionID <> '{1}'" -f ${Collection}.CollectionID, ${ParentCollection}.CollectionID));
        foreach (${OldCollectionRelationship} in ${OldCollectionRelationshipList}) {
            ${OldCollectionRelationship}.Delete();
        }
    }
    else {
        Write-Warning -Message 'Please ensure that you have entered a valid collection ID or name';
    }
}

 

Here is an example of how to use this function to move a collection based on their collection IDs:

Move-SccmCollection -SccmServer sccm01.mybiz.loc -SiteCode LAB -CollectionID LAB00011 -ParentCollectionID LAB00022;

Here is an example of how to use the function to move a collection based on the collection name:

Move-SccmCollection -SccmServer sccm01.mybiz.loc -SiteCode LAB -CollectionName ‘Visual Studio’ -ParentCollectionID Microsoft;

Posted in configmgr, powershell, scripting, tools, wmi | Tagged: , , , , , , , , , , , , , , , , | Leave a Comment »

PowerShell: PowerEvents Module Update to 0.3 Alpha

Posted by Trevor Sullivan on 2012/01/11


imageIf you haven’t already checked it out, I wrote and published a PowerShell module on CodePlex a little over a year ago. It’s called PowerEvents for Windows PowerShell, and allows you to easily work with permanent WMI (Windows Management Instrumentation) event subscriptions. Some folks may not be aware that I’ve also written comprehensive documentation on the theory behind WMI events and why they’re useful. This ~30-page PDF document is included in the PowerEvents download, and is useful even if you do not want to use the PowerEvents module.

As a bonus, the PowerEvents module was mentioned just recently in the PowerScripting Podcast (listen around 1h19m)!!

http://powerscripting.wordpress.com/2012/01/09/episode-171-listener-call-in/

Listen to my interview with the PowerScripting Podcast back in December 2010!

http://powerscripting.wordpress.com/2010/12/13/episode-134-trevor-sullivan-on-wmi-events-in-powershell/

PowerEvents Download Link: http://powerevents.codeplex.com/

Posted in powershell, scripting, tools, wmi | Tagged: , , , , , , , , | 1 Comment »

PowerShell: Report / Check the Size of ConfigMgr Task Sequences

Posted by Trevor Sullivan on 2012/01/10


Introduction

In Microsoft System Center Configuration Manager 2007 operating system deployment (OSD), there is a limitation of 4MB for task sequence XML data. This is discussed in a couple of locations:

The Technet document linked to above says the following:

Extremely large task sequences can exceed the 4-MB limit for the task sequence file size. If this limit is exceeded, an error is generated.

Solution: To check the task sequence file size, export the task sequence to a known location and check the size of the resulting .xml file.

Basically, the Technet troubleshooting article is suggesting that you would need to go into the ConfigMgr console, right-click a task sequence, export it to a XML file, and then pull up the file properties. That’s fine for one-off troubleshooting, but what if you had 1000 task sequences and needed to know how large all of them were? Read on to find out how!

Read the rest of this entry »

Posted in configmgr, powershell, scripting, wmi | Tagged: , , , , , , , , , , , , , , , , | 2 Comments »

ConfigMgr: Cleanup Software Updates Objects

Posted by Trevor Sullivan on 2011/11/29


Introduction

A common complaint I hear about Microsoft System Center Configuration Manager (SCCM / ConfigMgr) 2007 is the ability to clean up expired and superseded software updates from the objects related to software updates. As software updates are marked as expired or are superseded by newer software updates, Microsoft marks the old updates accordingly. Once an update has been retired, it is desirable for ConfigMgr administrators to remove the updates from deployments and reporting objects. This cleanup effort saves disk space for deployment packages, and can reduce unnecessary information from showing up in reports.

Read the rest of this entry »

Posted in configmgr, powershell, scripting, tools, wmi | Tagged: , , , , , , , , , , , , | Leave a Comment »

PowerShell: Disable ConfigMgr Task Sequence Countdown Notification

Posted by Trevor Sullivan on 2011/11/22


Introduction

If you are using Microsoft System Center Configuration Manager (SCCM / ConfigMgr) to deploy task sequences to ConfigMgr client systems, you may notice that by default, a countdown notification is shown as a balloon notification in the client’s system tray. In some cases, this functionality may be undesirable, and you may therefore wish to disable the balloon notification. Unfortunately, the task sequence properties GUI in the ConfigMgr console does not allow you to disable the notification, but you can do so via script.

The SMS_TaskSequencePackage class in the root\sms\site_lab (where “lab” is your three-digit ConfigMgr site code) WMI namespace represents each task sequence that has been created in a Configuration Manager hierarchy. The ProgramFlags property on this class contains a series of bitwise values (not sure if that’s the right term) which represent various options. In this case, we care about option 0x400 (1024 in base 10), which if enabled, disables the countdown timer.

image

PowerShell Code

The PowerShell code included below will allow you to specify a task sequence package ID that you would like to disable balloon notifications on. I suggest running the code inside of the PowerShell Integrated Scripting Editor (ISE).

Make sure you update your ConfigMgr server name (where the provider sits) and ConfigMgr site code before running it!

function Disable-ConfigMgrTaskSequenceNotification {
    param (
        [Parameter(Mandatory = $true)] $SccmServer
        , [Parameter(Mandatory = $true)] $SiteCode
        , [Parameter(Mandatory = $true)] $TaskSequenceID
    )
    
    try {
        # Retrieve the WMI instance that represents the intended task sequence package
        $TaskSequencePackage = [wmi]"\\$SccmServer\root\sms\site_$SiteCode`:SMS_TaskSequencePackage.PackageID='$TaskSequenceID'";
    }
    # If the WMI object does not exist, catch the error and deal with it ... somehow.
    catch [System.Management.Automation.RuntimeException] {
        Write-Host -Object ("A Windows Management Instrumentation error occurred.`n" + `
            "`n* Is the computer powered on?" + `
            "`n* Is a firewall blocking access to WMI?" + `
            "`n* Is the WMI service started on the remote system?");
    }
    
    # If the object handle was acquired from WMI, then go ahead and process it
    if ($TaskSequencePackage) {

        # Echo out the current ProgramFlags value
        Write-Verbose -Message ("Current program flags for {0} are {1}" `
                    -f $TaskSequencePackage.Name, $TaskSequencePackage.ProgramFlags);

        # If the notification disablement is not enabled (confusing, I know), then enable it.
        if (($TaskSequencePackage.ProgramFlags -band 0x400) -eq 0) {
            Write-Verbose -Message ("Disabling countdown for task sequence: {0}" -f $TaskSequencePackage.Name);
            
            # This is where the meat is: perform the binary XOR operation (same as adding 1024 in base 10) and set
            # the resulting value back to the ProgramFlags property. Remember that -bxor oscillates between on & off, so
            # that's why we have to perform the check in the if { ... } statement, prior to blindly switching it.
            $TaskSequencePackage.ProgramFlags = $TaskSequencePackage.ProgramFlags -bxor 0x400;
            
            # Commit the in-memory WMI instance back to the ConfigMgr provider
            $TaskSequencePackage.Put();
        }
    }
    # If a task sequence cannot be found with the appropriate ID, then notify the user.
    else {
        Write-Host `
            -Object ("Could not find task sequence with ID {0} in the {1} WMI namespace on {2}" `
            -f $TaskSequenceID, "root\sms\site_$SiteCode", $SccmServer)
    }
}

Clear-Host;
$SccmServer = 'sccm01.mydomain.com';
$SiteCode = 'LAB';
$TaskSequenceID = Read-Host -Prompt 'Please enter a task sequence ID to modify';

Disable-ConfigMgrTaskSequenceNotification `
    -SccmServer $SccmServer `
    -SiteCode $SiteCode `
    -TaskSequenceID $TaskSequenceID `
    -Verbose;

When you execute this script, you’ll be prompted for a task sequence ID, so make sure to have that handy.

image

Hope this helps!

Posted in configmgr, powershell, scripting, wmi | Tagged: , , , , , , , , , , , , , , | 1 Comment »

PowerShell / ConfigMgr: Count of Client Manufacturer / Models

Posted by Trevor Sullivan on 2011/11/09


Introduction

If you’re an administrator of Microsoft System Center Configuration Manager (SCCM / ConfigMgr) 2007, you might be interested in finding out what make / model of client & server systems you have, and how many of each unique value you have. Most people would probably simply pull up a ConfigMgr report, but did you know that there’s an automated way to get this information as well?

Using PowerShell

You’ll need the following to execute this simple script:

  • A user account with access to the ConfigMgr provider
  • The hostname of the ConfigMgr central site server
  • The site code of the ConfigMgr central site

Once you’ve launched PowerShell under the appropriate account’s credentials, simply run this command:

Clear-Host

$ComputerSystems = Get-WmiObject `
    -Namespace root\sms\site_000 `
    -ComputerName sccm01.mydomain.com `
    -Class SMS_G_System_Computer_System

$ComputerSystems `
    | Group-Object -Property Manufacturer,Model `
    | Where-Object { $_.Count -gt 5 } `
    | Sort-Object -Property Count -Descending

If you get an error saying "An empty pipe element is not allowed" then make sure that there is not a space after one of the backticks. The backtick is the continuation character, and tells PowerShell to keep processing the command on the next line, and if there is a space after it, the interpreter will get confused.

If everything works as expected, you should see output similar to the following:

Count Name                    
—– —-                    
  222 Dell Inc., OptiPlex 780 
  136 Dell Inc., OptiPlex GX620

  135 Dell Inc., OptiPlex 755 
  134 Dell Inc., OptiPlex 745 
  101 Dell Inc., OptiPlex GX280

There will also be a “group” property, which contains the actual .NET objects that were grouped into each line item.

Hope this helps!

Posted in configmgr, powershell, scripting, tools, wmi | Tagged: , , , , , , , , , , , , | Leave a Comment »

PowerShell: Update your ConfigMgr OSD Boot Images to WinPE 3.1

Posted by Trevor Sullivan on 2011/10/21


When you upgrade your boot images in Microsoft’s System Center Configuration Manager (SCCM / ConfigMgr) 2007 from WinPE 3.0 to WinPE 3.1, you must run the ExportDefaultBootImage() WMI method on the SMS_BootImagePackage WMI class for each boot image architecture. Typically this would simply include x86 (32-bit) and x64 (64-bit) boot images (Windows Image Format (WIM) files).

There are a few different methods of running this WMI method:

  • Manually through wbemtest
  • Using the VBscript scripting language
  • A PowerShell script

Since the first two methods have been covered already by other people, I will show an example of using Windows PowerShell to call the method. Simply replace the SCCMServer and SiteCode variables with the appropriate values, and WIM paths with your own, and run the script.

Clear-Host
$SccmServer = 'MySccmServer'
$SiteCode = '123'
$BootImageClass = [wmiclass]"\\$SccmServer\root\sms\site_$SiteCode`:SMS_BootImagePackage"

$WimFiles = @{
    'x86' = '\\$SccmServer\SMS_$SiteCode\OSD\boot\i386\winpe.x86.3.1.wim' 
    'x64' = '\\$SccmServer\SMS_$SiteCode\OSD\boot\x64\winpe.x64.3.1.wim'
}

$BootImageClass.ExportDefaultBootImage('x64' , 1, $WimFiles.x64)
$BootImageClass.ExportDefaultBootImage('x86' , 1, $WimFiles.x86)

Posted in configmgr, OSD, powershell, scripting, wmi | Tagged: , , , , , , , , , | Leave a Comment »

ConfigMgr 2012 Beta 2: WMI Namespace Documentation

Posted by Trevor Sullivan on 2011/08/02


I recently put together some documentation for the Microsoft System Center Configuration Manager 2012 Beta 2 WMI provider. This is a searchable, formatted Excel document that displays all the classes, properties, and methods for the SCCM 2012 provider. Hopefully this will help you to find the proper information for writing custom scripts and so on.

http://dl.dropbox.com/u/18088468/SCCM%202012%20WMI%20Namespace%20Documentation.xlsx

Please provide feedback if this was helpful, or if you’d like to see something else added to it!

Posted in configmgr, ConfigMgr vNext, tools, wmi | Tagged: , , , , , , , , , , | Leave a Comment »

PowerShell / ConfigMgr: Sendsched.vbs Replacement

Posted by Trevor Sullivan on 2011/07/25


Recently, someone posted a PowerShell script, which is intended as a replacement for the SendSched.vbs included in the Microsoft System Center Configuration Manager 2007 Toolkit v2.

I took the liberty of cleaning the code up a little bit, and simplifying it to be more PowerShell friendly. Enjoy.

#            
# Script Name: SendSched_PowerShell_Version.ps1
# Purpose: Serves as a replacement for the sendsched.vbs script included in the Microsoft System Center
#            Configuration Manager 2007 toolkit -- asynchronously invokes SCCM client tasks
#            
# Created By Kaido Jarvemets Http://Depsharee.blogspot.com            
# Configuration Manager MVP            
# 25.07.2011

# Updated by: Trevor Sullivan
#      Email: pcgeek86@gmail.com
#         Blog: http://trevorsullivan.net
#        Date: 2011-07-25
#
# Changelog:
#        * Replaced Get-ScheduleID function with a hashtable
#        * Removed custom ping function in favor of using Test-Connection
#        * Replaced default computer name with a period, which represents localhost
            
function Invoke-SCCMSchedule            
{            
    [CmdletBinding()]            
    Param(            
        [String]$ComputerName = ".",
        [Parameter(Mandatory = $true)]            
        [string]$ScheduleID
        
    )            
               
    $ScheduleIds = @{
        HardwareInventory    = "{00000000-0000-0000-0000-000000000001}"; # Hardware Inventory Collection Task             
        SoftwareInventory    = "{00000000-0000-0000-0000-000000000002}"; # Software Inventory Collection Task             
        HeartbeatDiscovery    = "{00000000-0000-0000-0000-000000000003}"; # Heartbeat Discovery Cycle             
        SoftwareInventoryFileCollection    = "{00000000-0000-0000-0000-000000000010}"; # Software Inventory File Collection Task             
        RequestMachinePolicy    = "{00000000-0000-0000-0000-000000000021}"; # Request Machine Policy Assignments             
        EvaluateMachinePolicy    = "{00000000-0000-0000-0000-000000000022}"; # Evaluate Machine Policy Assignments             
        RefreshDefaultMp    = "{00000000-0000-0000-0000-000000000023}"; # Refresh Default MP Task             
        RefreshLocationServices    = "{00000000-0000-0000-0000-000000000024}"; # Refresh Location Services Task             
        LocationServicesCleanup    = "{00000000-0000-0000-0000-000000000025}"; # Location Services Cleanup Task             
        SoftwareMeteringReport    = "{00000000-0000-0000-0000-000000000031}"; # Software Metering Report Cycle             
        SourceUpdate            = "{00000000-0000-0000-0000-000000000032}"; # Source Update Manage Update Cycle             
        PolicyAgentCleanup        = "{00000000-0000-0000-0000-000000000040}"; # Policy Agent Cleanup Cycle             
        RequestMachinePolicy2    = "{00000000-0000-0000-0000-000000000042}"; # Request Machine Policy Assignments             
        CertificateMaintenance    = "{00000000-0000-0000-0000-000000000051}"; # Certificate Maintenance Cycle             
        PeerDistributionPointStatus    = "{00000000-0000-0000-0000-000000000061}"; # Peer Distribution Point Status Task             
        PeerDistributionPointProvisioning    = "{00000000-0000-0000-0000-000000000062}"; # Peer Distribution Point Provisioning Status Task             
        ComplianceIntervalEnforcement    = "{00000000-0000-0000-0000-000000000071}"; # Compliance Interval Enforcement             
        SoftwareUpdatesAgentAssignmentEvaluation    = "{00000000-0000-0000-0000-000000000108}"; # Software Updates Agent Assignment Evaluation Cycle             
        UploadStateMessage    = "{00000000-0000-0000-0000-000000000111}"; # Send Unsent State Messages             
        StateMessageManager    = "{00000000-0000-0000-0000-000000000112}"; # State Message Manager Task             
        SoftwareUpdatesScan    = "{00000000-0000-0000-0000-000000000113}"; # Force Update Scan            
        AMTProvisionCycle    = "{00000000-0000-0000-0000-000000000120}"; # AMT Provision Cycle            
    }
    
    if(Test-Connection -Computer $ComputerName) {
        Try {
            $SmsClient = [wmiclass]"\\$ComputerName\root\ccm`:SMS_Client"
            $SmsClient.TriggerSchedule($ScheduleIds.$ScheduleID)
          }            
        Catch {
            Write-Host "Trigger Schedule Method failed" -ForegroundColor RED            
        }            
    }            
    else {
        Write-Host "Computer may be offline or please check Windows Firewall settings" -ForegroundColor Red
    }
             
}# End of Function Invoke-SCCMSchedule

Posted in configmgr, powershell, scripting, tools, wmi | Tagged: , , , , , , , , , | Leave a Comment »

PowerShell / ConfigMgr 2012: Check Client Reboot Pending State

Posted by Trevor Sullivan on 2011/07/25


Introduction

If you’ve worked with Configuration Manager 2007 for very long, you probably know that clients pending reboots can cause you quite a headache. Determining whether or not a client needs a reboot can be a challenging task, and most folks used desired configuration management rules to detect it.

Well, I’m happy to announce that there’s a new method of figuring out whether or not a SCCM client requires a reboot! There’s a new WMI namespace called root\ccm\ClientSDK, and within it is a WMI class called CCM_ClientUtilities, which has a static method called DetermineIfRebootPending() – the method does not take any input parameters, however it spits out several [out] parameters when it is called.

Read the rest of this entry »

Posted in configmgr, ConfigMgr vNext, powershell, scripting, wmi | Tagged: , , , , , , , , , , , | Leave a Comment »