This article is to help with those having issues executing sctipts file with Powershell in Windows 10.
If you want to run a script file(.ps1) with PowerShell, you might get an error message like this(see figure 1):
Why this error occured?
Because Windows PowerShell has a security built-in setting called "Execution Policy". This policy is created for safety concerns, and it can help prevent the execution of suspicious scripts. By default, execution policy is set to Restricted, and this means local scripts are not allowed to run in PowerShell. Therefore, we need to change the default settings.
How to change the default settings?
Open Start menu. Search for PowerShell, right-click the Windows PowerShell and click the Run as administrator option.(see figure 2)
*You must have administraor permission to change the execution policy, otherwise you will get an error.
Type the following command to allow scripts to run and press Enter:
Type A and press Enter (if applicable), it will take effect to all .ps1 file in your computer.(see figure 3)
Type the path of your saved script file and press Enter:
[In this case, I opened the Sample.ps1 which stored in a folder named PowerShell, F drive.]
(see figure 4)
*Remember to change the path to the location of your script. To do that, you can right click your scrtipts and go "Propertes", copy the location and paste in the PowerShell.(see figure 5)
After you complete all the steps, the script will start running, and if it was crafted correctly, you should see its output without issues. In my Sample.ps1, the correct output is”Your scripts executed successfully!”(see figure 6)
How to Restore the default settings
The above steps are to use the command to change the execution policy and allow local scripts to run in Windows 10. But if you are not planning to run scripts regularly, you can also restore the default settings to prevent any untrusted scripts running on your computer.
It's pretty the same with the above steps, but you need to change the cmdlet in step No.2, make sure to use the Set-ExecutionPolicy Restricted cmdlet (see figure 7).
You can click here to view Microsoft Execution Policies, it describes the PowerShell execution policies and explains how to manage them.
Hopefully this article can help you solve the issues.
Script - a programming language for a special run-time environment that automates the execution of tasks
cmdlet - Pronounced "command-let" is a special type of command provided in the Windows PowerShell command line environment.