How to Create and Run a PowerShell Script

In the earlier topics, we covered about PowerShell Comments, Determining PowerShell Version etc. It’s time to Create and Run a PowerShell Script.

Create a PowerShell Script

Let’s create a simple PowerShell script which will return the PowerShell version and the current Date.

#1. Open any editor like Notepad or Notepad++ and create a new file. Save the file as example.ps1. All the PowerShell files will have the extension as .ps1 so make sure you are saving the file by that extension.

#2. Let’s add simple commands into the Script. Basically, the below script returns the current date and time and the PowerShell version installed on the machine.

#3. Save the file

Run the PowerShell Script

Now that you have created the example.ps1 script its time to run and see the output of it. Before running the script you need to perform certain configurations. Check out the article on How to  Enable the Execution of the scripts in PowerShell.

There are basically 2 approaches to executing the script.

Approach 1: Run the Script from PowerShell Window

#1. Open the PowerShell using “Run as Administrator” mode.

#2. Navigate to the directory of the script which you have saved.

#3. Type the script name as ./<script_name.ps1> in our case it is ./example.ps1

Approach 2: Run the PowerShell Script from Command Prompt

#1. Open the command prompt in Administrator Mode.

#2. Type the command  PowerShell -noexit “& “”C:\Users\Desktop\example.ps1″””  Replace the C:\Users\Desktop\example.ps1 with the absolute path of your PowerShell script.

#3. You should get the output similar to the below screenshot.

Create and Run the PowerShell Script

Run PowerShell script from Command Line



You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *