Create and Run Script

In one of the previous sessions we have seen that, if you open Windows PowerShell (not Windows PowerShell ISE) command prompt you can write multiple commands/statements by pressing SHIFT + ENTER keys. Once you finish with your set of statements you can press ENTER and it will execute one by one statement and will show output.

Issue with above method is, set of statements which you write on Windows PowerShell command prompt would not be available for future use.

So let's look at how we can store set of statements/commands and how we can execute that script (set of statements/commands) later.

Click on start menu, search for Windows PowerShell ISE, right click on that and click on "Run as Administrator".

By default it opens empty script with name Untitled1.ps1.

Write set of commands in the Untitled1.ps1 file or copy below statements

Example
$totalMarks = 663;             	    # full number example
$totalSubject = 7;                  # decimal number example

Write-host 'Total Percentage: '($totalMarks / $totalSubject);

Click on "Run" icon or press F5, it will show output "Total Percentage: 94.7142857142857"

If you run script first time on your system you may get error like "execution of scripts is disabled on this system". If you get this error you can fix it by executing command `Set-ExecutionPolicy Unrestricted`.
There are four different types of execution policy in PowerShell:

  • Restricted: If this policy is set then any script can't be executed.
  • RemoteSigned: If this policy is set then only downloaded script from the Internet can be executed and those scripts must be signed by the trusted publisher.
  • Unrestricted: If this policy is set then any type of script can be executed.
  • AllSigned: If this policy is set then only signed by a trusted publisher script can be executed.
Default policy of Windows PowerShell is "restricted", so to run above script we need to change it to "Unrestricted" by using command `Set-ExecutionPolicy Unrestricted`.

Now if you want to use this script in future then save this script file using File > Save or press CTRL + S or click on Save icon on toolbar, it will open save dialog where you can give name e.g. CalculatePercentage.ps1 to the script and save it at desired location.

You can close the Windows PowerShell ISE if your work is over.

Let's see how we can reuse above saved script

Now if you want to reuse saved script "CalcualtePercentage.ps1", open Windows PowerShell ISE as an Administrator.

Click on File > Open or press CTRL + O or click on Open icon, it will show "Open" dialog box from where you can choose your file and click on "Open" button

It will load saved script in Windows PowerShell ISE script window.

Now run that script same as above by pressing F5 or clicking on "Run" icon on toolbar.

 

← Previous

Next →