Monday, July 25, 2011

Run-Script

As I mentioned in an earlier post, just like the DOS command line has batch files, PowerShell can run PowerShell script files.  These have the .PS1 extension.

So go ahead, throw a bunch of PowerShell commands together into a .PS1 file in NotePad and save it.  Next, navigate to the folder you saved it to and double-click on it.  Awesome, you just ran your first PowerShell script!  What do you mean it didn’t run?  It came up in NotePad?

Oh yeah.  By default, for security reasons, double-clicking on a PowerShell script doesn’t run it.  To do that you have a couple of options.  First is to open up PowerShell and run the script from PowerShell's command line.  To do that you simply  type:

C:\MyScripts\MyCoolScript.ps1

If your current folder is already C:\MyScripts you’ll type:

.\MyCoolScript.ps1

Note that we prefaced the script file with “.\”.  Without that, PowerShell thinks it’s a built-in command and yells that it doesn’t recognize it.

OK, you’ve typed it in, hit enter and away it goes, no?  Except that all you see is:

File C:\MyScripts\MyCoolScript.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
At line:1 char:11
+ .\test.ps1 <<<<
    + CategoryInfo          : NotSpecified: (:) [], PSSecurityException
    + FullyQualifiedErrorId : RuntimeException

$%!#$%!^&*#…OK, ok, breath…again…deep breath…Yet another security “feature”.  With this one type at the command line:

Set-ExecutionPolicy RemoteSigned
Or
Set-ExecutionPolicy Unrestricted

You only need to run this once and it will allow you to run scripts.  When setting RemoteSigned, any local scripts will run as-is, but remote scripts will need to be digitally signed.  Like Enable-PSRemoting, you’ll need to open PowerShell as administrator.

But I’m not an administrator!  The execution policy is not a true security setting, it’s simply there to help prevent the inadvertent running of malicious scripts.  You can actually set the execution policy when you open PowerShell from the command line by using the –ExecutionPolicy argument, using the same RemoteSigned or Unrestricted value.  This will only set the execution policy for that session.

Note that when using the Set-ExectuionPolicy you can set the scope of the setting using the –Scope argument to be either the current process (-Scope Process, same as setting it on the command line), current User (-Scope CurrentUser) or the local machine (-Scope LocalMachine).  The default value is LocalMachine.

No comments:

Post a Comment