First Windows Powershell script

In this topic, you will learn how to create a simple a Powershell script and execute it. Remember that script is nothing but list of commands. The script has an extension as .ps1

You can add the comments in script by prefixing the line with # symbol.

Create a simple file with name “s1.ps1” with below command in it.

dir

Now to execute this script, you need to fire below command from the command prompt.

> ./s1.ps1

You may get below error saying “script can not be loaded because running scripts is disabled”  if execution policy is not set properly. By default, Powershell has a “Restricted” execution policy. So you are not allowed to run any “.ps1” script in it.

There are 4 Execution Policies in Powershell.

  1. Restricted : This policy does not allow you to run any script in Powershell.
  2. AllSigned : This policy allows you to run only signed scripts from trusted publishers. You will be asked for confirmation before running script.
  3. RemoteSigned : This policy lets you run local unsigned scripts. You will not be asked for confirmation before running script.
  4. Unrestricted : This policy let you execute local as well as remote unsigned scripts. You will not be asked for confirmation before running script.

You can see your current execution policy using below syntax.

Get-ExecutionPolicy

You can change the current execution policy using below syntax.
Set-ExecutionPolicy <Policy-Name>

To run our script, we will be setting our policy to “RemoteSigned”. Note that you should start the Powershell as an Administrator to execute below command.

Set-ExecutionPolicy RemoteSigned

After that, you can run your Powershell script using below syntax. You should see the list of directories in output.

> ./s1.ps1

 

You may also like...