Remotely tweak powershell execution policies without powershell remoting.

Today I was trying to schedule a powershell command to execute via scheduled task on all my machines.  Copied the powershell script to execute on all the machines ran a for loop as follows to create the scheduled tasks on all the machines.

for /f %i in (\\utilityserver\servers.txt) do schtasks /s %i /create /TN custom_task /TR "powershell -nologo -file c:\localbin\task.ps1" /ST 16:00 /SC MINUTE /MO 5 /RU <Domain\user> /RP "XXXXX"

The tasks were created fine on all the machines but when I tried to run , it failed. Tried executing the powershell script locally on a server and it threw me a error message about execution policy. Now I have to enable the execution policy on around 100 servers which unfourtunately did not have powershell remoting setup. When you set a execution policy in powershell it actually modifies registry value for ExecutionPolicy at the following location.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell ( I found this by running procmon) .

If you have a unrestricted policy your registry will read like this

reg query  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell

    Path    REG_SZ    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    ExecutionPolicy    REG_SZ    Unrestricted

Now to set this across 100 machines

for /f %i in (\\utilityserver\servers.txt) do reg add \\%i\HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell /v ExecutionPolicy /t REG_SZ /d Unrestricted /f

Replace the value with Unrestricted | RemoteSigned | AllSigned | Restricted | Bypass which ever you want to set. This key will set the execution policy for all the users on a machine. You can also use the set-execution policy cmdlet if you have powershell remoting setup.

This will save you a bunch of time , or I will suggest you make this a part of your build process.