How to Write Your First PowerShell Script

Though there are many great scripting languages out there, we’re going to spend our time with PowerShell. If you’re using a recent version of Microsoft Windows, you’ve probably already got a version of it installed.

How do I create a PowerShell script?

PowerShell saves scripts in the .ps1 format. I have created both a file and a folder for our demonstration

C:\Scripts\My First Script.ps1

but please feel free to use your own custom folder and filenames.

Edit your file and add the following line:

Write-Host "Hello, World!"
hello world powershell script

Save the file and return to the PowerShell window. In order to run the script, the most common method is by calling it:

& "C:\Scripts\My First Script.ps1"

Go ahead and try that command. You should get an error that says scripts have been disabled on your system.

powershell scripts disabled

This is normal behavior. In order to prevent malicious scripts from running on your system, PowerShell enforces an execution policy. There are 4 execution policies you can use:

  • Restricted – Scripts won’t run. Period. (Default setting)
  • RemoteSigned – Locally-created scripts will run. Scripts that were created on another machine will not run unless they are signed by a trusted publisher.
  • AllSigned – Scripts will only run if signed by a trusted publisher (including locally-created scripts).
  • Unrestricted – All scripts will run regardless of who created them and whether or not they are signed.

In order to use our newly-created script, we will have to modify our execution policy to allow our script to run. Since we have not digitally signed our new script, our options for setting the execution policy are left to “RemoteSigned” and “Unrestricted.” We are going to change it to RemoteSigned.

In order to change the execution policy, we will need to reopen PowerShell as an Administrator (the command will fail otherwise) and run the following command:

Set-ExecutionPolicy RemoteSigned

The Set-ExecutionPolicy command will ask to verify that you really want to change the execution policy. Go ahead and select Y for yes, then go ahead and close and reopen your Powershell window.

After restarting the Powershell window, go ahead and try running that script again

& "C:\Scripts\My First Script.ps1"

It should write back, “Hello, World!” to the window:

hello world powershell script

Congratulations! You just wrote your first PowerShell script!

As this blog series continues, we’ll continue to add more helpful tips on how to use PowerShell. In the meantime, you know have the amazing power to create and run your own scripts.

We invite you to check out our list of PowerShell Commands to get familiar with how PowerShell operates.