In the earlier topics, we covered 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 that 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 an 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.
Write-Host "Details of PowerShell Version"
Get-Host
Write-Host "---------------------------"
Write-Host "Current Date and Time is"
Get-Date
#3. Save the file
Run the PowerShell Script
Now that you have created the example.ps1 script it’s 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.
