There are at least two different approaches to pass parameters to a PowerShell script:
- as command line arguments
- as environment variables
As an example for both methods we will use a simple script which will list the content of a folder, filtered by a given filename extension. The parameters are defines in an order like this:
FolderName ist the name of the folder that should be listed and FileNameExtension is the value of the extension that will be selected.
The script code, without the initialisation of the parameters, is given below:
Using Command Line Parameters
Using Position Parameters
We do not recommend using parameters like this:
- Depending on the parameters every job will be different.
- No general solution for a generic PowerShell job is possible. This will increase the effort for maintenance of jobs.
- In Addition, accessing a parameter by its position can lead to errors
- if someone changes the command line arguments without adjusting the script or
- if the same script will be used by different jobs with different command line arguments.
- The better approach is to use the parameters by name.
Using Named Parameters
Starting a script like below:
and the first statement in the script is the param statement:
will fill the variable Prefix with the Value
Using Environment Variables
JobScheduler provides parameters of jobs and orders as environment variables to a shell.
Using Explicit Variables
The command line that is used to start the script, would not make use of additional parameters for the script:
Instead, the script retrieves the parameter values by reading the environment variable for each parameter (see How to pass parameters from JobScheduler to a PowerShell script):
Defining all required variables at the beginning of the script will give one an overview, which variables are used from JobScheduler. In other words, this could be part of an integrated automatic documentation.
Using by parsing all environment variables
JobScheduler provide more environment variables as the one which are related to a parameter. it is possible to get all this variables as "internal" named variables into the powerscript.
The script below shows how it works:
Executing this script standalone or as part of another script it will parse all environment variables and create for each variable with the prefix
SCHEDULER_PARAM_ a PowerShell variable. For example, the environment variable SCHEDULER_PARAM_FOLDERNAME is then accessible by the script as $FOLDERNAME.
- The advantage of using parameters from environment variables is that access to parameters is effected by the name of the parameter, not by its position on the command line.
- This would allow to create a generic job to run PowerShell scripts.
- How to execute a PowerShell script with JobScheduler
- Why can't JobScheduler execute Windows PowerShell scripts?
- How to get the exit code of a PowerShell script
- How to configure a generic PowerShell job