Category Archives: Automation

Finding files in Sharepoint Online or Teams that exceed 218 path length

A well known issue when migrating to Office 365 (Sharepoint, Teams and Onedrive) is path length.

Recently, Microsoft increased the maximum path length in Sharepoint Online from 256 to 400 characters (total length of the URL). This causes issues when you use Office, because Office 2013, 2016 and 2019 do not support paths over 218 characters in length.*

To help you proactively identify files that exceed this limit I wrote a PowerShell script you can run:

  • it can filter based on file type
  • automatically finds and processes all sharepoint sites in your tenant
  • automatically finds and processes all team sites in your tenant
  • it can handle multi-factor authentication

Find get-filesWithLongPathsInOffice365.ps1 on GitLab

It leans heavily on the great work done by the community around OfficePnP, all credits to the community for providing so much quality code for free!

*longer paths may still work, this is not a hard limit

SAP SuccessFactors to Active Directory Sync (updated users)

For a customer that is using SuccessFactors to manage their employees / contractees, I wrote a script that will update the AD accounts of any person that is updated in SuccessFactors.

I expect you’ll have working knowledge on how to configure SF PerformanceManager to export the users you wish to update to a CSV file on the sFTP server SF provides for you.

With that, you should be able to configure the script. It’ll basically map any field you export to any field in Active Directory you wish. In some cases, such as the Manager field, special logic has been added to the script to look up the user’s manager. For other special fields you may have to write your own logic.

If you wish, the script will provide you with a full report in your email, for example:

Get it @ Gitlab directly: https://gitlab.com/Lieben/assortedFunctions/blob/master/update-AdUsersFromSAPSuccessFactorsReport.ps1

SAP SuccessFactors to Active Directory Sync (disabled users)

For a customer that is using SuccessFactors to manage their employees / contractees, I wrote a script that will disable the AD accounts of any person that is disabled in SuccessFactors.

I expect you’ll have working knowledge on how to configure SF PerformanceManager to export the users you wish to disable to a CSV file on the sFTP server SF provides for you.

With that, you should be able to configure the script. If you wish, the script will provide you with a full report in your email, for example:

Get it @ Gitlab directly: https://gitlab.com/Lieben/assortedFunctions/blob/master/disable-AdUsersFromSAPSuccessFactorsReport.ps1

Full AzureAD Applications Permission overview

So you’d like to know which applications are living in your AzureAD?

And you’d like to know which of those were added by your admins, and what permissions those applications have?

And you’d also like to know which applications your users are consenting to, and what rights those applications have on your users?

Look no further, I wrote a script to export all of that to Excel for you!

Application overview

Apps an admin has consented to and the type of rights it needs

Apps a user has consented to and the type of rights it needs

Apps to user mapping, for an easy overview of which user has consented to which app

Get it at:

Credits to Doug Finke for the Excel module I’m using!

 

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 &quot;HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\CentralPublishedResources\PublishedFarms&quot;<br />
foreach($farm in $farms){<br />
    (get-childItem &quot;HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\CentralPublishedResources\PublishedFarms\$($farm.PSChildName)\Applications&quot;).PSChildName<br />
}<br />

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!

</p>
<p>Function Grant-OAuth2PermissionsToApp{<br />
Param(<br />
[Parameter(Mandatory=$true)]$Username, #global administrator username<br />
[Parameter(Mandatory=$true)]$Password, #global administrator password<br />
[Parameter(Mandatory=$true)]$azureAppId #application ID of the azure application you wish to admin-consent to<br />
)</p>
<p>Function Grant-OAuth2PermissionsToApp{<br />
    Param(<br />
        [Parameter(Mandatory=$true)]$Username, #global administrator username<br />
        [Parameter(Mandatory=$true)]$Password, #global administrator password<br />
        [Parameter(Mandatory=$true)]$azureAppId #application ID of the azure application you wish to admin-consent to<br />
    )</p>
<p>    $secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force<br />
    $mycreds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)<br />
    $res = login-azurermaccount -Credential $mycreds<br />
    $context = Get-AzureRmContext<br />
    $tenantId = $context.Tenant.Id<br />
    $refreshToken = $context.TokenCache.ReadItems().RefreshToken<br />
    $body = &quot;grant_type=refresh_token&amp;refresh_token=$($refreshToken)&amp;resource=74658136-14ec-4630-ad9b-26e160ff0fc6&quot;<br />
    $apiToken = Invoke-RestMethod &quot;https://login.windows.net/$tenantId/oauth2/token&quot; -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'<br />
    $header = @{<br />
    'Authorization' = 'Bearer ' + $apiToken.access_token<br />
    'X-Requested-With'= 'XMLHttpRequest'<br />
    'x-ms-client-request-id'= [guid]::NewGuid()<br />
    'x-ms-correlation-id' = [guid]::NewGuid()}<br />
    $url = &quot;https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$azureAppId/Consent?onBehalfOfAll=true&quot;<br />
    Invoke-RestMethod –Uri $url –Headers $header –Method POST -ErrorAction Stop<br />
}<br />

GITLAB: Grant-OAuth2PermissionsToApp.ps1

Exchange Online reconnect script v2

A few weeks ago I posted a script that would automatically, periodically, reconnect to Exchange Online. In field testing it would still prompt for credentials after 1-2 days, whatever I did.

So I took a different route and am now rewriting Microsofts’ module on the fly to no longer prompt for credentials. If you use below function to connect to Exchange Online, you should never receive reconnect prompts 🙂

disclaimer: don’t overwrite $o365Creds with invalid creds elsewhere in your script as those are used globally.

</p>
<p>function buildResilientExchangeOnlineSession {<br />
    Param(<br />
        [Parameter(Mandatory=$true)]$o365Creds,<br />
        $commandPrefix<br />
    )<br />
    Write-Verbose &quot;Connecting to Exchange Online&quot;<br />
    Set-Variable -Scope Global -Name o365Creds -Value $o365Creds -Force<br />
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $o365Creds -Authentication Basic -AllowRedirection<br />
    Import-PSSession $Session -AllowClobber -DisableNameChecking<br />
    Write-Verbose &quot;Connected to Exchange Online, exporting module...&quot;<br />
    $temporaryModulePath = (Join-Path $Env:TEMP -ChildPath &quot;temporaryEXOModule&quot;)<br />
    $res = Export-PSSession -Session $Session -CommandName * -OutputModule $temporaryModulePath -AllowClobber -Force<br />
    $temporaryModulePath = Join-Path $temporaryModulePath -ChildPath &quot;temporaryEXOModule.psm1&quot;<br />
    Write-Verbose &quot;Rewriting Exchange Online module, please wait a few minutes...&quot;<br />
    [String]$newContent<br />
    $found = $False<br />
    (Get-Content $temporaryModulePath) | % {<br />
        if(!$found -and $_.IndexOf(&quot;host.UI.PromptForCredential(&quot;) -ge 0){<br />
            $line = &quot;-Credential `$global:o365Creds ``&quot;<br />
            if($line){<br />
                $found = $True<br />
            }<br />
        }<br />
        if($line){<br />
            $newContent += $line<br />
            $line=$Null<br />
        }else{<br />
            $newContent += $_<br />
        }<br />
        $newContent += &quot;`r`n&quot;<br />
    }<br />
    $newContent | Out-File -FilePath $temporaryModulePath -Force -Confirm:$False -ErrorAction Stop<br />
    $Session | Remove-PSSession -Confirm:$False<br />
    Write-Verbose &quot;Module rewritten, re-importing...&quot;<br />
    if($commandPrefix){<br />
        Import-Module -Name $temporaryModulePath -Prefix $commandPrefix -DisableNameChecking -WarningAction SilentlyContinue -Force<br />
        Write-Verbose &quot;Module imported, you may now use all Exchange Online commands using $commandPrefix as prefix&quot;<br />
    }else{<br />
        Import-Module -Name $temporaryModulePath -DisableNameChecking -WarningAction SilentlyContinue -Force<br />
        Write-Verbose &quot;Module imported, you may now use all Exchange Online commands&quot;<br />
    }<br />
    return $temporaryModulePath<br />
}</p>
<p>

download: https://gitlab.com/Lieben/assortedFunctions/blob/master/buildResilientExchangeOnlineSession.ps1