Part 3, Deep dive Microsoft Intune Management Extension – Win32 Apps

IntuneWin32ComboLogoMicrosoft made it finally happen and provides an integrated way to deploy Win32 Apps via the Intune Management Extension. This is by far the biggest step forward in the Modern Management field. Until now the community came up with lots of ways to utilize PowerShell scripts to finally install some Win32 Apps. By doing this you need to take care of the content location, availability, distribution, the app install, and verification logic. All this is now available in the enhanced Intune Management Extension. As a short refresh regarding Intune Management Extension, I recommend to read my blog articles about it, where you find a lot of information regarding the architecture, the inner workings, and troubleshooting advises:

Part 1 Deep dive Microsoft Intune Management Extension – PowerShell Scripts
Part 2 Deep dive Microsoft Intune Management Extension – PowerShell Scripts

Both articles are very relevant to this new feature as they all describe the architecture and technical details regarding the Intune Management Extension itself. Exactly this Intune Management Extension is used now for deploying Win32 apps packaged as .intunewin file format. It’s even better, the new functionality can be used to basically transport everything in a package and trigger a certain command line for execution. This is not a end to end walk-through how to use the feature in regards of the Intune portal or on the client itself. For this check out other great articles found in my last section End to end usage walk-throughs?. This is an article all about the inner workings of this new capability, a deep dive into the new technology itself.

Table of content for easy navigation

How do we get packaged apps now?

To get a Win32 apps deployed via the Intune Management Extension we first need to package the content we want to distribute. Microsoft decided to use the same approach like they did for the macOS world, where they provide a small tool to create the packages – Microsoft Intune App Wrapping Tool for macOS. A similar tool to create these packages is available for the Windows world now. This tool is called:

Microsoft Intune Win32 App Packaging Tool

For all of you with ConfigMgr experience, the new feature to deploy Win32 apps with Intune can be compared a little bit with the Packages and Programs functionality within ConfigMgr, but with some additions.

The usage of the Microsoft Intune Win32 App Packaging Tool (IntuneWinAppUtil.exe) is quite simple. We specify a folder and the executable and create then an yourappname.intunewin file. This is our packaged app which we then can upload to the Intune service. The command line of the tool is this:

IntuneWinAppUtil -c  -s  -o  <-q>

To dig a little deeper we inspect the resulting package in detail now. After successful execution it will generate the .intunewin file from the specified source folder and setup file. For MSI setup files, this tool will retrieve required information for later usage in the Intune portal. To explore this a little bit I captured the output and highlighted some important facts there, to gain understanding how the tool is working.

IntuneWin32AppToolOutput

As seen the tool is executed with the necessary parameters to create a package for Google Chrome Enterprise Edition Browser, which is provided as a .msi file. A sub folder called Chrome is in the same folder as the IntuneWinAppUtil. The command line then is:

IntuneWinAppUtil.exe -c .\Chrome -s GoogleChromeStandaloneEnterprise64.msi -o .\ -q

If we look at the green highlighted output now we find some very important information appearing which is exactly describing the workflow:

  1. Compressing the source folder and its files to a sub folder ‘content’ with the new extension .intunewin
  2. Encrypting the compressed file
  3. Computing SHA265 hash
  4. Generating a detection.xml file in a sub folder ‘metadata’
  5. Compressing complete working folder and create again an .intunewin file

As we can see a normal zip compression is used and therefore it is easy to verify all this by opening the generated package with our favorite archive application:

IntuneWinContentRoot

We can see the content folder and metadata folder. Where the content folder stores the encrypted .intunewin file:

IntuneWinContentSubContent

and the metadata folder contains the detection.xml file:

IntuneWinContentSubMetadata

If we now have a look at the detection.xml file we can see the information gathered about the package and msi file:

<ApplicationInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ToolVersion="1.0.0.0">
  <Name>Google Chrome</Name>
 <UnencryptedContentSize>52284458</UnencryptedContentSize>
  <FileName>GoogleChromeStandaloneEnterprise64.intunewin</FileName>
  <SetupFile>GoogleChromeStandaloneEnterprise64.msi</SetupFile>
  <EncryptionInfo>
    <EncryptionKey>Rj9EtHeHGYMv5HYBpyobrmp0rVg0pzIy0TwO9PnSRg8=</EncryptionKey>
    <MacKey>5kxZeuk6xfeMak+r/9hzbwS0vBUW1jBMhgN10Jy7XBQ=</MacKey>
    <InitializationVector>2AK05qM3tm/5ijDnlFPISA==</InitializationVector>
    <Mac>zI8vragiGb1VtbVRiKo3lPkJldZGZB4juX50MCNrmDw=</Mac>
    <ProfileIdentifier>ProfileVersion1</ProfileIdentifier>
    <FileDigest>Nzl3O6e70W1P0kJDJiWh3eU6gCVOhODNNy7mspfplQA=</FileDigest>
    <FileDigestAlgorithm>SHA256</FileDigestAlgorithm>
  </EncryptionInfo>
  <MsiInfo>
    <MsiProductCode>{A4BC9C54-4589-3A4C-8217-9FA00262F471}</MsiProductCode>
    <MsiProductVersion>67.92.84</MsiProductVersion>
    <MsiUpgradeCode>{C1DFDF69-5945-32F2-A35E-EE94C99C7CF4}</MsiUpgradeCode>
    <MsiExecutionContext>System</MsiExecutionContext>
    <MsiRequiresLogon>false</MsiRequiresLogon>
    <MsiRequiresReboot>false</MsiRequiresReboot>
    <MsiIsMachineInstall>true</MsiIsMachineInstall>
    <MsiIsUserInstall>false</MsiIsUserInstall>
    <MsiIncludesServices>false</MsiIncludesServices>
    <MsiIncludesODBCDataSource>false</MsiIncludesODBCDataSource>
    <MsiContainsSystemRegistryKeys>true</MsiContainsSystemRegistryKeys>
    <MsiContainsSystemFolders>false</MsiContainsSystemFolders>
  </MsiInfo>
</ApplicationInfo>

A detailed review shows us the file and encryption information and in addition the MSI file information. This information is used by the Intune portal to pre-populate some Intune app definitions for us.

The MSI information is only available when a msi file is packaged. If we package a setup.exe for example you will not see the entire section in the detection.xml file.

Why is the .intunewin packaged like this?

This is pretty simple to explain. The portal and the Intune service gets all necessary information to deal with the app (in this case Google Chrome). The msi information listed in the detection.xml is used to simplify the setup within the Intune UI by pre-filling the app form during creation. For example by adding the install and uninstall commands for the msi automatically:

IntuneWin32AppsMSIInstallCommand

The EncryptionInfo is used to store it with your Intune tenant to gain access to the uploaded .intunewin package. The encrtypted .intunewin (located in the content folder) can be distributed safely to the Intune back-end services responsible for content distribution without getting exposed to others, only the tenant who uploaded the file has the EncryptionInfo and can decrypt the file.

Where can I find details of the Win32 App deployment?

The Intune Management Extension tracks some details of the Win32 apps in the registry at: HKLM\SOFTWARE\Microsoft\IntuneManagementExtension\Apps\

IntuneWin32AppDetailsRegistry

The yellow highlighted names provide us the execution commands for install and uninstall and the attempts and results of it.

If we look at the green highlighted GUID at HKLM\SOFTWARE\Microsoft\IntuneManagementExtension\Win32Apps\73d664e4-0886-4a… we can see it matches my Azure AD user object ID. To compare it I got the details via Azure AD PowerShell:

GetAzureADUser

The red highlighted GUID (b0f62b79-e464-4f95-afe2-ed99eb612fe5) is the application GUID which is assigned by the Intune service back-end. This can be easily traced by looking at the graph data with the Graph Explorer from Microsoft:

https://developer.microsoft.com/en-us/graph/graph-explorer

In my example I used this to retrieve the details of my uploaded app:

https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/b0f62b79-e464-4f95-afe2-ed99eb612fe5

This is the detailed information about the uploaded Win32 .intunewin app:

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#deviceAppManagement/mobileApps/$entity",
    "@odata.type": "#microsoft.graph.win32LobApp",
    "id": "b0f62b79-e464-4f95-afe2-ed99eb612fe5",
    "displayName": "Google Chrome (new)",
    "description": "Google Browser",
    "publisher": "Google",
    "largeIcon": null,
    "createdDateTime": "2018-09-21T09:38:11.4343585Z",
    "lastModifiedDateTime": "2018-09-21T09:39:16.2037636Z",
    "isFeatured": true,
    "privacyInformationUrl": null,
    "informationUrl": null,
    "owner": "",
    "developer": "",
    "notes": "",
    "uploadState": 1,
    "publishingState": "published",
    "committedContentVersion": "1",
    "fileName": null,
    "size": 52284512,
    "installCommandLine": "msiexec /i \"GoogleChromeStandaloneEnterprise64.msi\" /q",
    "uninstallCommandLine": "msiexec /x {A4BC9C54-4589-3A4C-8217-9FA00262F471} /q",
    "applicableArchitectures": "x64",
    "minimumFreeDiskSpaceInMB": null,
    "minimumMemoryInMB": null,
    "minimumNumberOfProcessors": null,
    "minimumCpuSpeedInMHz": null,
    "msiInformation": null,
    "setupFilePath": null,
    "minimumSupportedOperatingSystem": {
        "v8_0": false,
        "v8_1": false,
        "v10_0": false,
        "v10_1607": true,
        "v10_1703": false,
        "v10_1709": false,
        "v10_1803": false
    },
    "detectionRules": [
        {
            "@odata.type": "#microsoft.graph.win32LobAppProductCodeDetection",
            "productCode": "{A4BC9C54-4589-3A4C-8217-9FA00262F471}",
            "productVersionOperator": "notConfigured",
            "productVersion": null
        }
    ],
    "installExperience": {
        "runAsAccount": "system"
    },
    "returnCodes": [
        {
            "returnCode": 0,
            "type": "success"
        },
        {
            "returnCode": 1707,
            "type": "success"
        },
        {
            "returnCode": 3010,
            "type": "softReboot"
        },
        {
            "returnCode": 1641,
            "type": "hardReboot"
        },
        {
            "returnCode": 1618,
            "type": "retry"
        }
    ]
}

Intune Management Extension Agent working folders?

If we have a look at the file system at:

C:\Program Files (x86)\Microsoft Intune Management Extension\Content

we can find some interesting folders where the agent is downloading the content and detection scripts and stores the actual MSI log files:

ItnuneWin32AppsFolders

Agent execution context when processing .intunewin files?

The agent is bound to the same restrictions during execution like we know them for PowerShell scripts, meaning the calling process (the Intune Management Extension agent) is a 32-bit process. This can result in some unexpected behavior. For example when trying to package a simple .ps1 file within a .intunewin and trying to execute cmdlets in this scripts which are only available in a 64-bit environment. We then have to use a technique to restart the PowerShell script as a 64-bit process. This is described in my previous articles and I have built a Intune PowerShell script template to simplify the start for this, which can be found on my GitHub here https://github.com/okieselbach/Intune/blob/master/ManagementExtension-Samples/IntunePSTemplate.ps1. This can also affect installers packaged as .intunewin when they assume a 64-bit environment!

If no restart technique is used keep in mind that environment variables must be handled with care from 32-bit processes. For example if you like to target the %windir%\System32 environment from a 32-bit process you have to use %windir%\Sysnative otherwise you will land in %windir%\SysWOW64. Visit the linkt to read more about the file system redirector: https://docs.microsoft.com/en-us/windows/desktop/winprog64/file-system-redirector

What are the retry and execution intervals?

The agent has default values for retry and execution:

  • max. of 3 retries
  • interval between the retries is 5 min.
  • max. execution run time is 60 min.

these limits are not adjustable at the moment.

Current Limitations (as per date Oct-2018)?

  • No user context app installation (added 22th of Oct)
  • No system context installation without user logged on (added 22th of Oct)
  • No dependency support
  • No supersedence
  • No support for Delivery Optimization
  • No integration into Enrollment Status Page, no wait for Win32 app installs
  • No notification suppression
  • No ordered installations, sequencing like .NET Framework install before App X
  • Current application size is capped at 2GB 8GB per app (changed 22th of Oct)

End to end usage walk-throughs?

Good walk-throughs on how to use the feature with the Intune portal and the end user experience can be found here:

Deploy Win32 Applications with Microsoft Intune
http://www.scconfigmgr.com/2018/09/24/deploy-win32-applications-with-microsoft-intune/

Deploy customized Win32 apps via Microsoft Intune
https://www.petervanderwoude.nl/post/deploy-customized-win32-apps-via-microsoft-intune/

Intune – sidecar for Win32 apps revealed
http://gerryhampsoncm.blogspot.com/2018/09/intune-sidecar-for-win32-apps-revealed.html

Intune Win32 App deployment – A gamechanger
https://ccmexec.com/2018/10/intune-win32-app-deployment-a-gamechanger/

Official documentation can be seen here

Intune Standalone – Win32 app management
https://docs.microsoft.com/en-us/intune/apps-win32-app-management

Remember to check back frequently as Intune progresses and the feature will be enhanced in short cycles. I will update the article accordingly.

Happy packaging, deploying and troubleshooting Win32 apps with Intune!

Part 2, Deep dive Microsoft Intune Management Extension – PowerShell Scripts

Because of the popularity of my first blog post Deep dive Microsoft Intune Management Extension – PowerShell Scripts, I’ve decided to write a second post regarding Intune Management Extension to further explain some architecture behind this feature and upcoming question from the community. A deeper understanding helps to successful troubleshoot the feature.

Table of content for easy navigation

 

Details of the MSI deployment of the Intune Management Extension agent?

Please read the first article Deep dive Microsoft Intune Management Extension – PowerShell Scripts, to get an understanding of the MSI install job.

The EnterpriseDesktopAppManagement CSP takes care of this task and delivers the MSI to the device and starts the execution. The CSP provides some helpful information in registry for troubleshooting.

In the registry at HKLM\SOFTWARE\Microsoft\EnterpriseDesktopAppManagement\<SID>\<MSI-ProductCode> you can find helpful information for troubleshooting:

EnterpriseDesktopAppManagementCspRegistry

Highlighted value names are described in detail here:

CurrentDownloadUrl: URL to the MSI install file.

EnforcementRetryCount: The number of times the download and installation operation will be retried before the installation will be marked as failed.

EnforcementRetryIndex: The current number of retry.

EnforcementRetryInterval: Amount of time, in minutes between retry operations.

EnforcementStartTime: Start time of enforcement.

EnforcementTimeout: Amount of time, in minutes that the installation process can run before the installer considers the installation may have failed and no longer monitors the installation operation.

LastError: Error after last execution.

Status: The Status can have the following values according to the EnterpriseDesktopAppManagement CSP documentation:

Value = Status
10 = Initialized
20 = Download In Progress
25 = Pending Download Retry
30 = Download Failed
40 = Download Completed
48 = Pending User Session
50 = Enforcement In Progress
55= Pending Enforcement Retry
60 = Enforcement Failed
70 = Enforcement Completed

In case of no sidecar agent on the device the status may indicate an error or it is still in progress of downloading. Try to figure out this status. Correlate the status with your device and environment. There may be a proxy issue?

According to the screenshot above the CSP will try it 3 times with a timeout of 10 min and then it will be marked as failed. Is there a retry after x days, I assume yes but I don’t have some documentation for it. As soon as I have more information I will update the article accordingly.

 

Be aware of the log files regarding sensitive data!

The following script below will create a local user account with a specified static password. It is a working script, but be aware that it should not be used in production! The whole script content will be logged to the IntuneManagementExtension.log file. There you will find the clear text static password as defined in the script. As an example I have copied and marked the particular log file entries below the script to show that. Disk encryption technologies like BitLocker are lowering the risks a bit, but even then this is not a concept to be used in production environments! An attacker can read the log files with standard user permissions and get the sensitive data. Without BitLocker encryption this can be done even offline!

Again: I do NOT recommend transferring sensitive data like passwords via this approach! I know it’s often done. There is a similar approach for on-prem AD which is often used. The GPO preferences for local user management tasks uses a simple xml file with passwords base64 encoded -> this is not secure! Please consider something that was build for that purpose. Admin account management should be done via LAPS or other third party. I know there is no equivalent solution like LAPS for a cloud only environment right now from Microsoft.

# Author: Oliver Kieselbach
# Date: 01/03/2018
# Description: Create a local user account.

# REMARK: DO NOT USE IN PRODUCTION, Password will not be unique and be visible in clear text in log file!

# The script is provided "AS IS" with no warranties.

Param([switch]$Is64Bit = $false)

Function Restart-As64BitProcess
{
If ([System.Environment]::Is64BitProcess) { return }
$Invocation = $($MyInvocation.PSCommandPath)
if ($Invocation -eq $null) { return }
$sysNativePath = $psHome.ToLower().Replace("syswow64", "sysnative")
Start-Process "$sysNativePath\powershell.exe" -ArgumentList "-ex bypass -file `"$Invocation`" -Is64Bit" -WindowStyle Hidden -Wait
}

if (!$Is64Bit) { Restart-As64BitProcess }
else
{
Start-Transcript -Path "$env:temp\CreateLocalUser.log"

$password = ConvertTo-SecureString "SecretP@ssw0rd!" -AsPlainText -Force
New-LocalUser "John" -AccountNeverExpires:$true -FullName "John Doe" -Password $password

Stop-Transcript
}

To demonstrate the problem with this approach, here is the corresponding log file part after script execution with the complete script and static password in clear text:

sensitivedatainlogfile.png

 

Getting content of scripts once they are uploaded to Intune?

The Intune Azure Portal does not provide any UI element to show the uploaded script again. Thanks to the GitHub repository Intune PowerShell Samples we do not script something by our own. We can use a script provided from there called DeviceManagementScripts_Get.ps1. It will get all uploaded scripts, including script content, and details from the Intune API via Microsoft Graph API.

Get it from here:
https://github.com/microsoftgraph/powershell-intune-samples/blob/master/DeviceConfiguration/DeviceManagementScripts_Get.ps1

Save it locally and run it with PowerShell and provide your Intune Administrator credentials when asked for:

IntuneManagementExtensionScriptContent

 

What about return codes (exit codes) of PowerShell scripts?

At the moment the Intune Management Extension will gather various results, but the Intune Azure portal does not show them in an UI element (if it will change in the future and we have something available, I will update the post accordingly). As for now scripts can be executed through the Intune agent and the Intune UI will show just the execution state success or failure. The status is related to successful agent execution, like no hash mismatch, no script content problem, and no error output… it does not reflect the script exit code.

Scripts like this, I called it “failscript.ps1” are handled as success at the moment:

[Environment]::Exit(-1)

See here the results in Intune Azure Portal:

IntuneAgentFailscriptStatus

Perhaps Intune will show us script exit codes in the UI sometime, then we could verify this easily with the failscript from above.

If we use Write-Error cmdlet in our scripts then Intune will pick up the error output. Here an example:

Write-Error -Message "Could not write regsitry value" -Category OperationStopped

This gives us a failed status in the monitoring section of the PowerShell scripts:

IntuneAgentWriteErrorScriptStatus

 

 

Where can I find a helpful PowerShell script template to start with?

I have made a simple script template which:

  1. Enforces execution in x64 PowerShell (restart of PowerShell as x64 process)
  2. Generates a log file in C:\Windows\temp when run in system context
    or %LocalAppData%\temp when run in user context
  3. Has exit code handling (exit code is even gathered when restarted as x64 process)
  4. Uses Write-Error to signal Intune a failed execution and makes sure we have reporting reflecting our script execution success (standard error is even gathered when restarted as x64 process)

For ongoing maintenance it is provided via GitHub Gist:

 

Script execution retry interval when failed?

The PowerShell scripts are executed via agent on the target device. If an execution fails, the agent tries to run the script again during next check-in. Current check-in interval is every 60 minutes. This procedure is limited to 3 attempts!

This is tracked in registry at:

HKLM\SOFTWARE\Microsoft\IntuneManagementExtension\Policies\UserGUID\ScriptGUID

The DownloadCount also means execution count and the result is tracked as Success or Failed.

IntuneManagementExtensionScriptRegistry

If we change the run as account (user/system), signature check or script content, the DownloadCount will be reset, and the agent will try another 3 attempts to execute the script.

If a script should be enforced to run again, we can simply reset DownloadCount and ErrorCode to 0 and set Result and ResultDetails to nothing (empty string). After this we just restart the Microsoft Intune Management Extension Service (IntuneManagementExtension) and the script will rerun again on this device.

 

Can we schedule scripts?

No we do not have a run schedule at the moment. For example the agent does not execute the script every x hours. The agent checks every 60 minutes for new policies in the backend – during this no re-run of scripts occurs once a script is successful executed. If scheduling of scripts is needed I suggest to register the script as a scheduled tasks via PS commands. That’s the only way at the moment (as soon as we have something available for scheduling I will update the post accordingly).

Below a script to copy the scheduled script to a certain folder like C:\ProgramData\CustomScripts\myScript.ps1 and then register a scheduled task to run it periodically:

# Author: Oliver Kieselbach
# Date: 01/31/2018
# Description: install ps script and register scheduled task

# The script is provided "AS IS" with no warranties.

# define your PS script here
$content = @"
Out-File -FilePath "C:\Windows\Temp\test.txt" -Encoding unicode -Force -InputObject "Hello World!"
"@

# create custom folder and write PS script
$path = $(Join-Path $env:ProgramData CustomScripts)
if (!(Test-Path $path))
{
 New-Item -Path $path -ItemType Directory -Force -Confirm:$false
}
Out-File -FilePath $(Join-Path $env:ProgramData CustomScripts\myScript.ps1) -Encoding unicode -Force -InputObject $content -Confirm:$false

# register script as scheduled task
$Time = New-ScheduledTaskTrigger -At 12:00 -Daily
$User = "SYSTEM"
$Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ex bypass -file `"C:\ProgramData\CustomScripts\myScript.ps1`""
Register-ScheduledTask -TaskName "RunCustomScriptDaily" -Trigger $Time -User $User -Action $Action -Force

Here some documentation regarding PowerShell and scheduled tasks:
https://docs.microsoft.com/en-us/powershell/module/scheduledtasks/register-scheduledtask?view=win10-ps

But you need to think about a strategy how to track all this or how to modify in the future. Once set you may want to have a modification script to change schedules or even delete it from the device again.

 

Integrated HealthCheck of Intune Management Extension agent?

The Intune Management Extension creates a scheduled task which will run a Health Check once a day.

IntuneManagementExtensionHealthCheck

If familiar with ConfigMgr and the ConfigMgr agent, there we have the same concept. The health check involves 4 files:

ClientHealthEval.exe and ClientHealthEval.exe.config: The binary which runs the health check.

HealthCheck.xml: The xml with all rules to run to perform the health check.

HealthReport.json: The json report with results of the rules defined by the xml.

The tests are defined in the xml file to check the agent registered service, startup type, service status and memory usage.

 

User interaction and timeout?

When using a scripts with the typical user interaction (like shown as an example in my first article Deep dive Microsoft Intune Management Extension – PowerShell Scripts), be advised that this script is getting executed and showing a dialog which blocks the script from finishing, until the user interacts with the dialog and then let the script finish. This can lead to timeouts and then scripts are getting marked as failed even when successfully ran.

The current default script timeout is 10 minutes for execution which is currently not adjustable.

 

PowerShell scripts execution without user logon?

Since 22th of October the end users are no longer required to be logged in on the device to execute PowerShell scripts.

 

If you find something missing or changed feel free to leave a comment. Thanks!

Deep dive Microsoft Intune Management Extension – PowerShell Scripts

Microsoft made a big step forward in the Modern Management field. Limitations like custom configurations or even Win32 App installs can be addressed now. Microsoft developed an EMS agent (aka SideCar) and released it as a new Intune feature called Intune Management Extension. This agent is able to manage and execute PowerShell scripts on Windows 10 devices and it does this quite well.

IntuneManagementExtensionMSIProperties

We can simply upload our own PowerShell scripts for device configuration:

PowerShellScriptsIntune

Part 2 of this article answers common questions I’ve seen, when working with the Intune Management Extension – Part 2, Deep dive Microsoft Intune Management Extension – PowerShell Scripts.

Part 3 of this series will dive into the Microsoft Intune Management Extension – Win32 Apps deployment capabilities – Part 3, Deep dive Microsoft Intune Management Extension – Win32 Apps

 

How do we get the agent installed on the devices?

The ability to deploy basic MSI packages via MDM OMA-DM channel, is provided by Microsoft since the beginning of Windows 10. This is achieved by using the EnterpriseDesktopAppManagement CSP.

Microsoft is using this mechanism to deploy the agent to Windows 10 devices. Beginning with Windows 10 Version 1607 we have support of the Intune Management Extension now. The device must be AAD joined and the automatic MDM enrollment must be enabled (see Prerequisites).

The workflow is basically like this. If a PowerShell script is assigned to a user group (device groups are not supported since 22th of Oct.) and the agent is not installed, it will be pushed down automatically to the device via EnterpriseDesktopAppManagement CSP by Intune. This can be verified and traced in the “Advanced Diagnostics Report” of the MDM management.

Open Settings > Accounts > Access work or school > Connected to TenantName’s Azure AD > Info > scroll down to the bottom and click “Create report”

AdvancedDiagnosticsReportNow you get an report about all MDM configurations including the desktop app installations. Here we can see the EnterpriseDesktopAppManagement msi install of the EMSAgent with the ProductCode: {25212568-E605-43D5-9AA2-7AE8DB2C3D09}

EMSAgentInstallReport

./device/Vendor/MSFT/EnterpriseDesktopAppManagement/MSI/%7B25212568-E605-43D5-9AA2-7AE8DB2C3D09%7D

The instruction can be translated into more human readable form with ProductCode and curly brackets, as the yellow marked resource uses URL encoding and here %7B = { and %7D = }

./device/Vendor/MSFT/EnterpriseDesktopAppManagement/MSI/{25212568-E605-43D5-9AA2-7AE8DB2C3D09}

If the device encounters any error during installation of the agent, we can troubleshoot this with the eventlog:

Start event viewer > Applications and Services Logs > Microsoft > Windows > DeviceManagement-Enterprise-Diagnostics-Provider > Admin

An example where the agent installation went wrong with an error event id 1924 looks like this:

Event ID 1924, Error

EnterpriseDesktopAppManagement CSP: An application install has failed. 
Examine the MSI log (C:\Windows\system32\config\systemprofile\AppData\
Local\mdm\{25212568-E605-43D5-9AA2-7AE8DB2C3D09}.log) for more details. 
Install command: ("C:\Windows\system32\msiexec.exe" /quiet /l*v 
C:\Windows\system32\config\systemprofile\AppData\Local\mdm\
{25212568-E605-43D5-9AA2-7AE8DB2C3D09}.log /qn /i "C:\Windows\system32\
config\systemprofile\AppData\Local\mdm\
{BD19E4D8-D6C9-48B2-A53C-579D03B29FE9}.msi" ), 
MSI ProductCode: {25212568-E605-43D5-9AA2-7AE8DB2C3D09}, 
User SID: (S-0-0-00-0000000000-0000000000-000000000-000), 
Result: (User cancelled installation.).

Here we can see the original MSI install command including logfile path for further analysis:

C:\Windows\system32\config\systemprofile\AppData\Local\mdm\ {25212568-E605-43D5-9AA2-7AE8DB2C3D09}.log

The agent will get installed in the 32-bit Program Files path:

C:\Program Files (x86)\Microsoft Intune Managment Extension

IntuneManagementExtension

 

How does the agent gets it’s policy?

The agent will start to figure out the service endpoint via Service Discovery. A common approach in Microservices architecture in modern cloud platforms. After getting the Intune Service URL (https://somemssubdomain.manage.microsoft.com/SideCar/StatelessSideCarGatewayService) the agent can start to communicate and will receive its assigned policies.

All this can be traced in the logfiles here:

C:\ProgramData\Microsoft\IntuneManagementExtension\Logs

IntuneManagementExtensionLogs

The agent will start to download and execute the assigned PowerShell script here:

C:\Program Files (x86)\Microsoft Intune Managment Extension\Policies\Scripts\UserGUID_ScriptGUID.ps1

and the results are written here:

C:\Program Files (x86)\Microsoft Intune Managment Extension\Policies\Results\UserGUID_ScriptGUID.output|.error|.timeout

After successful execution the script and results are cleaned up and nothing is left on the device. Corresponding registry entries for the assigned scripts and execution results are here:

HKLM\SOFTWARE\Microsoft\IntuneManagementExtension\Policies\UserGUID\ScriptGUID

IntuneManagementExtensionRegistry

 

How often does the agent check for new policies?

The default is every 60 minutes.

 

What are the PowerShell script execution options?

We can execute scripts in system context or user context. Optional we can enforce a signature check.

ScriptSettings

The current file size limit is 10KB for ASCII scripts and 5KB for unicode scripts. The current file size limit is max. 200KB.

 

How do I enforce next agent check for policies?

Simply restart the Windows Service “Microsoft Intune Management Extension”.

IntuneManagementExtensionWindowsService

 

Is there a particular order in which multiple scripts are executed?

No, they are executed in random order.

 

What can be done with the PowerShell script execution?

Some examples and potentially pitfalls with the usage of the Intune Management Extension are listed below:

Install Win32 application

Install Win32 applications can be done easily by using a web request to get sources for the installation and finally execution of the sources. This technique is used a lot in the Chocolatey space. A simple example with 7-zip is shown below and can be modified to your needs:

# Author: Oliver Kieselbach
# Date: 11/28/2017
# Description: Download executable or msi and execute to install.

# The script is provided "AS IS" with no warranties.
$url = "http://www.7-zip.org/a/7z1701-x64.msi"
$filePath = "c:\windows\temp\7z1701-x64.msi"
$ProgressPreference = 0
Invoke-WebRequest $url -OutFile $filePath -UseBasicParsing
& $filePath /quiet

To use Chocolatey you should follow the install instructions from the Chocolatey website:

iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

After Chocolatey Framework installation you can use choco.exe install Package in additional PS scripts to install Chocolatey software. An excellent post from Peter van der Woude regarding Chocolatey and Intune Management Extension can be found here: Combining the powers of the Intune Management Extension and Chocolatey

 

Write registry keys in x64 hive and not WOW6432Node

As the agent is an 32-bit agent every PowerShell script execution will be in the 32-bit agent process. If we write a registry key on a x64 device from a 32-bit process it will be redirected to the WOW6432Node in the registry. This is often not the desired behavior. To solve this we can restart the script as a 64-bit process for script execution. An example to write a registry key to the x64 hive with this technique is shown below:

# Author: Oliver Kieselbach
# Date: 11/28/2017
# Description: Write to registry and ensure execution from x64 process environment.

# The script is provided "AS IS" with no warranties.

Param([switch]$Is64Bit = $false)

Function Restart-As64BitProcess
{
 If ([System.Environment]::Is64BitProcess) { return }
 $Invocation = $($MyInvocation.PSCommandPath)
 if ($Invocation -eq $null) { return }
 $sysNativePath = $psHome.ToLower().Replace("syswow64", "sysnative")
 Start-Process "$sysNativePath\powershell.exe" -ArgumentList "-ex bypass -file `"$Invocation`" -Is64Bit" -WindowStyle Hidden -Wait
}

Function New-RegistryKey
{
 Param([Parameter(Mandatory = $true)]
 [string]$Key,
 [Parameter(Mandatory = $true)]
 [string]$Name,
 [Parameter(Mandatory = $true)]
 [string]$Value,
 [ValidateSet("String", "ExpandString", "Binary", "DWord", "Multistring", "QWord", ignorecase=$true)]
 [string]$Type = "String")
 try
 {
 $subkeys = $Key.split("\")

foreach ($subkey in $subkeys)
 {
 $currentkey += ($subkey + '\')
 if (!(Test-Path $currentkey))
 {
 New-Item -Type String -Path $currentkey | Out-Null
 }
 }

Set-ItemProperty -Path $currentkey -Name $Name -Value $Value -Type $Type -ErrorAction SilentlyContinue
 }
 catch [system.exception]
 {
 $message = "{0} threw an exception: `n{0}" -f $MyInvocation.MyCommand, $_.Exception.ToString()
 Write-Host $message
 }
}

if (!$Is64Bit) { Restart-As64BitProcess }
else
{
 # Enable Potentially Unwanted Application protection
 New-RegistryKey -Key "hklm:\SOFTWARE\Microsoft\Windows Defender" -Name "PUAProtection" -Value "1" -Type DWord
}

Please see my GitHub account for Intune Management Extension Samples for a enhanced and maintained PowerShell Template (IntunePSTemplate.ps1) which takes care of x64 restarting, logging and so on!

 

Execute in user context and show dialog

To show a simple example to execute scripts in user context we can use the following script to present a Message Box to the user:

 Add-Type -AssemblyName PresentationFramework
 [System.Windows.MessageBox]::Show('Hello World from Sid-Car!')

HelloSideCar

 

I hope this explains the technical implementation of the Microsoft Intune Management Extension and the extension addresses some road blockers you might have in the past with Intune regarding advanced configurations.

See also my follow up post Part 2, Deep dive Microsoft Intune Management Extension – PowerShell Scripts for even more details and common questions around architecture and troubleshooting.

Part 3 of this series will dive into the Microsoft Intune Management Extension – Win32 Apps deployment capabilities – Part 3, Deep dive Microsoft Intune Management Extension – Win32 Apps