psrpcore

PSRP Runspace and Pipeline objects.

Contains the Runspace and Pipeline objects used for the PowerShell Remoting Protocol.

class psrpcore.ApplicationPrivateDataEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Application Private Data Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool

Message Type: psrpcore.types.ApplicationPrivateData

Action Required: Share with higher layer

The server generates this data automatically when receiving an psrpcore.types.InitRunspacePool or psrpcore.types.ConnectRunspacePool message from the client.

property data: Dict[str, Any]

The private data dictionary returned from the server.

class psrpcore.ClientGetCommandMetadata(*args: Any, **kwargs: Any)

Client Get Command Metadata Pipeline.

A Get Command Metadata pipeline to be used from the client.

Parameters:
  • runspace_pool (ClientRunspacePool) – The Runspace Pool the pipeline is a member off.

  • name (str | List[str]) – List of command names to get the metadata for. Uses * as a wildcard.

  • command_type (CommandTypes) – The type of commands to filter by.

  • namespace (List[str] | None) – Wildcard patterns describbing the command namespace to filter by.

  • arguments (List[Any] | None) – Extra arguments passed to the higher-layer above PSRP.

  • pipeline_id (UUID | None) – Manually set the Pipeline ID, used when reconnecting to an existing Pipeline.

class psrpcore.ClientHostResponder(connection: ClientRunspacePool | ClientPowerShell | ClientGetCommandMetadata)

Client Host Responser.

Helper class that can be used to response to runspace and pipeline host calls. Each method is named after the corresponding host method identifer and document the required values that need to be set to respond to the hsot call for that request.

Parameters:

connection (ClientRunspacePool | ClientPowerShell | ClientGetCommandMetadata) – The client Runspace Pool or Pipeline to response on.

get_background_color(ci: int, color: ConsoleColor) None

GetBackgroundColor Response.

Responds to psrpcore.types.HostMethodIdentifier.GetBackgroundColor with the background color of the host.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • color (ConsoleColor) – The background color of the host.

get_buffer_contents(ci: int, cells: List[List[BufferCell]]) None

GetBufferContents Response.

Responds to psrpcore.types.HostMethodIdentifier.GetBufferContents with contents of the buffer that was requested.

The cells value is a list of a list of psrpcore.types.BufferCell where the first list dimension represents each row and the 2nd dimension is each column of that row.

Note

PowerShell does not implement this call for security reasons. Unless you trust the target host you should not return this information, or sanitise the data as needed.

Parameters:
  • ci (int) – The call id the response is for.

  • cells (List[List[BufferCell]]) – A list of a list of cells.

get_buffer_size(ci: int, width: int, height: int) None

GetBufferSize Response.

Responds to psrpcore.types.HostMethodIdentifier.GetBufferSize with the size of the buffer of the host. The size is measured in character cells which can contain a 16-bit Char.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • width (int) – The number of cells the fit the width of the buffer.

  • height (int) – The number of cells that fit the height of the buffer.

get_current_culture(ci: int, culture: str) None

GetCurrentCulture Response.

Responds to psrpcore.types.HostMethodIdentifier.GetCurrentCulture with the host’s culture, like en-US.

Note

For pwsh this value is typically static and set by the server on creation. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • culture (str) – The host culture.

get_current_ui_culture(ci: int, culture: str) None

GetCurrentUICulture Response.

Responds to psrpcore.types.HostMethodIdentifier.GetCurrentUICulture with the host’s UI culture, like en-US. The UI culture is used for operations like loading resource files.

Note

For pwsh this value is typically static and set by the server on creation. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • culture (str) – The host UI culture.

get_cursor_position(ci: int, x: int, y: int) None

GetCursorPosition Response.

Responds to psrpcore.types.HostMethodIdentifier.GetCursorPosition the coordinates of the cursor in the host.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • x (int) – The X (horizontal) coordinate of the cursor.

  • y (int) – The Y (vertical) coordinate of the cursor.

get_cursor_size(ci: int, size: int) None

GetCursorSize Response.

Responds to psrpcore.types.HostMethodIdentifier.GetCursorSize with the size (as a percentage) of the cursor.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • size (int) – The size, as a percentage, of the host cursor.

get_foreground_color(ci: int, color: ConsoleColor) None

GetForegroundColor Response.

Responds to psrpcore.types.HostMethodIdentifier.GetForegroundColor with the foreground (text) color of the host.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • color (ConsoleColor) – The foreground color of the host.

get_instance_id(ci: int, instance_id: UUID) None

GetInstanceId Response.

Responds to psrpcore.types.HostMethodIdentifier.GetInstanceId with a unique identifier of the host.

Note

For pwsh this value is typically static and set by the server on creation. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • instance_id (UUID) – The host identifier.

get_is_runspace_pushed(ci: int, is_pushed: bool) None

GetIsRunspacePushed Response.

Responds to psrpcore.types.HostMethodIdentifier.GetIsRunspacePushed with whether the runspace is pushed or not.

Note

For pwsh this value is typically static and set by the server on creation. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • is_pushed (bool) – The runspace is pushed or not.

get_key_available(ci: int, waiting: bool) None

GetKeyAvailable Response.

Responds to psrpcore.types.HostMethodIdentifier.GetKeyAvailable with whether the host is waiting on input.

Parameters:
  • ci (int) – The call id the response is for.

  • waiting (bool) – Host is waiting on input.

get_max_physical_window_size(ci: int, width: int, height: int) None

GetMaxPhysicalWindowSize Response.

Responds to psrpcore.types.HostMethodIdentifier.GetMaxPhysicalWindowSize with the maximum physical size of the window of the host. The size is measured in character cells which can contain a 16-bit Char.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • width (int) – The number of cells the fit the max physical width of the window.

  • height (int) – The number of cells that fit the max physical height of the window.

get_max_window_size(ci: int, width: int, height: int) None

GetMaxWindowSize Response.

Responds to psrpcore.types.HostMethodIdentifier.GetMaxWindowSize with the maximum size of the window of the host. The size is measured in character cells which can contain a 16-bit Char.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • width (int) – The number of cells the fit the max width of the window.

  • height (int) – The number of cells that fit the max height of the window.

get_name(ci: int, name: str) None

GetName Response.

Responds to psrpcore.types.HostMethodIdentifier.GetName with a human friendly host name identifier.

Note

For pwsh this value is typically static and set by the server on creation. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • name (str) – The host name to respond.

get_version(ci: int, version: str | PSVersion) None

GetVersion Response.

Responds to psrpcore.types.HostMethodIdentifier.GetVersion with the version of the host.

Note

For pwsh this value is typically static and set by the server on creation. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • version (str | PSVersion) – The version of the host.

get_window_position(ci: int, x: int, y: int) None

GetWindowPosition Response.

Responds to psrpcore.types.HostMethodIdentifier.GetWindowPosition the coordinates (from the top left point) of the host window.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • x (int) – The X (horizontal) coordinate of the host window.

  • y (int) – The Y (vertical) coordinate of the host window.

get_window_size(ci: int, width: int, height: int) None

GetWindowSize Response.

Responds to psrpcore.types.HostMethodIdentifier.GetWindowSize with the size of the window of the host. The size is measured in character cells which can contain a 16-bit Char.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • width (int) – The number of cells the fit the width of the window.

  • height (int) – The number of cells that fit the height of the window.

get_window_title(ci: int, title: str) None

GetWindowTitle Response.

Responds to psrpcore.types.HostMethodIdentifier.GetWindowTitle with the title of the host window.

Note

For pwsh this value is set when the server creates the host based on the host default data. It is rare for this to be requested by the server.

Parameters:
  • ci (int) – The call id the response is for.

  • title (str) – The title of the window.

prompt(ci: int, choices: Dict[str, Any]) None

Prompt Response.

Responds to psrpcore.types.HostMethodIdentifier.Prompt with the values for field that was entered.

Parameters:
  • ci (int) – The call id the response is for.

  • choices (Dict[str, Any]) – The response with the key being the name of the field and the value is the value entered for that field.

prompt_for_choice(ci: int, choice: int) None

PromptForChoice Response.

Responds to psrpcore.types.HostMethodIdentifier.PromptForChoice with the choice that was slected.

Parameters:
  • ci (int) – The call id the response is for.

  • choice (int) – The choice that was selected. This is a 0 based index of selected choice from the host call.

prompt_for_credential(ci: int, credential: PSCredential) None

PromptForCredential Response.

Responds to psrpcore.types.HostMethodIdentifier.PromptForCredential1 or psrpcore.types.HostMethodIdentifier.PromptForCredential2 with the credential that was entered.

Parameters:
  • ci (int) – The call id the response is for.

  • credential (PSCredential) – The credential that was entered.

prompt_for_multiple_choice(ci: int, choices: int | List[int]) None

PromptForChoiceMultipleSelection Response.

Responds to psrpcore.types.HostMethodIdentifier.PromptForChoiceMultipleSelection with the choices that were selected.

Parameters:
  • ci (int) – The call id the response is for.

  • choices (int | List[int]) – The choices that were selected. Each choice is a 0 based index of the selected choice from the host call.

read_key(ci: int, character: int | str | ~psrpcore.types._primitive.PSChar, key_down: bool, control_key_state: ~psrpcore.types._host.ControlKeyStates = <ControlKeyStates.none: 0>, key_code: int = 0) None

ReadKey Response.

Responds to psrpcore.types.HostMethodIdentifier.ReadKey with key that was inputted onto the host.

Parameters:
  • ci (int) – The call id the response is for.

  • character (int | str | PSChar) – The character (UTF-16 16-bit char) that was inputted.

  • key_down (bool) – Generated by a key press True or release False.

  • control_key_state (ControlKeyStates) – State of the control keys.

  • key_code (int) – Device-independent key code value.

read_line(ci: int, line: str) None

ReadLine Response.

Responds to psrpcore.types.HostMethodIdentifier.ReadLine with the line that was read.

Parameters:
  • ci (int) – The call id the response is for.

  • line (str) – The line that was read.

read_line_as_secure_string(ci: int, line: PSSecureString) None

ReadLineAsSecureString Response.

Responds to psrpcore.types.HostMethodIdentifier.ReadLineAsSecureString with the line as a secure string that was read.

Parameters:
  • ci (int) – The call id the response is for.

  • line (PSSecureString) – The line that was read as a secure string.

class psrpcore.ClientPowerShell(*args: Any, **kwargs: Any)

Client PowerShell Pipeline.

A PowerShell pipeline to be used from the client. This is the main pipeline class used by the client to start a pipeline on the server.

Parameters:
  • runspace_pool (ClientRunspacePool) – The Runspace Pool the pipeline is a member off.

  • add_to_history (bool) – Whether to add the pipeline to the history field of the runspace.

  • apartment_state (ApartmentState | None) – The apartment state of the thread that executes the pipeline.

  • history (str | None) – The value to use as a historial reference of the pipeline.

  • host (HostInfo | None) – The host information to use when executing the pipeline.

  • is_nested (bool) – Whether the pipeline is nested in another pipeline or not.

  • no_input (bool) – Whether there is any data to be input into the pipeline.

  • remote_stream_options (RemoteStreamOptions) – Whether to add invocation info the the PowerShell streams or not.

  • redirect_shell_error_to_out (bool) – Redirects the global error output pipe to the commands error output pipe.

  • pipeline_id (UUID | None) – Manually set the Pipeline ID, used when reconnecting to an existing Pipeline.

add_argument(value: Any) ClientPowerShell

Adds argument to the last command.

Adds a positional argument to the last command in the pipeline.

Parameters:

value (Any) – The argument to add.

Returns:

itself

Return type:

ClientPowerShell

add_command(cmdlet: str | Command, use_local_scope: bool | None = None) ClientPowerShell

Adds a command

Adds a command to the current statement.

Parameters:
  • cmdlet (str | Command) – The command as a string or Command object.

  • use_local_scope (bool | None) – Whether the command is run under local scope or not.

Returns:

itself

Return type:

ClientPowerShell

add_parameter(name: str | None, value: Any = True) ClientPowerShell

Adds a parameter to the last command.

Adds a parameter to the last command in the pipeline. A switch parameter can either have True, False, or None as the value with None being equivalent to False.

Parameters:
  • name (str | None) – The name of the parameter to add.

  • value (Any) – The value to set for the parameter.

Returns:

itself

Return type:

ClientPowerShell

add_parameters(**parameters: Any) ClientPowerShell

Adds parameters to the last command.

Like ClientPowerShell.add_parameter() this adds multiple parameters to the last command in the pipeline. The key word arguments corresponds to the parameters to add.

Parameters:

parameters (Any) – The parameters to add as kwargs.

Returns:

itself

Return type:

ClientPowerShell

add_script(script: str, use_local_scope: bool | None = None) ClientPowerShell

Adds a script.

Adds a script to the current statement. A script is essentially a scriptblock containing the PowerShell code to execute.

Parameters:
  • script (str) – The script to add.

  • use_local_scope (bool | None) – Whether the command is run under local scope or not.

Returns:

itself

Return type:

ClientPowerShell

add_statement() ClientPowerShell

Adds a statement.

Adds a statement to the pipeline. A statement can be used to separate multiple commands and scripts as separate statements rather than pipeline commands.

Returns:

itself

Return type:

ClientPowerShell

class psrpcore.ClientRunspacePool(*args: Any, **kwargs: Any)

Client Runspace Pool.

Represents a Runspace Pool on a remote host which can contain one or more running pipelines. This is a non blocking connection object that handles the incoming and outgoing PSRP packets without worrying about the IO. This model is inspired by Sans-IO model where this object deals with only the PSRP protocol and needs to be combined with an IO transport separately.

This is meant to be a close representation of the System.Management.Automation.Runspaces.RunspacePool .NET class.

Parameters:
  • application_arguments (Dict[str, Any] | None) – Arguments that are sent to the server and accessible through $PSSenderInfo.ApplicationArguments of a pipeline that runs in this Runspace Pool.

  • apartment_state (ApartmentState) – The apartment state of the thread used to execute commands within this Runspace Pool.

  • host (HostInfo | None) – The HostInfo that describes the client hosting application.

  • thread_options (PSThreadOptions) – Determines whether a new thread is created for each invocation.

  • min_runspaces (int) – The minimum number of Runspaces a pool can hold.

  • max_runspaces (int) – The maximum number of Runspaces a pool can hold.

  • runspace_pool_id (UUID | None) – Manually set the Runspace Pool ID, used when reconnecting to an existing Runspace Pool.

connect() None

Connects to the Runspace Pool.

This connects to a disconnected Runspace Pool on the peer.

exchange_key() None

Exchange session specific key.

Request the session key from the peer.

get_available_runspaces() int

Get the number of Runspaces available.

This builds a request to get the number of available Runspaces in the pool. The psrpcore.GetRunspaceAvailabilityEvent event is returned once the response is received from the server.

Returns:

The command id for this request.

Return type:

int

host_response(ci: int, return_value: Any | None = None, error_record: ErrorRecord | None = None) None

Respond to a host call.

Respond to a host call event with either a return value or an error record. It is recommended to use psrpcore.ClientHostResponder to respond to host calls as it will format the return values from a .NET type

Parameters:
  • ci (int) – The call ID associated with the host call to response to.

  • return_value (Any | None) – The return value for the host call.

  • error_record (ErrorRecord | None) – The error record raised by the host when running the host call.

open() None

Opens the Runspace Pool.

This opens the Runspace Pool on the peer.

reset_runspace_state() int

Reset the Runspace Pool state.

Resets the variable table for the Runspace Pool back to the default state. This requires the server to be running with PowerShell v5 or newer. Older versions will fail with InvalidProtocolVersion.

Returns:

The command id for this request.

Return type:

int

set_max_runspaces(value: int) int | None

Set the maximum number of runspaces.

Build a request to set the maximum number of Runspaces the pool maintains. The max_runspaces property is updated once the SetMaxRunspacesEvent is received.

Parameters:

value (int) – The maximum number of runspaces in a pool to change to.

Returns:

The command id for this request or None if no

request was created.

Return type:

Optional[int]

set_min_runspaces(value: int) int | None

Set the minimum number of runspaces.

Build a request to set the minimum number of Runspaces the pool maintains. The min_runspaces property is updated once the SetMinRunspacesEvent is fired.

Parameters:

value (int) – The minimum number of runspaces in a pool to change to.

Returns:

The command id for this request or None if no

request was created.

Return type:

Optional[int]

class psrpcore.ClixmlOutput(output: list[~typing.Any] = <factory>, error: list[~psrpcore.types._complex.ErrorRecord] = <factory>, debug: list[~psrpcore.types._complex.DebugRecord] = <factory>, verbose: list[~psrpcore.types._complex.VerboseRecord] = <factory>, warning: list[~psrpcore.types._complex.WarningRecord] = <factory>, progress: list[~psrpcore.types._complex.ProgressRecord] = <factory>, information: list[~psrpcore.types._complex.InformationRecord] = <factory>)

CLIXML output collection.

Helper class that can be used to parse raw CLIXML strings into separated object collections.

An example of how this can be used to get objects back from PowerShell:

import subprocess

import psrpcore

res = subprocess.run(
    ['pwsh', '-OutputFormat', 'xml', '-Command', 'Get-Process -Id $pid'],
    text=True,
    capture_output=True,
    check=True,
)
out = psrpcore.ClixmlOutput.from_clixml([res.stdout, res.stderr])

for obj in out.output:
    print(obj.Name)
debug: list[DebugRecord]

Objects from the debug stream.

error: list[ErrorRecord]

Objects from the error stream.

classmethod from_clixml(clixml: str | list[str]) ClixmlOutput

Parse the CLIXML string into objects.

Parsed the provided CLIXML string into their various strings and process well known output formats for each stream into a canonical type.

Parameters:

clixml (str | list[str]) – The raw CLIXML string to parse. This can be a list of strings if the CLIXML comes from multiple sources like stdout and stderr.

Returns:

The processed CLIXML objects and the streams they

were associated with.

Return type:

ClixmlOutput

information: list[InformationRecord]

Objects fr om the information stream.

output: list[Any]

Objects from the output stream.

progress: list[ProgressRecord]

Objects from the progress stream.

verbose: list[VerboseRecord]

Objects from the verbose stream.

warning: list[WarningRecord]

Objects from the warning stream.

class psrpcore.ClixmlShell

Helper class for PowerShell minishell.

This is a helper class that can be used to collect streams inside Python and emit the final CLIXML string for stdout/stderr that PowerShell can read. It is useful for exchanging richer objects between PowerShell and Python processes.

The data_to_send() function can be used to get the stream values as a CLIXML string to write to stdout. While this can be called multiple times PowerShell won’t emit the records until the process ends.

import sys

import psrpcore

class MyObj:
    def __init__(self) -> None:
        self.value = 123
        self.other = "foo"

shell = psrpcore.ClixmlShell()
shell.write_output("foo")
shell.write_output({"foo": "bar"})
shell.write_output(MyObj())

sys.stdout.write(shell.data_to_send())

In PowerShell the above Python script can be called with:

$out = python my_script.py
$out[0]  # foo
$out[1].foo  # bar
$out[2].value  # 123
$out[2].other  # foo

The PowerShell process must be capturing the output in some way, for example through a variable or redirection/pipelining.

data_to_send() str

Gets the CLIXML output string.

Returns the string that should be written to stdout. This string is CLIXML string that contains the serialized streams provided to this shell.

Returns:

The string to write to stdout.

Return type:

str

write_debug(value: str) None

Write to debug stream.

Writes the string to the debug stream. The emitted value is written in PowerShell through $host.UI.WriteDebugLine($value) and not as an actual DebugRecord.

Parameters:

value (str) – The string to write.

write_error(value: str | ErrorRecord) None

Write to error stream.

Writes the string or psrpcore.types.ErrorRecord to the error stream.

Parameters:

value (str | ErrorRecord) – The string or ErrorRecord to write.

write_information(value: str | InformationRecord) None

Write to information stream.

Writes the string or psrpcore.types.InformationRecord to the error information stream.

Parameters:

value (str | InformationRecord) – The string or InformationRecord to write.

write_output(value: Any | None) None

Write to output stream.

Writes the value to the output stream. The value can be any object that is automatically translated according to the psrpcore serialization rules.

Parameters:

value (Any | None) – The value to write to the output stream.

write_progress(source_id: int, value: ProgressRecord) None

Write to progress stream.

Writes the psrpcore.types.ProcessRecord to the progress stream. The emitted value is written in PowerShell through $host.UI.WriteProgress($sourceId, $value) and not as an actual ProgressRecord.

Parameters:
  • source_id (int) – Unique identifier of the source of the record.

  • value (ProgressRecord) – The ProgressRecord to write.

write_verbose(value: str) None

Write to verbose stream.

Writes the string to the verbose stream. The emitted value is written in PowerShell through $host.UI.WriteVerboseLine($value) and not as an actual VerboseRecord.

Parameters:

value (str) – The string to write.

write_warning(value: str) None

Write to warning stream.

Writes the string to the warning stream. The emitted value is written in PowerShell through $host.UI.WriteWarningLine($value) and not as an actual WarningRecord.

Parameters:

value (str) – The string to write.

class psrpcore.Command(*args: Any, **kwargs: Any)

Pipeline Command.

Defines a Command object which can be added to a Pipeline for invocation.

Parameters:
  • name (str) – The command name or script contents.

  • is_script (bool) – If the command represents a script or command.

  • use_local_scope (bool | None) – The command is run in local scope or not.

command_text

The command name or script.

is_script

See args.

use_local_scope

See args.

parameters

List of parameters to invoke with the command.

end_of_statement

Whether the command is the last one in the current statement or not.

merge_unclaimed

Set as the merge point for any error records generated by previous commands in the statement.

add_argument(value: Any) Command

Add a positional argument to the command.

add_parameter(name: str | None, value: Any = True) Command

Add a parameter and value to the command.

add_parameters(**parameters: Any) Command

Adds mutliple parameters to the command.

property merge_debug: PipelineResultTypes

What stream to send debug records to.

property merge_error: PipelineResultTypes

What stream to send error records to.

property merge_information: PipelineResultTypes

What stream to send information records to.

property merge_my: PipelineResultTypes

Used for v2 compatibility to merge error to output/null.

property merge_to: PipelineResultTypes

Used for v2 compatibility to merge error to output/null.

property merge_verbose: PipelineResultTypes

What stream to send verbose records to.

property merge_warning: PipelineResultTypes

What stream to send warning records to.

redirect_all(stream: ~psrpcore.types._complex.PipelineResultTypes = <PipelineResultTypes.Output: 1>) None

Redirects all streams.

Redirects all the non-output streams to the targeted stream. The target stream can only be none, Output, or Null.

Parameters:

stream (PipelineResultTypes) – The stream to redirect to.

redirect_debug(stream: ~psrpcore.types._complex.PipelineResultTypes = <PipelineResultTypes.Output: 1>) None

Redirect the debug stream to this.

redirect_error(stream: ~psrpcore.types._complex.PipelineResultTypes = <PipelineResultTypes.Output: 1>) None

Redirect the error stream to this.

redirect_information(stream: ~psrpcore.types._complex.PipelineResultTypes = <PipelineResultTypes.Output: 1>) None

Redirect the information stream to this.

redirect_verbose(stream: ~psrpcore.types._complex.PipelineResultTypes = <PipelineResultTypes.Output: 1>) None

Redirect the verbose stream to this.

redirect_warning(stream: ~psrpcore.types._complex.PipelineResultTypes = <PipelineResultTypes.Output: 1>) None

Redirect the warning stream to this.

class psrpcore.ConnectRunspacePoolEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Connect Runspace Pool Event.

Event Information:

Direction: Client -> Server

For: Runspace Pool

Message Type: psrpcore.types.ConnectRunspacePool

Action Required: Send responses back to the client

The client sends this message when attempting to connect to a disconnected Runspace Pool. The server will generate the psrpcore.types.RunspacePoolInitData, psrpcore.types.ApplicationPrivateData, and psrpcore.types.RunspacePoolStateMsg to send back to the client.

property max_runspaces: int | None

The maximum number of runspaces in the Runspace Pool.

property min_runspaces: int | None

The minimum number of runspaces in the Runspace Pool.

class psrpcore.CreatePipelineEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Create Pipeline Event.

Event Information:

Direction: Client -> Server

For: Pipeline

Message Type: psrpcore.types.CreatePipeline

Action Required: Process pipeline

The client sends this message when invoking a new pipeline. There are no responses automatically generated to send back to the client as it is up to the server to invoke when there are available resources.

property pipeline: PowerShell

The PowerShell pipeline details.

class psrpcore.DebugRecordEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Debug Record Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool or Pipeline

Message Type: psrpcore.types.DebugRecordMsg

Action Required: Send to higher layer

The server sends this message when there is a debug record generated by the server. The data should be shared with the higher layer as necessary.

property record: DebugRecord

The DebugRecord emitted by the peer.

class psrpcore.EncryptedSessionKeyEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Encrypted Session Key Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool

Message Type: psrpcore.types.EncryptedSessionKey

Action Required: None - secure strings can now be serialized

The server sends this message after processing the psrpcore.types.PublicKey message from the client. It contains the encrypted session key used when serializing psrpcore.types.PSSecureString objects.

property key: bytes

The session key generated by the peer.

class psrpcore.EndOfPipelineInputEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

End Of Pipeline Input Event.

Event Information:

Direction: Client -> Server

For: Pipeline

Message Type: psrpcore.types.EndOfPipeline

Action Required: Server notifies the pipeline that no more input is to be expected.

The client sends this message once it has finished sending all the input for the pipeline.

class psrpcore.ErrorRecordEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Error Record Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool or Pipeline

Message Type: psrpcore.types.ErrorRecordMsg

Action Required: Send to higher layer

The server sends this message when there is an error record generated by the server. The data should be shared with the higher layer as necessary.

property record: ErrorRecord

The ErrorRecord emitted by the peer.

class psrpcore.GetAvailableRunspacesEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Get Available Runspaces Event.

Event Information:

Direction: Client -> Server

For: Runspace Pool

Message Type: psrpcore.types.GetAvailableRunspaces

Action Required: Send response back to the client

The client sends this to request the number of available runspaces in the Runspace Pool. The server automatically generates the psrpcore.types.RunspaceAvailability as a response to the client.

property ci: int

The call id associated with the request.

class psrpcore.GetCommandMetadataEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Get Command Metadata Event.

Event Information:

Direction: Client -> Server

For: Pipeline

Message Type: psrpcore.types.GetCommandMetadata

Action Required: Process pipeline

The client sends this message when requesting command metadata in a Runspace Pool. There are no responses automatically generated to send back to the client as it is up to the server to process when there are available resources.

property pipeline: GetMetadata

The GetCommandMetadata pipeline details.

class psrpcore.GetMetadata(*args: Any, **kwargs: Any)

Get Command Metadata Pipeline.

This implements the GetCommandMetadata pipeline specific methods used to get command metadata information.

Parameters:
  • name (str | List[str]) – List of command names to get the metadata for. Uses * as a wildcard.

  • command_type (CommandTypes) – The type of commands to filter by.

  • namespace (List[str] | None) – Wildcard patterns describbing the command namespace to filter by.

  • arguments (List[Any] | None) – Extra arguments passed to the higher-layer above PSRP.

class psrpcore.GetRunspaceAvailabilityEvent(message_type: PSRPMessageType, ps_object: RunspaceAvailability, runspace_pool_id: UUID, pipeline_id: None = None)

Get Runspace Availability Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool

Message Type: psrpcore.types.RunspaceAvailability

Action Required: Send to higher layer

The server sends this message in resposne to a psrpcore.types.GetAvailableRunspaces message.

property count: int

The available runspaces specified by the server.

class psrpcore.InformationRecordEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Information Record Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool or Pipeline

Message Type: psrpcore.types.InformationRecordMsg

Action Required: Send to higher layer

The server sends this message when there is an information record generated by the server. The data should be shared with the higher layer as necessary.

property record: InformationRecord

The InformationRecord emitted by the peer.

class psrpcore.InitRunspacePoolEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Init Runspace Pool Event.

Event Information:

Direction: Client -> Server

For: Runspace Pool

Message Type: psrpcore.types.InitRunspacePool

Action Required: Send responses back to the client

The client sends this message when attempting to open a new Runspace Pool. The server will generate the psrpcore.types.ApplicationPrivateData and psrpcore.types.RunspacePoolStateMsg to send back to the client.

property apartment_state: ApartmentState

The apartment state specified by the peer.

property application_arguments: Dict[str, Any]

Higher layer application arguments provided by the peer.

property host_info: HostInfo

The PSHost info provided by the peer.

property max_runspaces: int

The maximum number of runspaces in the Runspace Pool.

property min_runspaces: int

The minimum number of runspaces in the Runspace Pool.

property ps_thread_options: PSThreadOptions

The PowerShell thread options specified by the peer.

exception psrpcore.InvalidPipelineState(action: str, current_state: T, expected_states: List[T])

The Pipeline is not in the required state.

exception psrpcore.InvalidProtocolVersion(action: str, current_version: PSVersion, required_version: PSVersion)

The protocolversion of the peer does not meet the required version.

property message: str
exception psrpcore.InvalidRunspacePoolState(action: str, current_state: T, expected_states: List[T])

The Runspace Pool is not in the required state.

exception psrpcore.MissingCipherError

Trying to (de)serialize a Secure String but no cipher was provided.

property message: str
exception psrpcore.PSRPCoreError

Base error for any PSRP errors.

class psrpcore.PSRPEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

PSRP Event.

Represents an event based on the various PSRP messages that can be received from a peer. It contains information such as the Runspace Pool and Pipeline the event is targeted towards as well as the raw PSObject received for further parsing.

Parameters:
  • message_type (PSRPMessageType) – The psrpcore.types.PSRPMessageType that identifies the message type.

  • ps_object (T1) – The message received from the peer.

  • runspace_pool_id (UUID) – The Runspace Pool the event is for.

  • pipeline_id (T2) – The Pipeline the event is for, otherwise None when the event is just for the Runspace Pool.

message_type

See args.

runspace_pool_id

See args.

pipeline_id

See args.

classmethod create(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2 | None = None) PSRPEvent

Creates an event for the specific message types - used internally.

class psrpcore.PSRPPayload(data: bytes, stream_type: StreamType, pipeline_id: UUID | None)

The PSRP data payload that is exchanged between the client and server.

data: bytes

The raw data to be exchanged with the client and server.

pipeline_id: UUID | None

The pipeline id if the data is related to a Pipeline or None for a Runspace Pool.

stream_type: StreamType

The type of data that is contained.

class psrpcore.PSRemotingCrypto

PSCryptoProvider used by PSRP for serializing SecureStrings.

decrypt(value: str) str

Decrypts the encrypted value.

Decrypts the encrypted value passed in. The value provided is the raw XML element text of the <SS> element to decrypt.

Parameters:

value (str) – The encrypted XML text element to decrypt.

Returns:

The decrypted value.

Return type:

str

encrypt(value: str) str

Encrypted the bytes.

Encrypts the value passed in and returns the raw XML <SS> element for serialization.

Parameters:

value (str) – The string to encrypt.

Returns:

The encrypted and encoded XML text element.

Return type:

str

register_key(key: bytes) None
class psrpcore.PipelineHostCallEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Pipeline Host Call Event.

Event Information:

Direction: Server -> Client

For: Pipeline

Message Type: psrpcore.types.PipelineHostCall

Action Required: Send to higher layer for processing

The server sends this message when requesting the host to invoke a psrpcore.types.HostMethodIdentifier method. It is up to the client to send this information to the higher layer and send back a response if required.

property ci: int

The call id associated with the request.

property method_identifier: HostMethodIdentifier

The method that needs to be invoked.

property method_parameters: List[Any]

List of parameters to invoke the method with.

class psrpcore.PipelineHostResponseEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Pipeline Host Response Event.

Event Information:

Direction: Client -> Server

For: Pipeline

Message Type: psrpcore.types.PipelineHostResponse

Action Required: Send to higher layer for processing

The client sends this message in response to a PipelineHostCallEvent. It contains the host response information that is processed by the higher layer.

property ci: int

The call id associated with the request.

property error: ErrorRecord | None

The error record if the host call failed.

property method_identifier: HostMethodIdentifier

The method that was invoked.

property result: Any | None

The result (if any) from the host call.

class psrpcore.PipelineInputEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Pipeline Input Event.

Event Information:

Direction: Client -> Server

For: Pipeline

Message Type: Any

Action Required: Send to higher layer for processing

The client sends any input it desires for the pipeline. It is sent to the higher layer to be used with the running Pipeline.

property data: Any

The data sent as input.

class psrpcore.PipelineOutputEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Pipeline Output Event.

Event Information:

Direction: Server -> Client

For: Pipeline

Message Type: Any

Action Required: Send to higher layer for processing

The server sends this message when there is output generated from the Pipeline. The data should be shared with the higher layer as necessary.

property data: Any

The data sent as output.

class psrpcore.PipelineStateEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Pipeline State Event.

Event Information:

Direction: Server -> Client

For: Pipeline

Message Type: psrpcore.types.PipelineState

Action Required: Send to higher layer for processing

The server sends this msg in response to a pipeline state change. The client should share this with the higher layer which checks whether it is Failed and use the reason to see why it did.

property reason: ErrorRecord | None

An error record containing the reason why the pipeline is Failed.

property state: PSInvocationState

The Pipeline state.

class psrpcore.PowerShell(*args: Any, **kwargs: Any)

PowerShell Pipeline.

This implements the PowerShell pipeline specific methods used to invoke a PowerShell pipeline.

Parameters:
  • add_to_history (bool) – Whether to add the pipeline to the history field of the runspace.

  • apartment_state (ApartmentState | None) – The apartment state of the thread that executes the pipeline.

  • history (str | None) – The value to use as a historial reference of the pipeline.

  • host (HostInfo | None) – The host information to use when executing the pipeline.

  • is_nested (bool) – Whether the pipeline is nested in another pipeline or not.

  • no_input (bool) – Whether there is any data to be input into the pipeline.

  • remote_stream_options (RemoteStreamOptions) – Whether to add invocation info the the PowerShell streams or not.

  • redirect_shell_error_to_out (bool) – Redirects the global error output pipe to the commands error output pipe.

class psrpcore.ProgressRecordEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Progress Record Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool or Pipeline

Message Type: psrpcore.types.ProgressRecordMsg

Action Required: Send to higher layer

The server sends this message when there is a progress record generated by the server. The data should be shared with the higher layer as necessary.

property record: ProgressRecord

The progress record emitted by the peer.

class psrpcore.PublicKeyEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Public Key Event.

Event Information:

Direction: Client -> Server

For: Runspace Pool

Message Type: psrpcore.types.PublicKey

Action Required: Send response back to the client

The client sends this message when it requests the encrypted session key used when serializing psrpcore.types.PSSecureString objects. The server automatically generates the psrpcore.types.EncryptedSessionKey as a response to the client.

property key: bytes

The public key bytes from the peer.

class psrpcore.PublicKeyRequestEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Public Key Request Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool

Message Type: psrpcore.types.PublicKeyRequest

Action Required: Send response back to the server

The server sends this message when it wants to serialize a psrpcore.types.PSSecureString object. The client automatically generates the psrpcore.types.PublicKey as a response to the server.

class psrpcore.ResetRunspaceStateEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Reset Runspace State Event.

Event Information:

Direction: Client -> Server

For: Runspace Pool

Message Type: psrpcore.types.ResetRunspaceState

Action Required: Send to higher layer

The client sends this message when it wants to reset the Runspace Pool state.

property ci: int

The call id associated with the request.

class psrpcore.RunspacePoolHostCallEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Runspace Pool Host Call Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool

Message Type: psrpcore.types.RunspacePoolHostCall

Action Required: Send to higher layer for processing

The server sends this message when requesting the host to invoke a psrpcore.types.HostMethodIdentifier method. It is up to the client to send this information to the higher layer and send back a response if required.

property ci: int

The call id associated with the request.

property method_identifier: HostMethodIdentifier

The method that needs to be invoked.

property method_parameters: List[Any]

List of parameters to invoke the method with.

class psrpcore.RunspacePoolHostResponseEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Runspace Pool Host Response Event.

Event Information:

Direction: Client -> Server

For: Runspace Pool

Message Type: psrpcore.types.RunspacePoolHostResponse

Action Required: Send to higher layer for processing

The client sends this message in response to a RunspacePoolHostCall. It contains the host response information that is processed by the higher layer.

property ci: int

The call id associated with the request.

property error: ErrorRecord | None

The error record if the host call failed.

property method_identifier: HostMethodIdentifier

The method that was invoked.

property result: Any | None

The result (if any) from the host call.

class psrpcore.RunspacePoolInitDataEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Runspace Pool Init Data Event

Event Information:

Direction: Server -> Client

For: Runspace Pool

Message Type: psrpcore.types.

Action Required: Send to higher layer

The server sends this message in response to the psrpcore.types.ConnectRunspacePool message. The client adjusts the Runspace Pool min/max limits and the higher layer can process the data as required.

property max_runspaces: int

The maximum number of runspaces in the Runspace Pool.

property min_runspaces: int

The minimum number of runspaces in the Runspace Pool.

class psrpcore.RunspacePoolStateEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Runspace Pool State Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool

Message Type: psrpcore.types.RunspacePoolStateMsg

Action Required: Send to higher layer for processing

The server sends this msg in response to a runspace state change. The client should share this with the higher layer which checks whether it is Broken and use the reason to see why it did.

property reason: ErrorRecord | None

An error record containing the reason why the runspace is Broken.

property state: RunspacePoolState

The Runspace Pool state.

class psrpcore.ServerHostRequestor(connection: ServerRunspacePool | ServerPipeline)

Server Host Requestor.

Helper class that can be used to create Runspace Pool or Pipeline host call requests. Each method exposes the required/optional arguments for each call and extra handling that may be required for that request. The ClientHostResponder is used on the client side to respond to the host calls that require a response.

Parameters:

connection (ServerRunspacePool | ServerPipeline) – The server Runspace Pool or Pipeline to send requests to.

enter_nested_prompt() None

EnterNestedPrompt Request.

Sends the psrpcore.types.HostMethodIdentifier.EnterNestedPrompt host call that instructs the host to interrupt the currently running pipeline and start a new, “nested” input loop, where an input loop is the cycle of prompt, input, execute.

This corresponds to the PSHost.EnterNestedPrompt Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

exit_nested_prompt() None

ExitNestedPrompt Request.

Sends the psrpcore.types.HostMethodIdentifier.ExitNestedPrompt host call that causes the host to end the currently running input loop. If the input loop was created by a prior call to EnterNestedPrompt, the enclosing pipeline will be resumed. If the current input loop is the top-most loop, then the host will act as though set_should_exit() was called.

This corresponds to the PSHost.ExitNestedPrompt Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

flush_input_buffer() None

FlushInputBuffer Request.

Sends the psrpcore.types.HostMethodIdentifier.FlushInputBuffer host call to reset the keyboard input buffer.

This corresponds to the PSHostRawUserInterface.FlushInputBuffer Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

get_background_color() int

GetBackgroundColor Request.

Sends the psrpcore.types.HostMethodIdentifier.GetBackgroundColor host call to request the background color of the host.

This corresponds to the PSHostRawUserInterface.BackgroundColor Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_buffer_contents(left: int, top: int, right: int, bottom: int) int

GetBufferContents Request.

Sends the psrpcore.types.HostMethodIdentifier.GetBufferContents host call to request the contents of the screen region specified.

This corresponds to the PSHostRawUserInterface.GetBufferContents Method.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Note

PowerShell does not implement this call for security reasons. Unless you trust the client host you should write an error record instead.

Parameters:
  • left (int) – The left margin of the buffer region.

  • top (int) – The top margin of the buffer region.

  • right (int) – The right margin of the buffer region.

  • bottom (int) – The bottom margin of the buffer region.

Returns:

The call id for the request.

Return type:

int

get_buffer_size() int

GetBufferSize Request.

Sends the psrpcore.types.HostMethodIdentifier.GetBufferSize host call to get the size of the screen buffer as measured by cells.

This corresponds to the PSHostRawUserInterface.BufferSize Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_current_culture() int

GetCurrentCulture Request.

Sends the psrpcore.types.HostMethodIdentifier.GetCurrentCulture host call that requests the current culture of the host.

This corresponds to the PSHost.CurrentCulture Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_current_ui_culture() int

GetCurrentUICulture Request.

Sends the psrpcore.types.HostMethodIdentifier.GetCurrentUICulture host call that requests the current UI culture of the host.

This corresponds to the PSHost.CurrentUICulture Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_cursor_position() int

GetCursorPosition Request.

Sends the psrpcore.types.HostMethodIdentifier.GetCursorPosition host call to get the position of the cursor on the screen buffer.

This corresponds to the PSHostRawUserInterface.CursorPosition Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_cursor_size() int

GetCursorSize Request.

Sends the psrpcore.types.HostMethodIdentifier.GetCursorSize host call to get the size of the cursor as a percentage.

This corresponds to the PSHostRawUserInterface.CursorSize Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_foreground_color() int

GetForegroundColor Request.

Sends the psrpcore.types.HostMethodIdentifier.GetForegroundColor host call to request the foreground color of the host.

This corresponds to the PSHostRawUserInterface.ForegroundColor Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_instance_id() int

GetInstanceId Request.

Sends the psrpcore.types.HostMethodIdentifier.GetInstanceId host call that requests the identifier of the hosting application.

This corresponds to the PSHost.InstanceId Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_is_runspace_pushed() int

GetIsRunspacePushed Request.

Sends the psrpcore.types.HostMethodIdentifier.GetIsRunspacePushed host call to check if the runspace is pushed or not.

This corresponds to the IHostSupportsInteractiveSession.IsRunspacePushed Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_key_available() int

GetKeyAvailable Request.

Sends the psrpcore.types.HostMethodIdentifier.GetKeyAvailable host call to examine if a keystroke is waiting in the input buffer.

This corresponds to the PSHostRawUserInterface.KeyAvailable Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_max_physical_window_size() int

GetMaxPhysicalWindowSize Request.

Sends the psrpcore.types.HostMethodIdentifier.GetMaxPhysicalWindowSize host call to get largest possible window size that can be set.

This corresponds to the PSHostRawUserInterface.MaxPhysicalWindowSize Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_max_window_size() int

GetMaxWindowSize Request.

Sends the psrpcore.types.HostMethodIdentifier.GetMaxWindowSize host call to get largest possible window size that can fit in the current buffer.

This corresponds to the PSHostRawUserInterface.MaxWindowSize Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_name() int

GetName Request.

Sends the psrpcore.types.HostMethodIdentifier.GetName host call that requests the human friendly host name identifier. human friendly host name identifier.

This corresponds to the PSHost.Name Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_version() int

GetVersion Request.

Sends the psrpcore.types.HostMethodIdentifier.GetVersion host call that requests the version of the hosting application.

This corresponds to the PSHost.Version Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_window_position() int

GetWindowPosition Request.

Sends the psrpcore.types.HostMethodIdentifier.GetWindowPosition host call to get the position of the view window relative to the screen buffer.

This corresponds to the PSHostRawUserInterface.WindowPosition Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_window_size() int

GetWindowSize Request.

Sends the psrpcore.types.HostMethodIdentifier.GetWindowSize host call to get the size of the view window as measured by cells.

This corresponds to the PSHostRawUserInterface.WindowSize Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

get_window_title() int

GetWindowTitle Request.

Sends the psrpcore.types.HostMethodIdentifier.GetWindowTitle host call to get the window title.

This corresponds to the PSHostRawUserInterface.WindowTitle Property.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

notify_begin_application() None

NotifyBeginApplication Request.

Sends the psrpcore.types.HostMethodIdentifier.NotifyBeginApplication host call that is called by the engine to notify the host that it is about to execute a “legacy” command line application. A legacy application is defined as a console-mode executable that may do one or more of the following:

  • reads from stdin

  • writes to stdout

  • writes to stderr

The engine will always call this method and notify_end_application() in pairs.

This corresponds to the PSHost.NotifyBeginApplication Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

notify_end_application() None

NotifyEndApplication Request.

Sends the psrpcore.types.HostMethodIdentifier.NotifyEndApplication host call that is called by the engine to notify the host that the execution of a legacy command has completed.

The engine will always call this method and notify_begin_application() in pairs.

This corresponds to the PSHost.NotifyEndApplication Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

pop_runspace() None

PopRunspace Request.

Sends the psrpcore.types.HostMethodIdentifier.PopRunspace host call that is called by the engine to notify the host that a Runspace pop has been requested.

This corresponds to the IHostSupportsInteractiveSession.PopRunspace Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

prompt(caption: str, message: str, descriptions: List[FieldDescription]) int

Prompt Request.

Sends the psrpcore.types.HostMethodIdentifier.Prompt host call prompts the user with a number of fields for which to supply values.

This corresponds to the PSHostUserInterface.Prompt Method.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Parameters:
  • caption (str) – The caption or title for the prompt.

  • message (str) – The message describing the set of fields.

  • descriptions (List[FieldDescription]) – A list of fields to display.

Returns:

The call id for the request.

Return type:

int

prompt_for_choice(caption: str, message: str, choices: List[ChoiceDescription], default_choice: int = -1) int

PromptForChoice Request.

Sends the psrpcore.types.HostMethodIdentifier.PromptForChoice host call prompts the user to choose an option from a set list.

This corresponds to the PSHostUserInterface.PromptForChoice Method. See prompt_for_multiple_choice() for a way to allow the user to select multiple choices.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Parameters:
  • caption (str) – The caption or title for the prompt.

  • message (str) – The message describing the set of choices.

  • choices (List[ChoiceDescription]) – A list of choices.

  • default_choice (int) – The default choice that correspond to the index of choices, -1 means no default.

Returns:

The call id for the request.

Return type:

int

prompt_for_credential(caption: str = 'PSRPCore credential request', message: str = 'Enter your credentials.', username: str | None = None, target_name: str | None = None, allowed_credential_types: PSCredentialTypes | None = None, options: PSCredentialUIOptions | None = None) int

PromptForCredential Request.

Sends the psrpcore.types.HostMethodIdentifier.PromptForCredential1, or psrpcore.types.HostMethodIdentifier.PromptForCredential2 host call prompts the user for a credential.

This corresponds to the PSHostUserInterface.PromptForCredential Method.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Parameters:
  • caption (str) – The caption or title for the prompt.

  • message (str) – The message describing the credential required.

  • username (str | None) – The username the credential is for, if omitted or None/empty the username is requested in the prompt.

  • target_name (str | None) – The domain part of the username if set.

  • allowed_credential_types (PSCredentialTypes | None) – The types of credential that is being requested.

  • options (PSCredentialUIOptions | None) – Options to control the UI behaviour.

Returns:

The call id for the request.

Return type:

int

prompt_for_multiple_choice(caption: str, message: str, choices: List[ChoiceDescription], default_choices: List[int] | None = None) int

PromptForChoiceMultipleSelection Request.

Sends the psrpcore.types.HostMethodIdentifier.PromptForChoiceMultipleSelection host call prompts the user to choose multiple options from a set list.

This corresponds to the IHostUISupportsMultipleChoiceSelection.PromptForChoice Method.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Parameters:
  • caption (str) – The caption or title for the prompt.

  • message (str) – The message describing the set of choices.

  • choices (List[ChoiceDescription]) – A list of choices.

  • default_choices (List[int] | None) – A list of default choice that correspond to the index of choices.

Returns:

The call id for the request.

Return type:

int

read_key(options: ~psrpcore.types._host.ReadKeyOptions = <ReadKeyOptions.IncludeKeyDown: 4>) int

ReadKey Request.

Sends the psrpcore.types.HostMethodIdentifier.ReadKey host call to request read a key stroke.

This corresponds to the PSHostRawUserInterface.ReadKey Method.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Parameters:

options (ReadKeyOptions) – Further options to control the read key operation.

Returns:

The call id for the request.

Return type:

int

read_line() int

ReadLine Request.

Sends the psrpcore.types.HostMethodIdentifier.ReadLine host call to read characters from the console until a newline is encountered.

This corresponds to the PSHostUserInterface.ReadLine Method.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

read_line_as_secure_string() int

ReadLineAsSecureString Request.

Sends the psrpcore.types.HostMethodIdentifier.ReadLineAsSecureString host call to read characters from the console until a newline is encountered without echoing the input back to the user.

This corresponds to the PSHostUserInterface.ReadLineAsSecureString Method.

Note

The server should wait for the host response before continuing the pipeline that created this request.

Returns:

The call id for the request.

Return type:

int

scroll_buffer_contents(source_left: int, source_top: int, source_right: int, source_bottom: int, x: int, y: int, clip_left: int, clip_top: int, clip_right: int, clip_bottom: int, character: int | str | ~psrpcore.types._primitive.PSChar, foreground: ~psrpcore.types._complex.ConsoleColor = <ConsoleColor.White: 15>, background: ~psrpcore.types._complex.ConsoleColor = <ConsoleColor.Black: 0>) None

ScrollBufferContents Request.

Sends the psrpcore.types.HostMethodIdentifier.ScrollBufferContents host call to scoll a region of the screen buffer.

This corresponds to the PSHostRawUserInterface.ScrollBufferContents Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • source_left (int) – The left margin of the screen to be scrolled.

  • source_top (int) – The top margin of the screen to be scrolled.

  • source_right (int) – The right margin of the screen to be scrolled.

  • source_bottom (int) – The bottom margin of the screen to be scrolled.

  • x (int) – The horizontal location of the upper left coordinate to receive the source region contents.

  • y (int) – The vertical location of the upper left coordinate to receive the source region contents.

  • clip_left (int) – The left margin of the clipped region.

  • clip_top (int) – The top margin of the clipped region.

  • clip_right (int) – The right margin of the clipped region.

  • clip_bottom (int) – The bottom margin of the clipped region.

  • character (int | str | PSChar) – The character used to fill the cells intersecting the source and clip region.

  • foreground (ConsoleColor) – The foreground (text) color to fill the cells intersecting the source and clip region.

  • background (ConsoleColor) – The background color to fill the cells intersecting the source and clip region.

set_background_color(color: ConsoleColor) None

SetBackgroundColor Request.

Sends the psrpcore.types.HostMethodIdentifier.SetBackgroundColor host call to change the background color of the host.

This corresponds to the PSHostRawUserInterface.BackgroundColor Property.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

color (ConsoleColor) – The color to set the background color to.

set_buffer_cells(left: int, top: int, right: int, bottom: int, character: int | str | ~psrpcore.types._primitive.PSChar, foreground: ~psrpcore.types._complex.ConsoleColor = <ConsoleColor.White: 15>, background: ~psrpcore.types._complex.ConsoleColor = <ConsoleColor.Black: 0>) None

SetBufferContents Request.

Sends the psrpcore.types.HostMethodIdentifier.SetBufferContents1 host call to set the contents of the host buffer.

This corresponds to the PSHostRawUserInterface.SetBufferContents Method. See set_buffer_contents() to set the buffer contents by individual cells.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • left (int) – The left margin of the region to set the cell to.

  • top (int) – The top margin of the region to set the cell to.

  • right (int) – The right margin of the region to set the cell to.

  • bottom (int) – The bottom margin of the region to set the cell to.

  • character (int | str | PSChar) – The character used to fill the cells in the region specified.

  • foreground (ConsoleColor) – The foreground (text) color to fill the cells in the region specified.

  • background (ConsoleColor) – The background color to fill the cells in the region specified.

set_buffer_contents(x: int, y: int, contents: List[List[BufferCell]]) None

SetBufferContents Request.

Sends the psrpcore.types.HostMethodIdentifier.SetBufferContents2 host call to set the contents of the host buffer.

The contents value is a list of a list of psrpcore.types.BufferCell where the first list dimension represents each row and the 2nd dimension is each column of that row.

This corresponds to the PSHostRawUserInterface.SetBufferContents Method. See set_buffer_cells() to set an individual cell across a region.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • x (int) – The horizontal location of the upper left corner of the region to write the cells from.

  • y (int) – The vertical location of the upper left corner of the region to write the cells from.

  • contents (List[List[BufferCell]]) – A list of a list of cells that should be written.

set_buffer_size(width: int, height: int) None

SetBufferSize Request.

Sends the psrpcore.types.HostMethodIdentifier.SetBufferSize host call to change the size of the screen buffer as measured by cells.

This corresponds to the PSHostRawUserInterface.BufferSize Property.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • width (int) – The number of cells in the buffer width.

  • height (int) – The number of cells in the buffer height.

set_cursor_position(x: int, y: int) None

SetCursorPosition Request.

Sends the psrpcore.types.HostMethodIdentifier.SetCursorPosition host call to change the position of the cursor on the screen buffer.

This corresponds to the PSHostRawUserInterface.CursorPosition Property.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • x (int) – The horizontal location to set the cursor to.

  • y (int) – The vertical location to set the cursor to.

set_cursor_size(size: int) None

SetCursorSize Request.

Sends the psrpcore.types.HostMethodIdentifier.SetCursorSize host call to set the size of the cursor as a percentage.

This corresponds to the PSHostRawUserInterface.CursorSize Property.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

size (int) – The cursor size as a percentage.

set_foreground_color(color: ConsoleColor) None

SetForegroundColor Request.

Sends the psrpcore.types.HostMethodIdentifier.SetForegroundColor host call to change the foreground color of the host.

This corresponds to the PSHostRawUserInterface.ForegroundColor Property.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

color (ConsoleColor) – The color to set the foreground color to.

set_should_exit(exit_code: int) None

SetShouldExit Request.

Sends the psrpcore.types.HostMethodIdentifier.SetShouldExit host call that requests the current engine runspace to shut down and terminate the host’s root runspace.

This corresponds to the PSHost.SetShouldExit Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

exit_code (int) – The exit code accompanying the exit keyword.

set_window_position(x: int, y: int) None

SetWindowPosition Request.

Sends the psrpcore.types.HostMethodIdentifier.SetWindowPosition host call to change the position of the view window relative to the screen buffer.

This corresponds to the PSHostRawUserInterface.WindowPosition Property.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • x (int) – The horizontal location to set the window to.

  • y (int) – The vertical location to set the window to.

set_window_size(width: int, height: int) None

SetWindowSize Request.

Sends the psrpcore.types.HostMethodIdentifier.SetWindowSize host call to change the size of the view window size as measured by cells.

This corresponds to the PSHostRawUserInterface.WindowSize Property.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • width (int) – The number of cells in the view window width.

  • height (int) – The number of cells in the view window height.

set_window_title(title: str) None

SetWindowTitle Request.

Sends the psrpcore.types.HostMethodIdentifier.SetWindowTitle host call to change the title of the host window

This corresponds to the PSHostRawUserInterface.WindowTitle Property.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

title (str) – The title to set the host window to.

write(value: str, foreground_color: ConsoleColor | None = None, background_color: ConsoleColor | None = None) None

Write Request.

Sends the psrpcore.types.HostMethodIdentifier.Write1 or psrpcore.types.HostMethodIdentifier.Write2 host call that writes the characters to the screen buffer.

This corresponds to the PSHostUserInterface.Write Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • value (str) – The characters to write.

  • foreground_color (ConsoleColor | None) – The color to display the text with.

  • background_color (ConsoleColor | None) – The color to display the background with.

write_debug_line(line: str) None

WriteDebugLine Request.

Sends the psrpcore.types.HostMethodIdentifier.WriteDebugLine host call that writes a debugging message to the host.

This corresponds to the PSHostUserInterface.WriteDebugLine Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

line (str) – The debug line to write to the display.

write_error_line(line: str) None

WriteErrorLine Request.

Sends the psrpcore.types.HostMethodIdentifier.WriteErrorLine host call that writes the line to the error display of the host.

This corresponds to the PSHostUserInterface.WriteErrorLine Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

line (str) – The line to write to the error display.

write_line(line: str | None = None, foreground_color: ConsoleColor | None = None, background_color: ConsoleColor | None = None) None

WriteLine Request.

Sends the psrpcore.types.HostMethodIdentifier.WriteLine1, psrpcore.types.HostMethodIdentifier.WriteLine2, or psrpcore.types.HostMethodIdentifier.WriteLine2 host call that writes the characters with a newline to the screen buffer.

This corresponds to the PSHostUserInterface.WriteLine Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • line (str | None) – The line to write, if not set then just a newline is written.

  • foreground_color (ConsoleColor | None) – The color to display the line with.

  • background_color (ConsoleColor | None) – The color to display the background with.

write_progress(source_id: int, activity_id: int, activity: str, status_description: str, current_operation: str | None = None, parent_activity_id: int = -1, percent_complete: int = -1, record_type: ~psrpcore.types._complex.ProgressRecordType = <ProgressRecordType.Processing: 0>, seconds_remaining: int = -1) None

WriteProgress Request.

Sends the psrpcore.types.HostMethodIdentifier.WriteProgress host call that writes a progress record to be displayed on the host.

This corresponds to the PSHostUserInterface.WriteProgress Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:
  • source_id (int) – Unique identifier of the source of the record.

  • activity (str) – The description of the activity for which progress is being reported.

  • activity_id (int) – The Id of the activity to which this record corresponds. Used as a key for linking of subordinate activities.

  • status_description (str) – Current status of the operation, e.g. “35 of 50 items copied.”.

  • current_operation (str | None) – Current operation of the many required to accomplish the activity, e.g. “copying foo.txt”.

  • parent_activity_id (int) – The Id of the activity for which this record is a subordinate.

  • percent_complete (int) – The estimate of the percentage of total work for the activity that is completed. Set to a negative value to indicate that the percentage completed should not be displayed.

  • record_type (ProgressRecordType) – The type of record represented.

  • seconds_remaining (int) – The estimate of time remaining until this activity is completed. Set to a negative value to indicate that the seconds remaining should not be displayed.

write_verbose_line(line: str) None

WriteVerboseLine Request.

Sends the psrpcore.types.HostMethodIdentifier.WriteVerboseLine host call that writes a verbose message to the host.

This corresponds to the PSHostUserInterface.WriteVerboseLine Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

line (str) – The verbose line to write to the display.

write_warning_line(line: str) None

WriteWarningLine Request.

Sends the psrpcore.types.HostMethodIdentifier.WriteWarningLine host call that writes a warning message to the host.

This corresponds to the PSHostUserInterface.WriteWarningLine Method.

Note

This is a void method and the server should continue pipeline execution and expect no response from the client.

Parameters:

line (str) – The warning line to write to the display.

class psrpcore.ServerPipeline(*args: Any, **kwargs: Any)

Server Pipeline.

Represent a server pipeline and the various methods that can be used to communicate with the client pipeline. Any data generated by this pipeline is retrieved through the Runspace Pool it is a member off.

complete() None

Marks the pipeline as closed.

This marks the pipeline has completed and generates a psrpcore.types.PipelineState message to be sent to the client.

host_call(method: HostMethodIdentifier, parameters: List | None = None) int

Request pipeline host call.

Request a host call on the client for the pipeline. Will generate a psrpcore.types.PipelineHostCall message to be sent to the client.

Parameters:
  • method (HostMethodIdentifier) – The host method that is requested to be run.

  • parameters (List | None) – Parameters to invoke the call with.

Returns:

The call identifier for this hoist call.

Return type:

int

start() None

Marks the pipeline as started.

stop() None

Stops the pipeline.

Stops a running pipeline and generates a psrpcore.types.PipelineState message to be sent to the client.

write_debug(message: str, invocation_info: InvocationInfo | None = None, pipeline_iteration_info: List[int] | None = None) None

Write a Debug Record.

write_error(exception: NETException, category_info: ErrorCategoryInfo | None = None, target_object: Any = None, fully_qualified_error_id: str | None = None, error_details: ErrorDetails | None = None, invocation_info: InvocationInfo | None = None, pipeline_iteration_info: List[int] | None = None, script_stack_trace: str | None = None) None

Write Error Record.

Write an error record to the error stream.

Parameters:
  • exception (NETException) – The .NET exception.

  • category_info (ErrorCategoryInfo | None) – Info about the type of error record.

  • target_object (Any) – The object the error record is related to.

  • fully_qualified_error_id (str | None) – A unique identifier for this specific error record.

  • error_details (ErrorDetails | None) – Further details about this error record.

  • invocation_info (InvocationInfo | None) – Info about what generated the error record.

  • pipeline_iteration_info (List[int] | None) – Where in the pipeline did this error record get generated.

  • scrript_stack_trace – The stack trace which shows where the error was generated.

write_information(message_data: Any, source: str, time_generated: datetime | None = None, tags: List[str] | None = None, user: str | None = None, computer: str | None = None, process_id: int | None = None, native_thread_id: int | None = None, managed_thread_id: int | None = None) None

Write an information record.

Writes an information record to send to the client.

Note

This requires ProtocolVersion 2.3 (PowerShell 5.1+).

Parameters:
  • message_data (Any) – Data for this record.

  • source (str) – The source of this record, e.g. script path, function name, etc.

  • time_generated (datetime | None) – The time the record was generated, will default to now if not specified.

  • tags (List[str] | None) – Tags associated with the record, if any.

  • user (str | None) – The user that generated the record, defaults to the current user.

  • computer (str | None) – The computer that generated the record, defaults to the current computer.

  • process_id (int | None) – The process that generated the record, defaults to the current process.

  • native_thread_id (int | None) – The native thread that generated the record, defaults to the current thread.

  • managed_thread_id (int | None) – The managed thread that generated the record, defaults to 0.

write_output(value: Any) None

Write object.

Write an object to the output stream.

Parameters:

value (Any) – The object to write.

write_progress(activity: str, activity_id: int, status_description: str, current_operation: str | None = None, parent_activity_id: int = -1, percent_complete: int = -1, record_type: ~psrpcore.types._complex.ProgressRecordType = <ProgressRecordType.Processing: 0>, seconds_remaining: int = -1) None

Write a progress record.

Writes a progress record to send to the client.

Parameters:
  • activity (str) – The description of the activity for which progress is being reported.

  • activity_id (int) – The Id of the activity to which this record corresponds. Used as a key for linking of subordinate activities.

  • status_description (str) – Current status of the operation, e.g. “35 of 50 items copied.”.

  • current_operation (str | None) – Current operation of the many required to accomplish the activity, e.g. “copying foo.txt”.

  • parent_activity_id (int) – The Id of the activity for which this record is a subordinate.

  • percent_complete (int) – The estimate of the percentage of total work for the activity that is completed. Set to a negative value to indicate that the percentage completed should not be displayed.

  • record_type (ProgressRecordType) – The type of record represented.

  • seconds_remaining (int) – The estimate of time remaining until this activity is completed. Set to a negative value to indicate that the seconds remaining should not be displayed.

write_verbose(message: str, invocation_info: InvocationInfo | None = None, pipeline_iteration_info: List[int] | None = None) None

Write a Verbose Record.

write_warning(message: str, invocation_info: InvocationInfo | None = None, pipeline_iteration_info: List[int] | None = None) None

Write a Warning Record.

class psrpcore.ServerRunspacePool(*args: Any, **kwargs: Any)

Server Runspace Pool.

Represents a Runspace Pool from a server context.

Parameters:

application_private_data (Dict | None) – Any data about the server which is sent to the client during negotiation.

connect() None

Marks the pool as connected.

This marks the pool as connected from a disconnected state. Generates the psrpcore.types.RunspacePoolStateMsg that can be sent to the client.

host_call(method: HostMethodIdentifier, parameters: List | None = None, pipeline_id: UUID | None = None) int

Request host call.

Request a host call on the client. Will generate a psrpcore.types.RunspacePoolHostCall message to be sent to the client.

Parameters:
  • method (HostMethodIdentifier) – The host method that is requested to be run.

  • parameters (List | None) – Parameters to invoke the call with.

  • pipeline_id (UUID | None) – The pipeline identifier if the host call is for a specific pipeline or nont.

Returns:

The call identifier for this hoist call.

Return type:

int

receive_data(data: PSRPPayload) None

Store any incoming data.

Stores any incoming payloads in an internal buffer to be processed. This buffer is read when calling next_event().

Parameters:

data (PSRPPayload) – The PSRP payload data received from the transport.

request_key() None

Request key exchange.

Requests the client to start a key exchange so that psrpcore.types.PSSecureString objects can be serialized. This generates a psrpcore.types.PublicKeyRequest message to be sent to the client.

This is not used in ProtocolVersion 2.2 or newer but still present for backwards compatibility.

runspace_availability_response(ci: int, response: bool | int) None

Response to Runspace Availablity.

Responds to a RunspacePool availability event. The following responses are expected for these events:

SetMaxRunspacesEvent - bool

Whether the max request worked or not.

SetMinRunspacesEvent - bool

Whether the min request worked or not.

ResetRunspaceStateEvent - bool

Whether the reset request worked or not.

GetRunspaceAvailabilityEvent - int

The number of runspaces that are available

Parameters:
  • ci (int) – The call ID to respond to.

  • response (bool | int) – The response to send.

send_event(event_identifier: int, source_identifier: str, sender: Any = None, source_args: List[Any] | None = None, message_data: Any = None, time_generated: datetime | None = None, computer: str | None = None) None

Send event to client.

Sends an event to the client Runspace Pool. Generates a psrpcore.types.UserEvent message to be sent to the client.

Parameters:
  • event_identifier (int) – Unique identifier of this event.

  • source_identifier (str) – Identifier associated with the source of this event.

  • sender (Any) – Object that generated this event.

  • source_args (List[Any] | None) – List of arguments captured by the original event source.

  • message_data (Any) – Additional user data associated with this event.

  • time_generated (datetime | None) – Time and date that this event was generated, defaults to now.

  • computer (str | None) – The name of the computer on which this event was generated, defaults to the current computer.

set_broken(error: ErrorRecord) None

Mark pool as broken.

Marks the Runspace Pool as broken and states the reason why. Generates the psrpcore.types.RunspacePoolStateMsg that can be sent to the client.

Parameters:

error (ErrorRecord) – The error record explaining why the pool is broken.

class psrpcore.SessionCapabilityEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Session Capability Event.

Event Information:

Direction: Both

For: Runspace Pool

Message Type: psrpcore.types.SessionCapability

Action Required: Nothing for client, send response back to the client

The initial message received by both the client and server to state what protocol versions they understand. The server will automatically generate a psrpcore.types.SessionCapability message that must be sent back to the client.

property protocol_version: PSVersion

The protocol version of the peer.

property ps_version: PSVersion

The PowerShell version of the peer.

property serialization_version: PSVersion

The version of the peer’s serializer.

class psrpcore.SetMaxRunspacesEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Set Max Runspaces Event.

Event Information:

Direction: Client -> Server

For: Runspace Pool

Message Type: psrpcore.types.SetMaxRunspaces

Action Required:

The client sends this when trying to adjust the maximum available runspaces in a pool.

property ci: int

The call id associated with the request.

property count: int

The maximum runspace count to set.

class psrpcore.SetMinRunspacesEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Set Min Runspaces Event.

Event Information:

Direction: Client -> Server

For: Runspace Pool

Message Type: psrpcore.types.SetMinRunspaces

Action Required:

The client sends this when trying to adjust the minimum available runspaces in a pool.

property ci: int

The call id associated with the request.

property count: int

The minimum runspace count to set.

class psrpcore.SetRunspaceAvailabilityEvent(message_type: PSRPMessageType, ps_object: RunspaceAvailability, runspace_pool_id: UUID, pipeline_id: None = None)

Set Runspace Availability Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool

Message Type: psrpcore.types.RunspaceAvailability

Action Required: Send to higher layer

The server sends this message in resposne to a psrpcore.types.SetMaxRunspaces, psrpcore.types.SetMinRunspaces, or psrpcore.types.ResetRunspaceState message. The client automatically adjusts the runspace limits based on the response.

property success: bool

Whether the request suceeded or not.

class psrpcore.StreamType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

PSRP Message stream type.

The PSRP message stream type that defines the priority of a PSRP message. It is up to the connection to interpret these options and convey the priority to the peer in the proper fashion.

default = 1

The default type used for the majority of PSRP messages.

prompt_response = 2

Used for host call/responses PSRP messages.

class psrpcore.UserEventEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

User Event Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool or Pipeline

Message Type: psrpcore.types.UserEvent

Action Required: Send to higher layer

The server sends this message when reporting a user defined event from the runspace. The data should be shared with the higher layer as necessary.

property event: UserEvent

The user event received from the peer.

class psrpcore.VerboseRecordEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Verbose Record Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool or Pipeline

Message Type: psrpcore.types.VerboseRecordMsg

Action Required: Send to higher layer

The server sends this message when there is a verbose record generated by the server. The data should be shared with the higher layer as necessary.

property record: VerboseRecord

The VerboseRecord emitted by the peer.

class psrpcore.WarningRecordEvent(message_type: PSRPMessageType, ps_object: T1, runspace_pool_id: UUID, pipeline_id: T2)

Warning Record Event.

Event Information:

Direction: Server -> Client

For: Runspace Pool or Pipeline

Message Type: psrpcore.types.WarningRecordMsg

Action Required: Send to higher layer

The server sends this message when there is a warning record generated by the server. The data should be shared with the higher layer as necessary.

property record: WarningRecord

The WarningRecord emitted by the peer.