All posts by JosL

OnedriveMapper v3.15 released!

Version 3.15 of OneDriveMapper has been released:

  • MFA support for Phone Activation in Native Mode
  • MFA support for App Activation in Native Mode
  • Beta: automatic mapping of Teams, Sites and Groups that the user has favorited

AutoMapping

The following URL shows the Teams, Sites and Groups your account has favorited (following): https://YOURTENANTNAME.sharepoint.com/_layouts/15/sharepoint.aspx?v=following

If you set autoMapFavoriteSites to $True in the script configuration, the script will attempt to automatically assign free driveletters to all sites/teams/groups you’re following. This is, of course, beta functionality. I intend to add additional customization options for this feature in v3.16

As always, make sure to test before deploying to production, I’ve only tested Azure AD (no ADFS) setup, and note that MFA support can change quickly if Microsoft makes changes to the authentication process.

Get the new version here

Getting remoteapps through vm custom extension on Azure session brokers

So I wanted to retrieve the remoteapps present on VM’s in a uniform way, without logging in to either VM’s or database.

Using a custom extension, I tried to execute the Get-RDRemoteApp command and got the following:

Get-RDRemoteApp : A Remote Desktop Services deployment does not exist on server. This operation can be perfor
med after creating a deployment. For information about creating a deployment

Apparently, all the powershell commands for RDS require that you DON’T run them under SYSTEM. Of course VMExtensions run under SYSTEM. So, to get all remoteapps in a RDS deployment, execute the following Powershell script as VMExtension on a connection broker VM:

 

$farms = get-childitem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\CentralPublishedResources\PublishedFarms"
foreach($farm in $farms){
    (get-childItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\CentralPublishedResources\PublishedFarms\$($farm.PSChildName)\Applications").PSChildName
}

To register this Powershell script as a VM extension and retrieve the results

  1. Save the above PS code to a file
  2. Upload the file somewhere (e.g. public blob storage)
  3. Get the URL of the File
  4. Use Login-AzureRMAccount
  5. Execute Set-AzureRmVMCustomScriptExtension -FileUri URL TO SCRIPT -Run FILENAME OF SCRIPT -VMName VMNAME -Name “RetrieveRemoteApps” -ResourceGroupName RESOURCEGROUP NAME -location “westeurope” -ForceRerun $(New-Guid).Guid
  6. To retrieve the list (after execution): [regex]::Replace(((Get-AzureRmVMDiagnosticsExtension -ResourceGroupName RESOURCEGROUP NAME -VMName VM NAME -Name “RetrieveRemoteApps” -Status).SubStatuses[0].Message), “\\n”, “`n”)

Running an Azure runbook on a System hybrid worker

Azure Runbooks are usually run in the cloud (on an automatically assigned ‘Microsoft’ host) or on a Hybrid Worker Group.

Hybrid Worker Groups consist of 1 or more machines, but there are also ‘System hybrid workers’, which are machines monitored by OMS. If you want to execute a Powershell script directly on a specific System hybrid worker, or on a specific group member of a worker group, you can use Powershell and specify the host instead of the group:

Start-AzureRmAutomationRunbook -Name “RunbookName” -RunOn hybridWorkerName -AutomationAccountName “automationaccount” -ResourceGroupName “resourcegroup”

If you try this on a System Hybrid Worker, you’ll get an error on the device itself and in the runbook results:

“Invalid Runbook xxx Authenticode signature status – NotSigned”.

This can be ‘fixed’ by setting the following registry key to ‘False’:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HybridRunbookWorker\GuidOfYourWorker\EnableSignatureValidation

Et voila, the runbook runs nicely. I do not recommend disabling this key in production, this article is purely to share knowledge, and if someone knows how to do this without disabling this key, I’d love to hear it!

Remove-StaleIntuneDevices using a scheduled Azure Runbook

I recently came upon a really cool post by Josh and Sarah that explains how to clean up stale devices in Intune using the Graph API.

As I want to run this from an Azure runbook, silently, I had to modify it a little so it automatically consents to azure app permissions and logs in silently. If you’d like to use it, feel free to add it from the Azure gallery (search for Lieben) or download it yourself.

Make sure you’ve also imported the AzureAD and AzureRM modules into your automation account, and configured a credential object for the script to use.

GitLab: Remove-StaleIntuneDevicesForAzureAutomation.ps1

Technet: Remove-Stale-Intune-4b07488a

How to grant OAuth2 permissions to an Azure AD Application using PowerShell unattended / silently

You may know this button:There is no native Powershell command to grant OAuth permissions to an Azure AD Application, so I wrote a function for that. Note that this is NOT a supported way to grant permissions to an application because it does not follow the proper admin consent flow that applications normally use.

The great advantage of my method is that it can be used to grant permissions silently, AND to ‘hidden’ and/or multi-tenant applications that companies like Microsoft use for backend stuff like the Intune API. (e.g. the ‘Microsoft Intune Powershell’ multi-tenant application).

The function requires AzureAD and AzureRM modules installed!


Function Grant-OAuth2PermissionsToApp{
    Param(
        [Parameter(Mandatory=$true)]$Username, #global administrator username
        [Parameter(Mandatory=$true)]$Password, #global administrator password
        [Parameter(Mandatory=$true)]$azureAppId #application ID of the azure application you wish to admin-consent to
    )

    $secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
    $res = login-azurermaccount -Credential $mycreds
    $context = Get-AzureRmContext
    $tenantId = $context.Tenant.Id
    $refreshToken = @($context.TokenCache.ReadItems() | Where-Object {$_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date)})[0].RefreshToken
    $body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
    $apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
    $header = @{
    'Authorization' = 'Bearer ' + $apiToken.access_token
    'X-Requested-With'= 'XMLHttpRequest'
    'x-ms-client-request-id'= [guid]::NewGuid()
    'x-ms-correlation-id' = [guid]::NewGuid()}
    $url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$azureAppId/Consent?onBehalfOfAll=true"
    Invoke-RestMethod –Uri $url –Headers $header –Method POST -ErrorAction Stop
}

GITLAB: Grant-OAuth2PermissionsToApp.ps1

Update 2021: improved / mfa compatible token function