Tuesday, May 6, 2014

Running local PowerShell scripts

Although I work with Linux primarily, any good system administrator always knows a little bit about the Other Operating System(tm).  One of the most useful thing to come out of Windows in years is PowerShell and running PowerShell scripts.  In Windows 8 (and 7 to an extent), there is a security feature that prevents any PS scripts from running non-interactively- something called the Execution Policy. 

Running a script will probably result in something like this: 

. : File C:\Users\jadmin\PowerShell\some-random-script.ps1 cannot be loaded because running scripts is disabled on
this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3
+ . .\some-random-script.ps1
+   ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

Get-ExecutionPolicy -List should return an output that may resemble this:

            Scope                                             ExecutionPolicy
            -----                                             ---------------
    MachinePolicy                                                   Undefined
       UserPolicy                                                   Undefined
          Process                                                   Undefined
      CurrentUser                                                   Undefined
     LocalMachine                                                RemoteSigned

When it is Undefined, it defaults to Restricted- which means no scripts are allowed to run.  By default, all levels are set to Undefined.  Here you can see LocalMachine is set to RemoteSigned.  You can set it per-process or per-user, which is neat but out of the scope of this blog post.

In order to allow your machine to run locally created PowerShell scripts, you'll need to open a PowerShell window as an Administrator (as easy as right-click, Run As Administrator).   UAC will prompt you (you didn't disable UAC, right?).  Next, type "Set-ExecutionPolicy RemoteSigned".  Type Y and hit Enter (or just hit Enter as "Y" is the default). 

Now you should be able to run locally created scripts.  

In many online resources, there are people advising you to set your ExecutionPolicy to Unrestricted.  This is a mistake, especially if only for locally created PowerShell scripts. Unrestricted allows anything to run as a script, including those from remote sources such as Outlook,  Internet Explorer, and so on.  If you happen to forget to set it back, you'll be at risk.