Creating and Executing Powershell Scripts

Writing your first PowerShell script can be pretty easy. Just open notepad and paste in:

Write-Host "Hello World!"

Save that as a .ps1 file and you’re are all set. That line will just print out Hello World! to the console.

Now, how do you run that script?

First, you open up Windows PowerShell. Browse to the location where you script is, and type the name of the script.

If this is your first time running a PowerShell script, chances are you will see an error message like this:

PS C:\Users\user\Desktop> .\HelloWorld.ps1
File C:\Users\user\Desktop\HelloWorld.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:17
+ .\HelloWorld.ps1 <<<<
+ CategoryInfo : NotSpecified: (:) [], PSSecurityException
+ FullyQualifiedErrorId : RuntimeException

This is because PowerShell is pretty locked down to prevent unauthorized scripts from running.

Chances are you will be fine with:

Set-ExecutionPolicy Unrestricted

Just paste that into the PowerShell console and hit Y, enter, when prompted.

If you are concerned about setting the PowerShell Execution level to Unrestricted, you can choose the level that is correct for you:

  • Restricted – No scripts can be run. Windows PowerShell can be used only in interactive mode.
  • AllSigned – Only scripts signed by a trusted publisher can be run.
  • RemoteSigned – Downloaded scripts must be signed by a trusted publisher before they can be run.
  • Unrestricted – No restrictions; all Windows PowerShell scripts can be run.

Now that you have allowed scripts you should now be able to kick off your script.

PS C:\Users\user\Desktop> .\HelloWorld.ps1
Hello World!

Resources:
http://technet.microsoft.com/en-us/library/ee176961.aspx

0 Responses to “Creating and Executing Powershell Scripts”


  • No Comments

Leave a Comment