Executing Scripts
Let’s start by creating a simple script and executing it. The following code is placed in a file named myScript.ps1.
# One-line comments in scripts are written after a number sign.
$args
<#
Block Comments can be written over
multiple lines.
#>
The script starts with a comment, which is preceded by a # sign to indicate it is a comment. Next, it uses the automatic variable $args
to display the arguments passed to the script. It ends with a block
comment, which is written over multiple lines and enclosed with <# and #> characters.
Run the script as follows:
PS > .\myScript.ps1 "hey" "hey" "my" "my"
hey
hey
my
my
Windows
PowerShell does not execute scripts in the current directory by
default. You need to explicitly tell Windows PowerShell that the script
is placed in the current directory by typing .\ before the script name.
Alternatively, you can type its full path:
PS > C:\Scripts\myScript.ps1 "hey" "hey"
hey
hey
If the directory name contains whitespace, you can use the call operator (&) to execute the script. Here’s an example:
PS > & 'C:\My Scripts\myScript.ps1' "hey"
hey
Using Parameters in Scripts
The param statement is used to add parameters to scripts. The param
statement must be the first executed line of code in a script (except
for comments or comment-based help). Script parameters work in the same
way as function parameters.
The following shows a basic script using parameters.
param([string]$firstname, [string]$lastname)
"FirstName: $firstname"
"LastName: $lastName"
We can execute the script by typing .\, the script name (myScript.psi in this example), followed by the parameters.
PS > .\myScript.ps1 -firstname Niklas -lastname Goude
FirstName: Niklas
LastName: Goude