Parameters
Parameters allow to pass values to the script.
Unnamed
set-strictMode -version latest
$first_argument = $args[0]
$second_argument = $args[1]
…
Named arguments
param (
$username,
$password
)
set-strictMode -version latest
…
Using named arguments has the benefit that the script user can invoke the script with explicitly named argument names:
.\the-script.ps1 -username rene -password theMostSecretSecret
Note: the
set-strictMode
must follow the
param
statement, otherwise, PowerShell will complain with the error message
param : The term 'param' is not recognized as the name of a cmdlet, function, script file, or operable program.….
Statements and keywords at the top of a script
If a script contains
using
statements, they need to be at the beginning of the script.
If the script also contains a
param
keyword (that defines the script's
parameters), it must be after the
using
statements (if any) and before the rest of the script.
Only after the
using
and
param
statements/keywords can the script have a
set-strictMode
cmdLet.
Abort a script when it encounters an unrecognized term
The following script contains a typo:
elsif
instead of
elseif
.
$errorActionPreference = 'stop'
set-strictMode -version latest
$v = 5
foreach ($i in 0 .. 10) {
if ( $v -gt $i ) {
write-host 'v > i'
}
elsif ($i -lt 7) {
write-host 'i < 7'
}
}
When the interpreter encounters the corresponding line, it does not recognize elsif
and consequently emits the error message The term 'elsif' is not recognized as a name of a cmdlet, function, script file, or executable program …
In order to abort a script when it encounters an unrecognized term, $errorActionPreference
must be set to stop
.
Determining script-name and script-path (within a script)
$myInvocation.myCommand.name | The script's file name |
$psScriptRoot | The directory (without script's file name) where script is located |
$psCommandPath | The complete path of the script (= directory + file name) |
$myInvocation.myCommand.path | Alternative to get complete path |
set-strictMode -version latest
write-host
write-host " The name of script's file is : $($myInvocation.myCommand.name)"
write-host " It is located in the directory : $psScriptRoot"
write-host
write-host " Thus, the complete path to the script is: $psCommandPath"
write-host
write-host " The directory can also be evaluated with"
write-host " `$myInvocation.myCommand.path : $($myInvocation.myCommand.path)"
write-host