Jump to content

Getting to Know: the iWay 9.2 Connector for Microsoft PowerShell


Recommended Posts

Microsoft PowerShell

PowerShell is a cross-platform task automation solution developed by Microsoft. PowerShell is built on the .NET Common Language Runtime (CLR) and is supported on Windows, Linux and iOS platforms.

PowerShell provides a command line runtime which:

  • accepts text parameters and returns text results.
  • accepts and returns .NET objects.
  • supports command and parameter aliases.
  • supports command pipelining.

The PowerShell scripting language:

  • is extensible through functions, classes, scripts and modules.
  • allows extensible formatting system for easy output.
  • supports dynamically created types.
  • built-in support for common formats (CSV, JSON and XML).

PowerShell was conceived to span a large set of functions, one of which is to be an automation platform. Due to its extensible nature, via a large ecosystem of modules, PowerShell is a powerful management tool for a number of popular technologies:

  • Azure
  • Windows
  • Exchange
  • SQL
  • AWS
  • VMWare
  • Google Cloud

iWay PowerShell Connector Purpose

The PowerShell connector provides iWay with the capability to run PowerShell commands and scripts, thus giving a flow the capacity to interact with the underlying platform via the CLR .NET provided objects. Due to the large set of features, it can be a very powerful tool usable in a wide range of situations.

Prerequisites

PowerShell needs to be installed on machine where iSM is running. To ensure consistent results, it is recommended to have the same PowerShell version installed on all the machines where iSM deployments are made. This also applies to cloud configurations where multiple docker images can run in parallel. All docker iSM images have to use the same PowerShell version as well.

For PowerShell installation and system prerequisites please consult Microsoft's official documentation available for the version of your choice.
As of this writing, for the latest version of PowerShell - 7.4 - you can find documentation at the following locations:

The installation instructions show the location of the PowerShell executable. Make a note of this since this is going to be used when configuring the PowerShell connectors.

PowerShell Connector Generic Configuration

Currently, to define a PowerShell generic configuration you need to specify two parameters:

  • PowerShell Connector Configuration Map
    PowerShell runs a command/script in a session. The way iSM handles a PowerShell session can be configured by specifying a list of key-value pairs (a map).
    This parameter is optional. There is no default configuration map provided by iSM, therefore in this instance a PowerShell session will use the PowerShell provided defaults.

    The PowerShell connector accepts two (mutually exclusive) types of configurations (generics) maps:

    • file-based configuration (discussed later): 

      image.png.e66aebc7e1cdb5daf5995c00149671a5.png
    • UI table-based configuration (discussed later)

      image.thumb.png.be845b191744aa9a2ce42c69025d7134.png
  • Location of the PowerShell Executable
    On a system multiple versions of PowerShell can co-exist. In order to differentiate among them a connector should be told which one to use. You must be aware of the scripting capabilities of the used PowerShell executable. It is recommended to not accept the default PowerShell provided via the PATH environment variable, but rather to point to the PowerShell executable you want to use. A typical (default) PowerShell executable location is C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe. This usually points to an older version.
    Other, more recent, PowerShell versions could be downloaded and installed following this link.

Supported Configuration Properties

The following PowerShell connector configuration properties can serve one of the following two purposes:

  • iSM handling of a PowerShell session
  • PowerShell session configuration

PowerShell Connector Properties:

  • waitPause: time iSM waits before starting to read the output of a PowerShell command. It is mostly used to avoid exceptions if output production is delayed.

    NOTE: this can also be passed as a PowerShell session input argument instead of as configuration argument

  • maxWait: maximum waiting time for the session to start.

  • tempFolder: location where a temporary copy of the script will be generated for execution. Note that a script is not executed from the location where it was provided, but it is rather copied to this folder where it is run by the PowerShell executable.

  • ConfigurationFile: Specifies a session configuration (.pssc) file path. The configuration contained in the configuration file will be applied to the PowerShell session.

  • ConfigurationName: Specifies a configuration endpoint in which PowerShell is run. This can be any endpoint registered on the local machine including the default PowerShell remoting endpoints, or a custom endpoint having specific user role capabilities.

    • This parameter is optional.

    For more on this topic see the official documentation

  • SettingsFile: Overrides the system-wide powershell.config.json settings file for the session. By default, system-wide settings are read from the powershell.config.json found in the $PSHOME directory.
     

               image.png.23e3ddbcc4f33bf25de866dc52fbc50f.png

    Note: these settings are not used by the endpoint specified by the -ConfigurationName argument.

    For more on this topic see the official documentation

  • WorkingDirectory: Sets the initial working directory for startup. Any valid PowerShell file path is supported. To start PowerShell in your home directory, use: pwsh -WorkingDirectory ~

    For more on this topic see the official documentation

  • ExecutionPolicy: Sets the default execution policy for the current session, and saves it in the $env:PSExecutionPolicyPreference environment variable.

    This parameter does not change any of the persisted configured execution policies. It only applies to Windows platforms. The $env:PSExecutionPolicyPreference environment variable does not exist on non-Windows platforms.

    • Default value: Bypass

    For more on this topic see the official documentation

NOTE: not all the above properties ara available in all PowerShell flavors. Using them when not supported may lead to exceptions or timeouts. It is recommended to first try out any scripts/commands using the command line executable as the connector. However, even if the result is positive in such cases there is not always a guarantee that it will work in iSM because of the way PowerShell manages the input/output streams under various settings.

 

PowerShell Connector File-Based Configuration

Besides the PowerShell executable location this configuration type allows a user to specify the location of a configuration file to be used to configure how iSM handles a PowerShell session.

Currently there are two supported file types: .json and .properties.

           image.png.569d6fe3408d1cdcfaaf8fcaafffd487.png

Configuration file examples:

JSON file:
  {
    "ConfigurationFile": "somePath",
    "tempFolder": "c:\\temp",
    ...
  }
Properties file:
  ConfigurationFile=C:\Temp\Config\config.file
  tempFolder=c:\temp
  ...

As opposed to the table-based configuration, this type of configuration is flexible and adaptable to deployments, just by allowing the modification/generation of the configuration file during the deployment.

 

PowerShell Connector Table-Based Configuration

This type of configuration allows a user to enter the key-value properties in an interactive fashion. These parameters are saved as part of the project.

While this configuration is in some ways easier to use due to the visual nature, it is not suggested to be used for deployments since the configuration data is saved in a project file, thus being relatively static in nature (however, register expressions can provide some level of configurability). For configurability purposes use PowerShell Connector File-Based Configuration.

image.thumb.png.f26b3972780592064affa9007739d025.png

 

PowerShell Connector Agents

Current implementation supports two types of connector agents:

  • PowerShell Command Execution - executes a PowerShell command
  • PowerShell Script Execution - executes a PowerShell script

The execution of a PowerShell command/script returns a success/failure status as well as the text output generated by the command/script.

Connector Configuration

Common Configuration Settings:

  • Both agents accept any of the two configurations described in PowerShell Connector Generic Configuration.

  • Command/Script

    • Script Parameters - single parameter line to be passed to the script/command. Accepts symbolic replacement.

      image.png.9d894f37bf8463bf9fd14d6c019dd6d7.png
      Command Parameters

      image.png.f19114469ee39bbeea65d4ed1e539980.png
      Script Parameters

  • Settings

    • Wait Time - waiting time (in milliseconds) until OnFailTimeout signal is issued. After this elapsed time the command/script is aborted.

      image.png.11d09b13fcba82465ab8b9c1a210c924.png
      Connector Settings

  • Output

    • Result Register - register where the text result of the command is stored

    • Tag - XML tag under which the text result is stored.

      Warning: In some PowerShell versions the output from certain commands may contain invalid XML characters. The output is stored in a register that ends up in a serializable XML document, thus storing invalid XML characters (entities) could lead to deserialization issues. PowerShell uses invalid XML characters for display formatting purposes (no bearing on the data). To avoid situations like this the agent filters all invalid XML characters before sending the output value to XML.
      In such cases it is strongly recommended to return in the output only that part of the result relevant to your application. You might need to explore PowerShell options to change the output format in order to make it easier to parse,
    • Embed - whether to embed the text result of the run into the input document

    • Parent Tag - where in the input document the text result of the run is to be embedded

    • Exit Register - (as powershell.output.exitRegister parameter) Register where the exit code from PowerShell execution is stored. In case of running simple commands, not scripts, this register is set to 1 upon failure to execute the specified command. However, this depends on how each individual command is implemented.
      If omitted the result is going to be ignored.
      IMPORTANT: scripts should use $host.SetShouldExit(<exitValue>) upon termination. <exitValue> is used to populate the Exit Register.
      Use this register as a decision parameter in your flow. Multiple success values (exit codes) are possible, each leading to a specific processing path.

    • Treat Exit As Error If Not Zero - (as powershell.output.treatExitAsError). If PowerShell exit code (the value set by $host.SetShouldExit(<someExitValue>)) is different than zero, and if this flag is true, then the execution will be treated as error and OnShellExecFail event is issued.
      Set this on true in situations where there is only one success code (zero), all other codes indicating some error.

      image.png.deb636615e6bac090c2f45e340c2dcb5.png

      Connector Output Parameters

    NOTE: the value of the exit command from a script is not returned to iSM. Therefore, make sure to use $host.SetShouldExit(<someExitValue>) in order to communicate to the connector any information/code relevant to the flow.

PowerShell Command Execution Settings

  • Action Name - Execute PowerShell Script - selects the PowerShell Command Connector
  • Command
    • Command - name of the command/executable to execute

      image.png.41f95b66736960b1d5682d8ef71f72b4.png

PowerShell Script Execution

  • Action Name - Execute PowerShell Command - selects the PowerShell Script Connector
  • Script
    • Script Path - absolute or relative path to the script file to be executed.

      image.png.dc2cb5169f873e055b8bbb86c92b77a7.png

Passing environment variables to scripts/commands

To pass environment variables to PowerShell you have to set them in the Run Configurations > Runtime > {Project} > Environment section before starting the JVM.
For instance, for TEMP to be available to PowerShell add TEMP = C:\Temp:

         image.png.4db7a27a1ffe0a3b51b4dd36168a68de.png

Inside the script use the environment variable could be used as follows:

$env:TEMP

Example: The following script accepts two parameters. The result will contain the name of the parameters followed by the speed in Mbit/sec.

Function Measure-NetworkSpeed{
	
	param (
		$param1,
		$param2
	)
	
    # The test file has to be a 10MB file for the math to work. If you want to change sizes, modify the math to match
    $TestFile  = 'https://ftp.sunet.se/mirror/parrotsec.org/parrot/misc/10MB.bin'

    # $env:TEMP must be passed to java environment variables to be populated here
    $TempFile  = Join-Path -Path $env:TEMP -ChildPath 'testfile.tmp'

    $WebClient = New-Object Net.WebClient
    $TimeTaken = Measure-Command { $WebClient.DownloadFile($TestFile,$TempFile) } | Select-Object -ExpandProperty TotalSeconds
    $SpeedMbps = (10 / $TimeTaken) * 8
    $Message = $param1 + " " + $param2 + " {0:N2} Mbit/sec" -f ($SpeedMbps)

	# returned result
	$Message
}

# invoke function and output function result
Measure-NetworkSpeed $args[0] $args[1]

# value to populate Exit Register
$host.SetShouldExit(23)

exit 0

Connectors Execution Paths

PowerShell connector execution can follow the following paths:

  • OnSuccess - path followed when the operation is successful

  • OnFailure - a failure condition encountered during execution

  • OnError - an exception encountered during execution

  • OnShellNotAvailable - PowerShell executable is not installed on the system or not reachable. Location of the executable can be adjusted in the generics (see PowerShell Connector Configuration/Generics)

  • OnShellExecFail - PowerShell execution returned false. This path is followed depending if the script execution failed. This depends on the value set by $host.SetShouldExit(<value>) invocation and Treat Exit As Error If Not Zero connector setting.

  • OnFailNotFound - issued when a resource - possibly a configuration file or script - was not found

  • OnFailTimeOut - issued when the PS command/script execution timed out

  • OnParseError - a parsing operation failed, most likely a configuration file format does not comply with the specifications.


    image.png.42a49d1aea156712c3c165e83eb1c0a3.png

Example

We will run the above script using the following settings:

  • Generics > PowerShell > PowerShell executable: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  • Generics > PowerShell > Connector Configuration: tempFolder=C:\Temp (where the script is copied before execution)
  • Run Configurations > Runtime > [Project] > Environment Variables: TEMP=C:\Temp
  • PowerShell Connector > Script Path: <Script Folder>\test.ps1 (point to the location where the script resides)
  • PowerShell Connector > Script parameters: Network and Speed
  • PowerShell Connector > Settings > Wait Time: 90000 ms (give script enough time to finish)
  • PowerShell Connector > Output"
    • Result Register: psout
    • Exit Code Register: exitCode
    • Treat Exit as Error if not Zero: true
    • Tag: psout
    • Embed: false
    • Parent Tag: Test

Console output:

>Apr 30, 2024 6:17:42 PM com.ibi.agents.powershell.PowerShell getConfigValue
WARNING: Powershell configuration value 'waitPause' not specified in configuration. Attempting to use internal configuration value '5'
Apr 30, 2024 6:17:42 PM com.ibi.agents.powershell.PowerShell getConfigValue
INFO: Powershell configuration value 'waitPause' set to '5'
Apr 30, 2024 6:17:42 PM com.ibi.agents.powershell.PowerShell getConfigValue
INFO: Powershell configuration value 'maxWait' set to '900000'
Apr 30, 2024 6:17:42 PM com.ibi.agents.powershell.PowerShell getConfigValue
INFO: Powershell configuration value 'tempFolder' set to 'C:\Temp'

If the script calls $host.SetShouldExit(0) (regardless to the exit value) then the Success event is issued and:

  • connector output:

    image.png.63fa712056ecdac76a5db36eb02b4e76.png
     
  • connector registers:

    image.png.7b0ad22b5e6a1062cd7545b80ec7b7a5.png

If the script calls $host.SetShouldExit(80) (regardless to the exit value) then the OnSHellExecFail event is issued and:

  • connector output is not set.
  • connector registers will look like:

    image.png.fe6d7a293acfe0b19465de812544435f.png


Setting Treat Exit as Error if not Zero: false for the last case the Success path is followed.

Final Considerations

Parsing Results Before Generating Output

Many commands supported by PowerShell issue string results. Depending on the situation, if the command does not offer a more concise way to relate the result, the output string may need to be parsed in order to retrieve the desired value.

For flow simplicity, it is recommended to parse and produce the parsed result in the script. Here it might help configuring the output format for the session. Thus, the output produced by get-service ZoomCptService:

Status   Name               DisplayName
------   ----               -----------
Running  ZoomCptService     Zoom Sharing Service

might need parsing in order to extract the Status that the flow needs for farther processing. In order to do so you can use the PowerShell parsing tools to process the output of the command according o your needs.

All Script/Command Output is Captured by the Connector

You should be aware that all the output from the script is captured by the connector and stored in the designated register.

For instance, let's imagine that the script used in the previous example ends with

$arg[0]

$arg[1]

# invoke function and output function result
Measure-NetworkSpeed $args[0] $args[1]

# value to populate Exit Register
$host.SetShouldExit(23)

exit 0

This will cause both script arguments to be sent to the output. In essence, any non-assignment operation that produces a return is sent to the output and captured by the PowerShell connector.

image.png

Edited by Corneliu Chirnoaga
  • Like 1
Link to comment
Share on other sites

  • Corneliu Chirnoaga changed the title to Getting to Know: the iWay 9.2 Connector for Microsoft PowerShell

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
  • Create New...