05 / REUSABLE AUTOMATION · LESSON 17

Save a script you can reuse

Write a parameterised script and run it with different inputs.

10 min · learn at your pace

A file becomes a tool

A .ps1 file contains PowerShell code. The lab editor saves your code as /home/user/main.ps1 before running it.

Use param() at the beginning of a script to declare its inputs:

param([string]$Name = 'Operations')
"Hello, $Name"

The default value is used when the caller omits that parameter.

Invoke the script

From the terminal, the call operator & runs a script at a path:

& './main.ps1' -Name 'Platform'

Normally a called script has its own scope. Dot-sourcing, written . './main.ps1', runs it in the current scope, which is useful when loading functions. The lesson editor uses dot-sourcing so definitions remain available in the terminal.

PowerShell on your own computer may apply execution-policy rules to script files. This browser lab has its own compatibility policy; do not assume its settings describe your Windows environment.

A clear parameter name and a useful default make a script easier to use without opening its source every time.

Try an example.ps1
param([string]$Name = 'Operations')
"Hello, $Name"
YOUR TURN

Put it into practice.

Write a script with a string parameter Name that defaults to ops. Output Hello, followed by the name. It must also work with -Name Platform.

See an explained solution
One way to solve it.ps1
param([string]$Name = 'ops')
"Hello, $Name"

The same script now supports different callers. Omitting Name uses ops; passing -Name Platform overrides that default.