Logon script for Intune managed devices. Start apps/actions at logon!

Last week i came across a post on Reddit. Someone was asking how to launch Edge at user logon. He had a script which was not working (always). It remembered me that i have a script which does exactly this over and over again. The script is originally build by Nicola Suter (https://tech.nicolonsky.ch). All the credits go to him!

The script can be modified to your needs. It can do basically everything you want using PowerShell. It runs at user logon via a scheduled task. Reed below to see what values need to be changed when you want to customize the script.

Note: Link to the script is shown below. First I’ll show you what it does.

The script creates a scheduled task and a folder containing a PowerShell and VBScript.

What to modify (for custom usage)

If you want to script to do something totally different you’ll need to modify some lines in the script. The current script is ment for opening Edge at logon.

  • Line 16: Modify UEM_AutostartEdge.log to something common
  • Line 75/81: Place your PowerShell code here. This is the action which will be executed
  • Line 98: Modify UEM_AutostartEdge.log to the same value as done in line 16
  • Line 112: Modify the parameter value UEM_AutostartEdge to something common. This is the directory name created in C:\Programdata
  • Line 119: Modify the parameter value UEM_AutostartEdge.ps1 to something common. This is the PowerShell script name created in C:\Programdata\subdir
  • Line 142: Modify the parameter value UEM-AutostartEdgeVBSHelper.vbs to something common. This is the name of the VBScript created in C:\Programdata\subdir
  • Line 154: Modify the parameter value UEM-AutostartEdgeTasks to something common

This example script basically executes the following cmdlet:

Start-Process "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"

This does not open a specific URL but that could be solved quite easy. We can configure a default tab/start page using an Intune policy or simply modify the cmdlet:

Start-Process "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" www.google.nl

The script can do basically everything PowerShell can do in the UEM environment. You can deploy multiple scripts to devices as long as you modify all the settings/parameters in te script. Not doing this will overwrite your current script and breaks things.

Deploy using Intune

  1. Go to https://intune.microsoft.com -> Devices -> Scripts. Click on Add -> Windows 10 and later.
  2. Give the script a name and description (Optional)
  3. Run this script using the logged on credentials: No
  4. Enforce script signature check: No
  5. Run script in 64 bit PowerShell Host: Yes
  6. Assign the script to user/device groups and verify the scheduled task + programdata folder are created.

Once the scripts are deployed you should logoff and logon your device. It will now launch Microsoft Edge or execute any configured action.

Example script

The script can be found in my Github or below in this blog.

<#
	.DESCRIPTION
		This script sets UEM settings with PowerShell.
		When executed under SYSTEM authority a scheduled task is created to ensure recurring or once script execution on each user logon.
	.NOTES
        BASE Author: Nicola Suter, nicolonsky tech: https://tech.nicolonsky.ch
#>

[CmdletBinding()]
Param()

###########################################################################################
# Start transcript for logging															  #
###########################################################################################

Start-Transcript -Path $(Join-Path $env:temp "UEM_AutostartEdge.log")

###########################################################################################
# Helper function to determine a users group membership									  #
###########################################################################################

function Get-ADGroupMembership {
	param(
		[parameter(Mandatory=$true)]
		[string]$UserPrincipalName
	)
	process{

		try{

			$Searcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher
			$Searcher.Filter = "(&(userprincipalname=$UserPrincipalName))"
			$Searcher.SearchRoot = "LDAP://$env:USERDNSDOMAIN"
			$DistinguishedName = $Searcher.FindOne().Properties.distinguishedname
			$Searcher.Filter = "(member:1.2.840.113556.1.4.1941:=$DistinguishedName)"
			
			[void]$Searcher.PropertiesToLoad.Add("name")
			
			$List = [System.Collections.Generic.List[String]]@()

			$Results = $Searcher.FindAll()
			
			foreach ($Result in $Results) {
				$ResultItem = $Result.Properties
				[void]$List.add($ResultItem.name)
			}
		
			$List

		}catch{
			#Nothing we can do
			Write-Warning $_.Exception.Message
		}
	}
}

###########################################################################################
# Get current group membership for the group filter capabilities			            			  #
###########################################################################################

if ($driveMappingConfig.GroupFilter){
	try{
		#check if running as user and not system
		if (-not ($(whoami -user) -match "S-1-5-18")){

			$groupMemberships = Get-ADGroupMembership -UserPrincipalName $(whoami -upn)
		}
	}catch{
		#nothing we can do
	}	 
}
###########################################################################################
# UEM CODE														                                                    
###########################################################################################



Start-Process "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"



###########################################################################################
# End & finish transcript														                                  #
###########################################################################################

Stop-transcript

###########################################################################################
# Done																				                                          #
###########################################################################################

#!SCHTASKCOMESHERE!#

###########################################################################################
# If this script is running under system (IME) scheduled task is created  (recurring)	    #
###########################################################################################

Start-Transcript -Path $(Join-Path -Path $env:temp -ChildPath "UEM_AutostartEdge.log")

if ($(whoami -user) -match "S-1-5-18"){

	Write-Output "Running as System --> creating scheduled task which will run on user logon"

	###########################################################################################
	# Get the current script path and content and save it to the client					          	  #
	###########################################################################################

	$currentScript= Get-Content -Path $($PSCommandPath)
	
	$schtaskScript=$currentScript[(0) .. ($currentScript.IndexOf("#!SCHTASKCOMESHERE!#") -1)]

	$scriptSavePath=$(Join-Path -Path $env:ProgramData -ChildPath "UEM_AutostartEdge")

	if (-not (Test-Path $scriptSavePath)){

		New-Item -ItemType Directory -Path $scriptSavePath -Force
	}

	$scriptSavePathName="UEM_AutostartEdge.ps1"

	$scriptPath= $(Join-Path -Path $scriptSavePath -ChildPath $scriptSavePathName)

	$schtaskScript | Out-File -FilePath $scriptPath -Force

	###########################################################################################
	# Create dummy vbscript to hide PowerShell Window popping up at logon				          	  #
	###########################################################################################

	$vbsDummyScript = "
	Dim shell,fso,file
	Set shell=CreateObject(`"WScript.Shell`")
	Set fso=CreateObject(`"Scripting.FileSystemObject`")
	strPath=WScript.Arguments.Item(0)
	If fso.FileExists(strPath) Then
		set file=fso.GetFile(strPath)
		strCMD=`"powershell -nologo -executionpolicy ByPass -command `" & Chr(34) & `"&{`" &_ 
		file.ShortPath & `"}`" & Chr(34) 
		shell.Run strCMD,0
	End If
	"

	$scriptSavePathName="UEM-AutostartEdgeVBSHelper.vbs"

	$dummyScriptPath= $(Join-Path -Path $scriptSavePath -ChildPath $scriptSavePathName)
	
	$vbsDummyScript | Out-File -FilePath $dummyScriptPath -Force

	$wscriptPath = Join-Path $env:SystemRoot -ChildPath "System32\wscript.exe"

	###########################################################################################
	# Register a scheduled task to run for all users and execute the script on logon	    	  #
	###########################################################################################

	$schtaskName= "UEM-AutostartEdgeTasks"
	$schtaskDescription="UEM task envoker"

	$trigger = New-ScheduledTaskTrigger -AtLogOn
	#Execute task in users context
	$principal= New-ScheduledTaskPrincipal -GroupId "S-1-5-32-545" -Id "Author"
	#call the vbscript helper and pass the PosH script as argument
	$action = New-ScheduledTaskAction -Execute $wscriptPath -Argument "`"$dummyScriptPath`" `"$scriptPath`""
	$settings= New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
	
	$null=Register-ScheduledTask -TaskName $schtaskName -Trigger $trigger -Action $action  -Principal $principal -Settings $settings -Description $schtaskDescription -Force

	Start-ScheduledTask -TaskName $schtaskName
}

Stop-Transcript

###########################################################################################
# Done																				                                          #
###########################################################################################

Related Posts

2 thoughts on “Logon script for Intune managed devices. Start apps/actions at logon!

  1. This looks great but it doesnt seem to be adding the schedule task for me even when running the script as admin from ISE

Leave a Reply

Your email address will not be published. Required fields are marked *

one × three =