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
1 |
[cc lang="dos"]HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run[/cc] |
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 | REG_SZ | 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:
1 |
[cc lang="dos"]@ECHO OFF SET CloudwyseScriptsDIR=C:\Cloudwyse\Scripts[/cc] |
1 |
[cc lang="dos"]SET PSScriptPath=%CloudwyseScriptsDIR%wrapper.ps1[/cc] |
1 |
[cc lang="dos"]PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PSScriptPath%""' -WindowStyle Hidden}";[/cc] |
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:
1 2 3 4 |
[cc lang="powershell"]$ScriptPath = Split-Path $MyInvocation.MyCommand.Path . "$ScriptPathdate_check.ps1" . "$ScriptPathvmcheck.ps1" . "$ScriptPathIE_ESC.ps1"[/cc] |
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.