Powershell

How to run PowerShell script

A PowerShell script can be defined as a plain text file containing PowerShell commands. PowerShell provides an Integrated Scripting Environment (ISE) to write and manage PowerShell scripts. PowerShell scripts comprise a series of cmdlets to automate/perform various tasks. The “.ps1” extension refers to the PowerShell scripts. A PowerShell script can be run using multiple ways. This post enlists all the possible methods to run a PowerShell script with the following learning outcomes:

Prerequisites

If you are using the PowerShell Scripting Environment for the first time, you may face the following error while executing a PowerShell script.

As you can see in the above output screenshot, the script execution is disabled on this system. To enable it, you need to open the PowerShell (with administrative privileges) and then execute the following command:

Set-ExecutionPolicy RemoteSigned

It can be observed from the above output that the execution policy has been changed successfully.

Method 1: How to run a script using PowerShell ISE?

There are several methods to run the PowerShell script, the two methods are as follows:

Go to the Start menu and select the Windows PowerShell ISE, and the Play (in Green) button is used to run the script.

According to the above-mentioned snippet, the script is running properly.

Copy the absolute path of the script file and paste it into the PowerShell terminal to run

Method 2: How to run a script using PowerShell console?

PowerShell provides the facilities to run the script from its terminal. To do so, you must provide the absolute path of the script as we did in the following command:

C:\Users\powershell\Documents\date1.ps1

According to the output screenshot, the script is executed and has returned the value in the proper way.

Method 3: How to run a script using Command Prompt (CMD)?

The PowerShell script can also be run from the CLI. The below-mentioned command will be used to execute the script. You have to use the “powershell” keyword with a “-file” parameter. After the “-file” parameter, add the absolute path of the script file with “.ps1”.

powershell -file "C:\Users\powershell\Documents\date1.ps1"

The output shows that the script has been executed successfully.

Great job! You have successfully enabled and run the PowerShell script from three different environments i.e., PowerShell ISE, PowerShell terminal, and CLI.

Conclusion

The PowerShell script can be run using the PowerShell console command prompt (CMD) or the PowerShell ISE console. We have demonstrated the possible methods to run a PowerShell script. The PowerShell script saves its scripting files with the extension “.ps1”. Prior to the execution of a script, the execution policy must be set to RemoteSigned.

About the author

Adnan Shabbir