How to Run PowerShell Script: Simple Steps and Examples
To run a PowerShell script, open PowerShell and type
.\scriptname.ps1 where scriptname.ps1 is your script file. Make sure your execution policy allows running scripts by setting it with Set-ExecutionPolicy if needed.Syntax
To run a PowerShell script, use the following syntax:
.\scriptname.ps1: Runs the script namedscriptname.ps1in the current directory.Set-ExecutionPolicy: Changes the policy to allow script execution if blocked.
The .\ means the current folder, so PowerShell knows where to find your script.
powershell
.\scriptname.ps1
Example
This example shows how to create and run a simple PowerShell script that prints a greeting message.
powershell
Write-Output "Hello, PowerShell!"Output
Hello, PowerShell!
Common Pitfalls
Common mistakes when running PowerShell scripts include:
- Not using
.\before the script name, which causes PowerShell to not find the script. - Execution policy blocking scripts. By default, PowerShell may prevent scripts from running.
- Running scripts without proper permissions.
To fix execution policy issues, run PowerShell as administrator and use:
Set-ExecutionPolicy RemoteSigned
This allows running local scripts safely.
powershell
Wrong: scriptname.ps1 Right: .\scriptname.ps1
Quick Reference
| Command | Description |
|---|---|
| .\scriptname.ps1 | Run script in current directory |
| Set-ExecutionPolicy RemoteSigned | Allow running local scripts |
| Get-ExecutionPolicy | Check current execution policy |
| powershell -File scriptname.ps1 | Run script from command line |
Key Takeaways
Always use .\ before the script name to run it from the current folder.
Check and set execution policy with Set-ExecutionPolicy to allow scripts to run.
Run PowerShell as administrator if you need to change execution policy.
Use Write-Output in scripts to display messages.
Use Get-ExecutionPolicy to verify your current script running permissions.