How to create and run a PowerShell script file on Windows

By FoxLearn 2/20/2024 1:54:18 AM   325
PowerShell is a command line interface (CLI) for running commands and scripts to automate tasks and change settings on your device

Through this example you will learn how to write powershell scripts

Here's a simple example of a Windows PowerShell script that prompts the user for their name and then greets them

To create and run a PowerShell script, you can open Notepad or any text editor

# Prompt the user to enter their name
$name = Read-Host -Prompt "Please enter your name"

# Greet the user
Write-Host "Hello, $name! Welcome to PowerShell scripting."

then copy and paste the script above into the text editor

Save the file with a .ps1 extension, for example, my_script.ps1.

File extension for powershell script

The file extension for PowerShell scripts is typically ".ps1". When you create a PowerShell script, you would save it with a file name followed by the ".ps1" extension. For example, "myscript.ps1". This extension helps to identify the file as a PowerShell script, and it is recognized by PowerShell when you attempt to execute or run the script.

Opening your PowerShell, then navigate to the directory where you saved the script using the cd command.

Run the script by typing .\my_script.ps1 and pressing Enter.

This script simply reads input from the user, stores it in the variable $name, and then displays a greeting message using the Write-Host cmdlet.