Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The following sample job explains how to use output channels for PowerShell such as:


 

Code Block
languagepowershell
titlePowerShell Job with different output channels
collapsetrue
<?xml version="1.0" encoding="ISO-8859-1"?>
<job  process_class="my_Agent" stop_on_error="no">
    <settings >
        <log_level ><![CDATA[debug1]]></log_level>
    </settings>

    <script  language="powershell">
        <![CDATA[
# Use Write-Host, Write-Output or Echo cmdlets to write to the JobScheduler log
Write-OutputHost "job: this is some output"
echoWrite-Output "job: this is some output"

# This does not work: Use of Write-Host cmdlet is not applicable
# Write-Host echo "job: this is some output"

# Standard PowerShell verbose setting is consideredused for log output
$VerbosePreference, consider script scope when modifying this variable
$script:VerbosePreference = "Continue"
Write-Verbose "job: this is some verbose output"

# Standard PowerShell debug setting is considered for log output
$DebugPreference = "Continue"
# In # In addition the current log level of the job has to be set, i.e.g. log level "debug1" or higher logs debugverbose messagesoutput
Write-DebugVerbose "job: this is some debugverbose output"

# createsStandard aPowerShell warningdebug forsetting the job
Write-Warning "job: this is a warning"

# can be used to throw an error
# Write-Error "job: this is an error"
        ]]>
    </script>

    <run_time />
</job>

Explanations

is used for log output, consider script scope when modifying this variable
$script:DebugPreference = "Continue"
# In addition the current log level of the job has to be set, i.e. log level "debug3" or higher logs debug messages
Write-Debug "job: this is some debug output"

# creates a warning for the job
Write-Warning "job: this is a warning"

# can be used to throw an error
Write-Error "job: this is an error"
        ]]>
    </script>

    <run_time />
</job>

Explanations

  1. Using PowerShell standard output
    • Use of the Write-HostWrite-Output and Echo cmdlets is applicable
    Using PowerShell standard output
    • Use of the Write-Output and Echo cmdlets is applicable.
    • Use of the Write-Host cmdlet is not applicable for PowerShell jobs as the cmdlet requires a PowerShell host console to be available (powershell.exe), whereas JobScheduler runs PowerShell in a process without interaction.
  2. Using PowerShell verbose output
    • The standard PowerShell verbosity setting is considered for log output if the job is configured for a log level debug1 or higher.
    • Use $script:VerbosePreference Use $VerbosePreference = "Continue" 
    • Subsequently use the Write-Verbose cmdlet.
  3. Using PowerShell debug messages
    • The PowerShell debug setting is considered for log output in jobs by use of if the job is configured for a log level debug3 or higher.
    • Use $script:DebugPreference $DebugPreference = "Continue"
    • In addition, the current log level of the job has to be set, e.g. log level debug1 will log debug messages.
      • With the JobScheduler log level being switched to info no debug output is written to the log file.
      • With the JobScheduler log level being switched to debug1debug2, ..., debug9 then debug output is added to the log.
  4. Using PowerShell Warnings
    • Warnings are created by use of the Write-Warning cmdlet. Such warnings create corresponding warnings in the JobScheduler Master that are visible from the log and that might trigger a notification by mail.
  5. Using PowerShell Error Messages
    • Use of the Write-Error cmdlet will create a job error that is visible from the log and that triggers subsequent actions as e.g. notification by mail, stopping the job, suspending an order etc. 

JobScheduler PowerShell CLI for Jobs

Info
  • The feature is only available in case your Agent is running on a machine with PowerShell available
  • For more information about how to install and to use the JobScheduler PowerShell CLI module for an Agent see PowerShell Command Line Interface - Introduction

 

    • Subsequently use the Write-Debug cmdlet.
  1. Using PowerShell Warnings
    • Warnings are created by use of the Write-Warning cmdlet. Such warnings cause corresponding warnings in the JobScheduler Master that are visible from the log and that might trigger a notification by e-mail.
  2. Using PowerShell Error Messages
    • Use of the Write-Error cmdlet will raise a job error that is visible from the log and that triggers subsequent actions as e.g. notification by e-mail, stopping the job, suspending an order etc. 

JobScheduler PowerShell CLI for Jobs

Info


The JobScheduler PowerShell CLI module is available for PowerShell jobs. A basic job using the PowerShell CLI might look like this:

...

  • The PowerShell CLI is activated by the Import-Module JobScheduler command.
  • For a complete list of cmdlets available from the PowerShell CLI see PowerShell CLI 1.1 - Cmdlets

Additional examples are available from the PowerShell CLI 1.1 - Use Cases article.

Parameter Handling

...

  • Parameter passing by environment variables is only available for PowerShell jobs that do not implement any of the API functions spooler_init(), spooler_exit(), spooler_process() etc.
    • Solution 1
      • $env:SCHEDULER_PARAM_NAME1 returns the respective parameter
  • A new object $spooler_params has been introduced 
    • The objects includes parameters from both job and order. For parameters with the same name an order parameter beats a job parameter.
    • The object includes the following methods:
      • Solution 2
        • $spooler_params.get( "name1" ) reads a parameter value
        • $spooler_params.value( "name1" ) is an alias for $spooler_params.get()
      • Solution 3
        • $spooler_params.getAll() returns a Variable_set with all job and order parameters.
      • Solution 4
        • $parameters = $spooler_params.items returns a PSObject that allows to access individual parameters as PowerShell properties
        • $parameters.name1 returns the parameter "name1" as property
  • The  usual API methods for parameters access are available:
    • Solution 5
      • $spooler_task.params().value( "name1" ) reads a job parameter

    • Solution 6
      • $spooler_task.order().params().value( "name1" ) reads an order parameter

...

  • Parameters are return
    • Solution 1
      • $spooler_params.set( "name1", "value2" ) 
        • sets a job parameter if the current job is configured as a standalone job
        • sets an order parameter if the current job is configured for a job chain.
    • Solution 2
      • $spooler_task.params().set_value( "name1", "value2" ) sets a parameter for a job (for instance parameter name1 with the initial value value1) and modifies the value to value2
    • Solution 3
      • $spooler_task.order().params().set_value( "name1", "value2" ) sets a parameter for an order (for instance parameter name1 with the initial value value1) and modifies the value to value2

Anchor
powershell-as-a-shell
powershell-as-a-shell
Compatibility between PowerShell and Shell

...

Code Block
# Example Shell: 
echo name1 = value2 >> %SCHEDULER_RETURN_VALUES%

# Example PowerShell solution 1: 
$spooler_task.order().params().set_value( "name1", "value2" )
# Example PowerShell solution 2: shorthand notation for task/order parameter 
$spooler_params.set( "name1", "value2" )

Error Handling

PowerShell jobs offer a number of options to detect run-time errors.

...

_task.order().params().set_value( "name1", "value2" )
# Example PowerShell solution 2: shorthand notation for task/order parameter 
$spooler_params.set( "name1", "value2" )

Execution Policies

By default PowerShell ships with the execution policy Restricted that does not allow to run scripts from files.

Should jobs be able to run external PowerShell script files then the execution policy has to be modified. This can be performed

  • at machine level, e.g. if an administrator executes Set-ExecutionPolicy RemoteSigned
  • at user level if the the user executes Set-ExecutionPolicy bypass -scope CurrentUser
  • at process level if the the user executes Set-ExecutionPolicy bypass -scope process

Should execution policies not be explicitly ruled for a scheduling environment then we recommend to add Set-ExecutionPolicy bypass -scope process to the profile on a Windows platform.

Profile Handling

Display feature availability
StartingFromRelease1.11.5

Profile Locations

JobScheduler handles PowerShell profiles in a similar way to the PowerShell host. 

  • The $PROFILE variable returns a collection of locations that a profile is looked up for. By default PowerShell would use four variables as stated below that are mapped by JobScheduler to two possible profile locations.
  • If a profile is found in a number of locations then all profiles are processed in the sequence as stated below. 

Profile locations (<agent_data> points to the data directory that is configured for an Agent, usually by use of the SCHEDULER_DATA environment variable with the Agent instance script):

  • $PROFILE.AllUsersAllHosts, $PROFILE.AllUsersCurrentHost
    • <agent_data>\config\powershell\JobScheduler.PowerShell_profile.ps1
  • $PROFILE.CurrentUserAllHosts, $PROFILE.CurrentUserCurrentHost
    • Agent/Job runs as system account: the same profile as stated above is processed
      • <agent_data>\config\powershell\JobScheduler.PowerShell_profile.ps1
    • Agent/Job runs as user account: the profile is looked up in the Users sub-directory for the current user (indicated by <user_name>).
      • <agent_data>\config\Users\<user_name>\powershell\JobScheduler.PowerShell_profile.ps1

For details check 

Jira
serverSOS JIRA
columnskey,summary,type,created,updated,due,assignee,reporter,priority,status,resolution
serverId6dc67751-9d67-34cd-985b-194a8cdc9602
keyJS-1746

Use of Profiles

Profiles can be used

  • to specify alias names for cmdlets,
  • to specify global variables, e.g. paths, that can be used by all jobs,
  • to import PowerShell modules, e.g. to specify Import-Module JobScheduler for use of the PowerShell CLI
  • to specify the behavior in case of errors by use of the $ErrorActionPreference variable
    • A value $ErrorActionPreference = "Continue" (Default) allows a PowerShell script to continue after an error occurred. It is up to the script developer to check for errors, e.g. by use of exceptions.
    • A value $ErrorActionPreference = "Stop" is the recommended setting as it immediately stops execution of the script after an error occurred.

Error Handling

PowerShell jobs offer a number of options to detect run-time errors.

Error handling by JobScheduler

Checking the exit code of PowerShell script

  • PowerShell scripts can use the exit() function to stop execution and to signal the execution result by specifying
    • exit(0) for successful execution
    • exit(1) or any non-zero numeric value
  • JobScheduler will report the value of the exit() function as the job execution result.

Checking the last exit code of a Windows program or script

  • If a native Windows program or script (.bat, .cmd) causes an error then this will assign the exit code to the $LastExitCode global variable
    • If a number of programs/scripts are executed from a PowerShell job then the result of the last program/script will decide about the exit code stored with $LastExitCode.
    • This behavior does not apply to cmdlets causing errors.
    • The behavior to stop script execution in case of an error by use of the $ErrorActionPreference does not apply to errors caused by programs/scripts but to PowerShell commands and cmdlets only.
  • JobScheduler checks this variable and will set the job exit code accordingly. For exit codes != 0 an error is raised.
  • This behavior is superior compared to shell jobs as errors from any line in the job script are detected. For shell scripts only the last line of a job script determines the execution result (Unix: $?, Windows: %ERRORLEVEL%).

...

  • Native Windows programs or scripts and cmdlets can cause errors that create some error output (stderr). 
  • PowerShell jobs can be configured to handle any output found in stderr to indicate an error. Not all output to stderr may indicate an error as a number of Windows native programs is reported to write to stderr instead of stdout. Therefore users can choose from the following configuration:stdout. Therefore users can choose from the following configuration:
    • <job stderr_log_level="error"/>
      • Indicates that any output found in stderr will result in a job error.
    • <job stderr_log_level="errorinfo"/>
      • Indicates that any output found in stderr will result in a job error.
      <job stderr_log_level="info"/>Indicates that output to stderr is logged but will not result in a job error (default)
      • output to stderr is logged but will not result in a job error (default).
  • Users should consider that output checking is performed after the job has completed. It can therefore not be used to stop execution of a script in case of error, however, we recommend to use output checking that would set the execution result of jobs in case of errors that are not handled by the script.
  • For details check 
    Jira
    serverSOS JIRA
    columnskey,summary,type,created,updated,due,assignee,reporter,priority,status,resolution
    serverId6dc67751-9d67-34cd-985b-194a8cdc9602
    keyJS-1329
     and 
    Jira
    serverSOS JIRA
    columnskey,summary,type,created,updated,due,assignee,reporter,priority,status,resolution
    serverId6dc67751-9d67-34cd-985b-194a8cdc9602
    keyJS-1393

...

  • By default PowerShell most cmdlets write errors to the stderr output channel that is captured by JobScheduler.
    • This does not include that a processing error is raised as in this situation the next line of the PowerShell job script would be executed.
  • Users can force PowerShell to throw an exeception in case of cmdlet errors
    • by setting the global variable $ErrorActionPreference = "Stop". This would stop processing immediately and prevent subsequent lines of the PowerShell job script from being executed. The value of this variable will be considered in case of cmdlet errors and in case of syntax errors, e.g. when using wrong parameterization for cmdlets. JobScheduler will detect this type of error. It is recommended to set this variable in the PowerShell Profile, see chapter Profile Handling.
    • by setting the -ErrorAction stop parameter provided that the cmdlet supports common parameters. The -ErrorAction parameter is not considered for syntax errors when using cmdlets, e.g. in case of wrong parameterization.

...

  • Users who wish to suppress exit codes of failed executions of native Windows programs or scripts can use
    • $LastExitCode $script:LastExitCode = $null
  • This will disable the above mentioned check of the last exit code.

...

Jira
serverSOS JIRA
columnstype,key,issuelinks,fixversions,status,priority,summary,updated
maximumIssues20
jqlQuerylabels in (scripting-powershell)
serverId6dc67751-9d67-34cd-985b-194a8cdc9602