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.

Script

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! <<

Usage

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.

76 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: http://support.microsoft.com/kb/2913703

    [CmdletBinding()]

    param (
    [string]$ResourceName,
    [string]$SiteCode,
    [string]$SiteServer
    )

    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) {
    $containernodeid=$containernode.ContainerNodeId
    $InstanceKeys = Get-WmiObject -ComputerName $SiteServer -Class SMS_ObjectContainerItem -Namespace root/SMS/site_$SiteCode -Filter “ContainerNodeID=’$ContainerNodeId'”
    foreach ($InstanceKey in $InstanceKeys){
    $ik=$instancekey.InstanceKey
    $un=$primaryuser.UniqueUserName.replace(“\”,”\\”)
    $collectionId = Get-WmiObject -ComputerName $SiteServer -Class SMS_FullCollectionMembership -Namespace root/SMS/site_$SiteCode -Filter “CollectionID=’$ik’ and smsid=’$un'”
    $ci=$collectionId.CollectionId
    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
    #$ApplicationName.ApplicationName | out-file c:\applicationlist.txt -append
    $Count = $Count + 1
    }
    }
    }
    }
    }
    }
    }
    }

    Get-TargetedApplications

    Reply
  2. 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!

    Reply
  3. 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.

    Reply
  4. 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)

    Reply
  5. 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

    Reply
    • 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.

      Reply
  6. 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

    Reply
    • 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.

      Reply
  7. 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?

    Reply
  8. 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

    Reply
  9. 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.

    Reply
  10. 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,
    Bastien

    Reply
  11. 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.

    Reply
    • 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.

      Reply
  12. 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!
    Bastien

    Reply
  13. 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

    Reply
  14. 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?

    Reply
    • 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.

      Reply
  15. 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?

    Reply
  16. 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.

    Reply
  17. 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.

    Reply
  18. 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…

    Reply
  19. 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.

    Reply
  20. in regards to Chris’s response – “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.”

    How would you “Force” this relationship before the end of the build?

    Reply
  21. Hello Peter,

    Thank you for the script. I am getting an incorrect function when initializing the script. I was wondering if you could include a screenshot of the Get Application Task Sequence Step so I can ensure that I am including the parameters correctly. Thanks.

    Andy

    Reply
  22. Hi,

    I get the following error when running the script in a task sequences, I have granted “domain computers” read only access to SCCM as per your suggestion. If I run the script interactively it does retrieve assigned applications.
    Any suggestions on how to fix this would be very helpful.

    Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) RunPowerShellScript 14/02/2019 09:44:51 1644 (0x066C)
    At C:\_SMSTaskSequence\Packages\UKP006C9\Get-TargetedApplications_User.ps1:21 char:22 RunPowerShellScript 14/02/2019 09:44:51 1644 (0x066C)
    + … aryUsers = (Get-WmiObject -ComputerName $SiteServer -Class SMS_UserMa … RunPowerShellScript 14/02/2019 09:44:51 1644 (0x066C)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RunPowerShellScript 14/02/2019 09:44:51 1644 (0x066C)
    + CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException RunPowerShellScript 14/02/2019 09:44:51 1644 (0x066C)
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand RunPowerShellScript 14/02/2019 09:44:51 1644 (0x066C)
    RunPowerShellScript 14/02/2019 09:44:51 1644 (0x066C)

    Thanks,
    Martin.

    Reply
  23. Hi Peter,

    I should first state that I have copied one of the posters and amended the script itself with the following changes:

    [CmdletBinding()]
    $tsenv=New-Object -ComObject Microsoft.SMS.TSEnvironment
    $ResourceName=$tsenv.Value(“_SMSTSMACHINENAME”)
    $SiteCode=””
    $SiteServer=””
    $Container=”Approved Managed Applications”

    I have a run PowerShell step in the TS the references the script, this step has the following set up:
    Package: PKGID, Get-TargetedApplications
    Script name: Get-TargetedApplications_User.ps1
    Parameters: empty due to changes made to script
    PowerShell execution policy: Bypass

    The next step is Install Application and this is configured as per your screen shot, the only difference being that I have enable the option “if an application installation fails, continue installing other applications in the list.

    The TS is standard MDT one modified to fit our requirements, I know machines are domain joined prior to these steps as the TS includes a step to install Microsoft LAPS, this will only install on domain joined systems.

    Thanks, Martin.

    Reply
  24. Hi Peter,

    Success, I had to grant the domain group “Domain Computers” direct permissions on the site_ WMI Namespace. This is a bit odd as by adding “Domain Computers” to the SCCM read only role the group has been added to the local group “SMS Admins” which already has the correct access rights on the Namespace.

    Martin.

    Reply
  25. Is there a way to achieve this without giving domain computers read access to the wmi?
    For example by using a service account and in the ts use the option to run the powershells with that service account?

    Reply
  26. Hi Peter,

    Excellent to have this script available yet I am running into numerous obstacles and keep hitting the below errors. I have verified all the required permissions, followed your steps as you have highlighted but still cannot get tot the bottom of this. If you can provide any help at all it would be much appreciated as I am under pressure to get this into production.

    Many Thanks in advance

    Jon

    You cannot call a method on a null-valued expression.
    At C:\temp\Get-TargetedApplications_User.ps1:8 char:5
    + $PrimaryUsers = (Get-WmiObject -ComputerName $SiteServer -Class S …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
    At C:\temp\Get-TargetedApplications_User.ps1:31 char:9
    + $TSEnv.Value(“SkipApplications”) = “True”
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException

    SMSTS.LOG

    No Env variable with specified basename APPId and suffix ’01’ is found. No applications installed.

    Failed to run the action: Install Application.
    Unspecified error (Error: 80004005; Source: Windows)

    Reply
  27. Hi Peter,

    Thanks for your response, it was my fault, I had set the script to run under my account, that was the issue !! 🙂
    Just a final question, only about 1% of applications out of 500 are set to “required”, is there any way to bypass this and still force previously installed applications to install ?

    Many Thanks in advance

    Jon

    Reply
  28. Hello Peter,
    I am running into the problem that after the OS deployment TS, the user/device affinity is gone/empty from the object. So userbased apps will no longer get pre-deployed.
    Regards, Hans

    Reply
  29. Hello Peter, I’ve got the script working.
    But Found out that application should have one or more deployment types with the installation behaviour “Install for System”, not User,
    and option needs to be enabled >
    Allow this application to be installed from the Install Application task sequence without being deployed

    Kind regards,
    Hans

    Reply
  30. hi! how to change the script to get the list of collections not from the container, but from another collection, which includes all the necessary ones?

    Reply

Leave a Comment

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