How to Run a PowerShell Script

Rohan Timalsina Feb 02, 2024
  1. Use ./script_name to Run a PowerSell Script in PowerShell
  2. Use Complete Path to Run a PowerShell Script in PowerShell
  3. Use cmd.exe to Run a PowerShell Script
  4. Use -File Parameter to Run a PowerShell Script in cmd.exe
  5. Use the bypass switch to Run a PowerShell Script in cmd.exe
  6. Use type Command to Run a PowerShell Script in cmd.exe
How to Run a PowerShell Script

A PowerShell script is a collection of commands saved in a .ps1 extension file. PowerShell executes the commands written in .ps1 file.

We have created a PowerShell script named myscript.ps1, which contains the below command.

Write-Host "Your script is executed successfully."

Output:

Your script is executed successfully.

The above output should be displayed when executing a myscript.ps1. This tutorial will introduce different methods to run a PowerShell script.

Use ./script_name to Run a PowerSell Script in PowerShell

You need to be in the directory where the script file is located to use this method. cd command is used to change the working directory in PowerShell. After navigating to the directory of a script file, run ./script_name.

For example, our script file is located in C:\New.

cd C:\New

Then run a script.

./myscript.ps1

Output:

Your script is executed successfully.

Use Complete Path to Run a PowerShell Script in PowerShell

You do not need to change the working directory in this method. You can provide the complete path of a script file to run it.

C:\New\myscript.ps1

Output:

Your script is executed successfully.

Use cmd.exe to Run a PowerShell Script

You can run a PowerShell script from the command prompt. -noexit argument is not mandatory. It keeps the console open because PowerShell exits after the script is finished.

powershell -noexit C:\New\myscript.ps1

Output:

Your script is executed successfully.

Use -File Parameter to Run a PowerShell Script in cmd.exe

The -File parameter allows you to invoke a script from another environment, like cmd.exe.

powershell -File C:\New\myscript.ps1

Output:

Your script is executed successfully.

Use the bypass switch to Run a PowerShell Script in cmd.exe

You can use the bypass switch to run a PowerShell script without modifying the default script execution policy.

powershell -executionpolicy bypass -File C:\New\myscript.ps1

Output:

Your script is executed successfully.

Use type Command to Run a PowerShell Script in cmd.exe

You can also use the type command to run a PowerShell script in cmd.

type "C:\New\myscript.ps1" | powershell -c -

Output:

Your script is executed successfully.
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Script