Install User-targeted Applications during OS Deployment via PowerShell and ConfigMgr 2012

Let’s start my first post of this great new year with another nice PowerShell script. This post will be about deploying required user targeted applications, to the device of the primary user, during OS deployment. Yes, I know the setting of Pre-deploy software to the user’s primary device, but that doesn’t give enough control. After deployment, the device has to be completely ready for use.

A bit more than a year ago I already did a post about pre-provisioning user applications during OS deployment via Orchestrator and ConfigMgr 2012. This time I wanted to make less assumptions. I also wanted to be sure that a user is a member of a collection and what the application is that is deployed to the collection. I first tried to achieve this goal by adjusting my runbook in Orchestrator and I made it work (and it still works), but to make it work I had to use all custom PowerShell activities. This made me think why I still wanted this and I couldn’t come up with something better than “because I can”. So I decided to make one PowerShell script to find the applications and to create the task sequence variables.


The main part of this script is gathering data and filtering it. In short I could say this script consists of five queries and an action. The following six steps make sure that I only get the applications, that are required for the primary user of the device, to be installed during the OS deployment.

Step 1 – Get the Primary User

The first step is to get the primary user of the device that’s being deployed. That information can be retrieved in WMI in the class SMS_UserMachineRelationship. This class shows the relationship of a user with a device, even when it’s only a suggestion yet. The properties of Sources and Types can be used to see how the primary user is defined and to see if it’s a suggestion or a “real” affinity. I know that, in my case, all the device affinities are administrator defined. So to get the user name of the primary user of a device I use the following code snippet (format is <Domain>\<User>:

$PrimaryUser = (Get-WmiObject -ComputerName $SiteServer ` -Class SMS_UserMachineRelationship ` -Namespace root\SMS\Site_$SiteCode ` -Filter "ResourceName='$ResourceName'").UniqueUserName

Step 2 – Get the Container Node

The second step is to get the container node of the application deployment collections. This will be used to make sure that only collections used for application deployments will be queried. This information can be retrieved in WMI in the class SMS_ObjectContainerNode. This class shows the different folders in the console and its location. The property ObjectTypeName can be used to see the type of objects in the folder. In my case, I occasionally use identical folder names. So to get the container node information that I need, I use the following code snippet:

$ContainerNodeId = (Get-WmiObject -ComputerName $SiteServer ` -Class SMS_ObjectContainerNode ` -Namespace root/SMS/site_$SiteCode ` -Filter "Name='$Container' and ` ObjectTypeName='SMS_Collection_User'").ContainerNodeId

Step 3 – Get the Collections

The third step is to get the collections within the container. This information can be retrieved in WMI in the class SMS_ObjectContainerItem. This class shows the relation between an container and the objects within an container. So to get the collections within the container I use the following code snippet:

$InstanceKeys = (Get-WmiObject -ComputerName $SiteServer ` -Class SMS_ObjectContainerItem ` -Namespace root/SMS/site_$SiteCode ` -Filter "ContainerNodeID='$ContainerNodeId'").InstanceKey

Step 4 – Filter the Collections

The fourth step is to filter the collections on a specific collection member. This will make sure that only collections used for application deployments AND with the specific collection member will be queried later on.  This information can be found in WMI in the class SMS_FullCollectionMembership. This class shows the different collection members and their memberships. The best thing, the property SMSID shows the collection member in exactly exactly the same format as I have the primary user of the device. So to filter the collections I use the following code snippet:

$CollectionId = (Get-WmiObject -ComputerName $SiteServer ` -Class SMS_FullCollectionMembership ` -Namespace root/SMS/site_$SiteCode ` | Where-Object {$_.CollectionID -eq $InstanceKey -and ` $_.SMSID -eq $PrimaryUser}).CollectionId

Note: For an unknown reason, to me, a normal filter did not work together with the property SMSID. That’s why I had to use an where-object statement.

Step 5 – Get the targeted Applications

The fifth step is to get the applications that are targeted to the filtered collection. This makes sure that only applications deployed to collections, of which the primary user of the device is a member, will be filtered. This information can be found in WMI in the class SMS_ApplicationAssignment. The property OfferTypeID can be used to see if the deployment is required or available. I only want to have the required applications. So this makes that I use the following code snippet:

$ApplicationNames = (Get-WmiObject -ComputerName $SiteServer ` -Class SMS_ApplicationAssignment ` -Namespace root/SMS/site_$SiteCode ` -Filter "TargetCollectionID='$CollectionId' and ` OfferTypeID='0'").ApplicationName

Step 6 – Create the Task Sequence Variables

The sixth, and last step, is to create task sequence variables for the applications that have to be installed during the OS deployment. For every application I create a task sequence variable named APPIdXX with the value of the application. To achieve this I use the following code snippet:

foreach ($ApplicationName in $ApplicationNames) { $Id = "{0:D2}" -f $Count $AppId = "APPId$Id" $TSEnv.Value($AppId) = $ApplicationName $Count = $Count + 1 }

Note: In the complete script I already created a variable $Count with the value 0 and an object named $TSEnv of Microsoft.SMS.TSEnvironment.

>> The complete script is available via download here on the TechNet Galleries! <<


Now download the PowerShell script via the link above and add the PowerShell script to an old-school Package, so it will be available for a task sequence. Then create a standard Install an existing image package task sequence. Now edit the task sequence and make sure the following steps are included:

  • imageAdd a step Run PowerShell Script with the following settings:
    • Package: <NameOfPackageThatContainsTheScript>
    • Script name: <NameOfTheScript>
    • Parameters: %_SMSTSMachineName%
      • Note: The script needs more input parameters, but I usually add those parameters directly in the script as they are “static” per environment.
    • PowerShell execution policy: Bypass
  • Add a step Install Application with the following settings:
    • Select Install applications according to dynamic variable list
    • Base variable name: APPId

Note: The computer account running the script needs read access to ConfigMgr. So in most cases this would mean that the Domain Computers need read access to ConfigMgr. This can be achieved via the build-in role of Read-only Analyst.

72 thoughts on “Install User-targeted Applications during OS Deployment via PowerShell and ConfigMgr 2012”

  1. Thanks for this script, it was a great starting point for us. I re-wrote some portions of it for our use.

    1) added support for multiple primary users
    2) iterates through all containers, not just one named node
    3) fixed the wmi filtering problem, so it runs MUCH faster now. the \ in the username needs to be escaped to \\ before handing it to the wmi filter.

    Enjoy, I hope someone else finds it useful. It’s not the prettiest code ever, but it works nicely.

    One other note about this script is that we had to patch our sccm servers with a hotfix from CU4 to get the “install applications according to dynamic variable list” feature working. more info here:


    param (

    function Get-TargetedApplications {
    $Count = 1
    #get-date | out-file c:\applicationlist.txt
    $TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment
    $PrimaryUsers = Get-WmiObject -ComputerName $SiteServer -Class SMS_UserMachineRelationship -Namespace root\SMS\Site_$SiteCode -Filter “ResourceName=’$ResourceName’ and IsActive=’1′ and types=’1′”
    foreach ($PrimaryUser in $PrimaryUsers){
    #”primary user:” + $primaryuser.UniqueUserName | out-file c:\applicationlist.txt -append
    if ($PrimaryUser -ne $null) {
    $ContainerNodes = Get-WmiObject -ComputerName $SiteServer -Class SMS_ObjectContainerNode -Namespace root/SMS/site_$SiteCode -Filter “ObjectTypeName=’SMS_Collection_User'”
    foreach ($containernode in $ContainerNodes) {
    $InstanceKeys = Get-WmiObject -ComputerName $SiteServer -Class SMS_ObjectContainerItem -Namespace root/SMS/site_$SiteCode -Filter “ContainerNodeID=’$ContainerNodeId'”
    foreach ($InstanceKey in $InstanceKeys){
    $collectionId = Get-WmiObject -ComputerName $SiteServer -Class SMS_FullCollectionMembership -Namespace root/SMS/site_$SiteCode -Filter “CollectionID=’$ik’ and smsid=’$un'”
    if ($CollectionId -ne $null) {
    $ApplicationNames = (Get-WmiObject -ComputerName $SiteServer -Class SMS_ApplicationAssignment -Namespace root/SMS/site_$SiteCode -Filter “TargetCollectionID=’$Ci’ and OfferTypeID=’0′”)
    if ($ApplicationNames -ne $null) {
    foreach ($ApplicationName in $ApplicationNames) {
    $Id = “{0:D2}” -f $Count
    $AppId = “APPID$Id”
    $TSEnv.Value($AppId) = $ApplicationName.ApplicationName
    #$ApplicationName.ApplicationName | out-file c:\applicationlist.txt -append
    $Count = $Count + 1


  2. I am getting an 0x80004005 error message on the Install Package step. Anyone know what this could be?

  3. I’ve downloaded your Script from the MS TechNet (Updated 6/11/2014) . There is a Bug in this Version. It didn’t set the $TSEnv.Value
    After changing the Line 26 from $TSEnv.Value($AppId) =$ApplicationName.ApplicationName
    to $TSEnv.Value($AppId) =$ApplicationName it works very well

    Thank you for this great Script!

  4. I am getting an 0×80004005 error message when trying to install applications according to dynamic variable list. Anyone know what this could be? I don´t have to do anything whith the collections right?
    I think, that it selects the apps properly in the first step.

  5. Hi Peter,

    I’m getting the following error when running the script.
    I’m not so good in scripting, so can you help me out.

    Get-WmiObject : Cannot validate argument on parameter ‘ComputerName’. The argum RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    ent is null or empty. Provide an argument that is not null or empty, and then t RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    ry the command again. RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    At D:\_SMSTaskSequence\Packages\ZWT00231\UserApps.ps1:13 char:45 RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    + $PrimaryUsers = Get-WmiObject -ComputerName $SiteServer -Class SMS_UserMachin RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    eRe … RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    + ~~~~~~~~~~~ RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    + CategoryInfo : InvalidData: (:) [Get-WmiObject], ParameterBindi RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    ngValidationException RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    Shell.Commands.GetWmiObjectCommand RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)
    RunPowerShellScript 15-12-2014 09:50:41 3484 (0x0D9C)

  6. You’re right. I finally managed to adapt the script to my needs. I wish I was better at scripting.
    Thanks Peter, this script is very helpfull

  7. Thanks for the feedback. That’s correct, the script will not work when the collection contains an Active Directory User Group as member, but only when the collection contains the users of an Active Directory User Group. The reason for that is that the script checks the memberships of a user to a collection and not to an Active Directory Group.

  8. Hi Peter,

    Great script is there any way to have it check the Active Directory User Group if its a member then run the deployment? I ask as we have role based deployment for applications not direct user members

  9. Hi Pete,
    You don’t need direct memberships for the script to work. You should use a query that checks for the members of the AD group. That way the members of that AD group will show in the collections.

  10. When I run the wmi query for primary user on SMS_UserMachineRelationship. The Resource I am looking for is set to Unknown.

    Any Idea what would cause this?

  11. In the console the machine looks OK, I can search for it via machine name but the Primary User does not show at this point. The query during OSD runs and does not match a resource name, because the ResourceName field is unknown.

    Example of what is returned:
    IsActive: True
    RelationshipResourceID: ########
    ResourceClientType: 1
    ResourceID: ########
    ResourceName: Unknown
    Sources: (6)
    Types: (1)
    UniqueUserName: Domain\UserName

  12. I just figured this out, I need to force the UDA relationship before OSD makes this happen at the end of my build. Doing that the query pulls the correct information.

  13. Hi,
    I would like to use something like this but for applications which were deployed via the application catalog. Is there a way to do it?
    Thank you,

  14. Thank you for your quick answer. I don’t understand how this would work. Applications from the catalog are deployed on a user collection but they are not mandatory. The only way for me to know if the user has installed anything is by looking at the deployment tab in the user account properties.
    I though I would have to query the user account instead of query his collection membership.

  15. This script simply checks the collection membership of the user and simply finds the applications that are deployed to those collections. It doesn’t check if the application is truly installed or not.

  16. Ok, so I will try to modify it to do what I’m looking for.
    I will post it there if I’m successful.
    Thank you for your help!

  17. Hi, I’m getting ready to try this out in my lab environment. My question is can this be utilized if we have user targeted AVAILABLE applications? Or do they have to be required?

    My end goal would be to have all entitled apps for a user as available, but also be deployed during OSD on their primary workstation

  18. Peter,
    I may be stuck in the same scenario Chris mention’s above “I just figured this out, I need to force the UDA relationship before OSD makes this happen at the end of my build. Doing that the query pulls the correct information.”

    For the “Resource” name parameter, I am struggling to understand what to put here. This makes me feel like it will be static to a single computer name.

    Currently we are using a step in our UDI to input a Primary User to set the UDA. How can I get the script to read that as the resource?

  19. You’re correct. In some scenario’s this can be limiting. Using your own input can be better. In this case you could read the task sequence variable that you set and use that as input.

  20. Hi Peter, thanks for this awesome script. I’m trying to run it as part of UDI Wizard OSD Task Sequence, but running into a weird problem in that the SMSTS.LOG file is saying “Application failed to evaluate.” If I check the APPINTENTEVAL.LOG, it shows my applications with CURRENT STATE=ERROR and “Rejecting ScopeId_ … due to evaluation error.” Any ideas?

  21. Hey Peter, I figured it out. The SCCM applications I was testing with had complex SCCM Requirements based on Global Conditions (only install when not in certain OUs, don’t install if a specific other app is present.) For whatever reason, the evaluation wasn’t able to run these complex Global Condition Requirements so I removed them and everything worked. I guess whatever state Windows 10 is in when running that task sequence, it doesn’t have access to do complex stuff like figure out which OU its in.

  22. Hey again Peter, new problem: Your user-targeted and computer-targeted scripts correctly identify applications for deployment, but don’t differentiate between a deployment that is “install” or a deployment that is “uninstall.” This results in an “uninstall” deployment becoming an “install” deployment. Not a huge deal because SCCM will later correctly run an “uninstall” deployment when an Application Evaluation cycle occurs. Is there anyway to filter out “uninstall” deployments in the script? Thanks for all your help! This is making my life a lot easier.

  23. Thank you so much for putting this together Peter! Is there much of a security concern in giving domain computers the Read-Only Analyst view? I know they couldn’t write but it would be great for recon to be able to query SCCM for info from a compromised machine. Though, I suppose if an attacker is able to impersonate the machine account they already at least one box…

  24. Hi Andre,
    It does provide a computer account with the ability to query for more information. So yes, you might want to scope it further to specific areas.
    Regards, Peter

  25. Thanks Peter. I tried creating a separate account with read only access and tried the Run Command Line step to run the script to Run As that specific account. I ultimately couldn’t get it working and don’t fully understand why. From what I’ve read the version of powershell that is run (32 bit?) during a x64 OSD TS can’t use the -COMObject Microsoft.SMS.TSEnvironment when also using the RunAs…

    In any case I ended up commenting out the $TSEnv steps in order to use RunAs, then wrote the variables to a text file.

    New-Item -Path $env:windir\temp\AppVariables.csv
    Set-Content $env:windir\temp\AppVariables.csv -Value “var,appname”
    foreach ($ApplicationName in $ApplicationNames) {
    $Id = “{0:D2}” -f $Count
    $AppId = “APPId$Id”
    Add-Content -Path $env:windir\temp\AppVariables.csv -Value “$AppId,$ApplicationName”
    #$TSEnv.Value($AppId) = $ApplicationName

    Then I used a “Run Powershell” step to run a different script to read the file and create those variables.

    $TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment
    $vars = Import-Csv $env:windir\temp\AppVariables.csv
    foreach ($_ in $vars) {
    $AppId = $_.var
    $ApplicationName = $_.appname
    Write-Host $AppId $ApplicationName
    $TSEnv.Value($AppId) = $ApplicationName

    I’m sure there is a more elegant solution, but this is what worked for me without giving every computer read access to SCCM.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.