Wednesday, 4 July 2018

Configuring log-on scripts to run via powershell from the "Run" key in Windows registry


If you’ve tried to add a powershell script to a registry run key, you’ve probably discovered that it doesn’t run with powershell.  Instead, Windows just opens the script in Notepad and leaves it sitting there all naked and exposed!  So in order to launch the powershell scripts we’re going to need to use a .bat or .cmd file launched from the run key in the registry.  So we’re going to add a string (REG_SZ) to






When you create the key you can call it whatever you like but the value has to be exactly right – and point to the script you want to launch.  In my case this is:



Cloudwyse Scripts


cmd /c START /MIN "Cloudwyse Env Execution" cmd /c "C:\Cloudwyse\Scripts\lch_powershell.cmd"



So I’m telling windows to launch a minimised command prompt, and then I’m passing the command I want running within that command prompt which means that users won’t have a big black box pop up on their screen everytime they log in.  Within that .cmd script, I need to launch Powershell but if I just go ahead and use the “powershell -File” command then I will hit issues with the execution policy within Windows which is disabled by default.  So we need the scripts to bypass the Powershell execution policy, but we don’t necessarily want to change the execution policy for the whole server for good.  So we can use this within the .cmd file:



@ECHO OFF SET CloudwyseScriptsDIR=C:\Cloudwyse\Scripts\

SET PSScriptPath=%CloudwyseScriptsDIR%wrapper.ps1

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PSScriptPath%""' -WindowStyle Hidden}";



So we’re asking Windows to launch powershell, temporarily bypassing the execution policy for the context of this command only.  Then we pass the command which also bypasses the execution policy, but this time within the context of the file we’re about to launch which is “wrapper.ps1”.

So now we have our Powershell wrapper script running automatically everytime a user logs in.  We can now nest within that script all the other powershell scripts we would also like to run by doing the following:



$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

. "$ScriptPath\date_check.ps1"

. "$ScriptPath\vmcheck.ps1"

. "$ScriptPath\IE_ESC.ps1"



Simply add a new line to this script for every logon script you want to run for users.

And if you’re wondering why the “$MyInvocation” variable doesn’t seem to be used anywhere, that’s because it’s an automatic variable.  There’s a great article on it here if you’re interested in learning more.




No comments:

Post a comment