Well-executed PowerShell commands can accomplish a lot, but sometimes we must perform complex tasks requiring multiple commands. In such cases, we can write a PowerShell script and run it in the terminal when needed.
To run a script, we open up any text editor, write our commands and name the file with a .ps1
file extension.
For example, the following commands can be put into a script file called host-commands.ps1.
Write-Host "All commands that act on Host:" Get-Command -Noun Host
With these two commands in the host-commands.ps1 file, we can now run our script using the following command in the terminal:
.\host-commands.ps1
This will run the script and produce the following output:
All commands that act on Host: CommandType Name ----------- ---- Function Clear-Host Cmdlet Get-Host Cmdlet Out-Host Cmdlet Read-Host Cmdlet Write-Host
The .\
notation before the script name tells the shell to look for a file in the current directory and run it. In most shells, the forward slash notation ./
may also be used.
Instructions
There is now a script file, script.ps1. Use this script to print out a prompt and then the current date.
To start, on the first line of script.ps1 use Write-Host
to output a prompt about the date. Something like The Current Date Is:
When you are done, click Run.
On the second line of script.ps1 use Get-Date
to output the current date.
When you are done, click Run.
Now in the terminal, run your script with:
.\script.ps1