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.ApplicationPrivateDataAction Required: Share with higher layer
The server generates this data automatically when receiving an
psrpcore.types.InitRunspacePoolorpsrpcore.types.ConnectRunspacePoolmessage from the client.
- 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.GetBackgroundColorwith 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.GetBufferContentswith contents of the buffer that was requested.The
cellsvalue is a list of a list ofpsrpcore.types.BufferCellwhere 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.GetBufferSizewith 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.
- get_current_culture(ci: int, culture: str) None
GetCurrentCulture Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetCurrentCulturewith the host’s culture, likeen-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.
- get_current_ui_culture(ci: int, culture: str) None
GetCurrentUICulture Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetCurrentUICulturewith the host’s UI culture, likeen-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.
- get_cursor_position(ci: int, x: int, y: int) None
GetCursorPosition Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetCursorPositionthe 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.
- get_cursor_size(ci: int, size: int) None
GetCursorSize Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetCursorSizewith 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.
- get_foreground_color(ci: int, color: ConsoleColor) None
GetForegroundColor Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetForegroundColorwith 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.GetInstanceIdwith 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.
- get_is_runspace_pushed(ci: int, is_pushed: bool) None
GetIsRunspacePushed Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetIsRunspacePushedwith 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.
- get_key_available(ci: int, waiting: bool) None
GetKeyAvailable Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetKeyAvailablewith whether the host is waiting on input.
- get_max_physical_window_size(ci: int, width: int, height: int) None
GetMaxPhysicalWindowSize Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetMaxPhysicalWindowSizewith 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.
- get_max_window_size(ci: int, width: int, height: int) None
GetMaxWindowSize Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetMaxWindowSizewith 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.
- get_name(ci: int, name: str) None
GetName Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetNamewith 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.
- get_version(ci: int, version: str | PSVersion) None
GetVersion Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetVersionwith 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.
- get_window_position(ci: int, x: int, y: int) None
GetWindowPosition Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetWindowPositionthe 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.
- get_window_size(ci: int, width: int, height: int) None
GetWindowSize Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetWindowSizewith 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.
- get_window_title(ci: int, title: str) None
GetWindowTitle Response.
Responds to
psrpcore.types.HostMethodIdentifier.GetWindowTitlewith 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.
- prompt(ci: int, choices: Dict[str, Any]) None
Prompt Response.
Responds to
psrpcore.types.HostMethodIdentifier.Promptwith the values for field that was entered.
- prompt_for_choice(ci: int, choice: int) None
PromptForChoice Response.
Responds to
psrpcore.types.HostMethodIdentifier.PromptForChoicewith the choice that was slected.
- prompt_for_credential(ci: int, credential: PSCredential) None
PromptForCredential Response.
Responds to
psrpcore.types.HostMethodIdentifier.PromptForCredential1orpsrpcore.types.HostMethodIdentifier.PromptForCredential2with 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.PromptForChoiceMultipleSelectionwith the choices that were selected.
- 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.ReadKeywith 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
Trueor releaseFalse.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.ReadLinewith the line that was read.
- read_line_as_secure_string(ci: int, line: PSSecureString) None
ReadLineAsSecureString Response.
Responds to
psrpcore.types.HostMethodIdentifier.ReadLineAsSecureStringwith 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:
- add_command(cmdlet: str | Command, use_local_scope: bool | None = None) ClientPowerShell
Adds a command
Adds a command to the current statement.
- Parameters:
- Returns:
itself
- Return type:
- 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, orNoneas the value withNonebeing equivalent toFalse.- Parameters:
- Returns:
itself
- Return type:
- 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:
- 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:
- Returns:
itself
- Return type:
- 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:
- 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.
- 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.GetRunspaceAvailabilityEventevent is returned once the response is received from the server.- Returns:
The command id for this request.
- Return type:
- 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.ClientHostResponderto 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.
- 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:
- 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
SetMaxRunspacesEventis received.
- 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
SetMinRunspacesEventis fired.
- 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.
- information: list[InformationRecord]
Objects fr om the information 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:
- 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.ErrorRecordto 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.InformationRecordto 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.ProcessRecordto 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.
- class psrpcore.Command(*args: Any, **kwargs: Any)
Pipeline Command.
Defines a Command object which can be added to a Pipeline for invocation.
- Parameters:
- 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_parameter(name: str | None, value: Any = True) Command
Add a parameter and value 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, orNull.- 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.
- 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.ConnectRunspacePoolAction 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, andpsrpcore.types.RunspacePoolStateMsgto send back to the client.
- 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.CreatePipelineAction 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.DebugRecordMsgAction 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.EncryptedSessionKeyAction Required: None - secure strings can now be serialized
The server sends this message after processing the
psrpcore.types.PublicKeymessage from the client. It contains the encrypted session key used when serializingpsrpcore.types.PSSecureStringobjects.
- 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.EndOfPipelineAction 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.ErrorRecordMsgAction 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.GetAvailableRunspacesAction 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.RunspaceAvailabilityas a response to the client.
- 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.GetCommandMetadataAction 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.RunspaceAvailabilityAction Required: Send to higher layer
The server sends this message in resposne to a
psrpcore.types.GetAvailableRunspacesmessage.
- 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.InformationRecordMsgAction 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.InitRunspacePoolAction 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.ApplicationPrivateDataandpsrpcore.types.RunspacePoolStateMsgto 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 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.
- 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.
- 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.PSRPMessageTypethat 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.
- 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.
- 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.PipelineHostCallAction Required: Send to higher layer for processing
The server sends this message when requesting the host to invoke a
psrpcore.types.HostMethodIdentifiermethod. It is up to the client to send this information to the higher layer and send back a response if required.- property method_identifier: HostMethodIdentifier
The method that needs to be invoked.
- 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.PipelineHostResponseAction 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 error: ErrorRecord | None
The error record if the host call failed.
- property method_identifier: HostMethodIdentifier
The method that was invoked.
- 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.
- 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.
- 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.PipelineStateAction 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
Failedand 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.ProgressRecordMsgAction 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.PublicKeyAction Required: Send response back to the client
The client sends this message when it requests the encrypted session key used when serializing
psrpcore.types.PSSecureStringobjects. The server automatically generates thepsrpcore.types.EncryptedSessionKeyas a response to the client.
- 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.PublicKeyRequestAction Required: Send response back to the server
The server sends this message when it wants to serialize a
psrpcore.types.PSSecureStringobject. The client automatically generates thepsrpcore.types.PublicKeyas 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.ResetRunspaceStateAction Required: Send to higher layer
The client sends this message when it wants to reset the Runspace Pool state.
- 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.RunspacePoolHostCallAction Required: Send to higher layer for processing
The server sends this message when requesting the host to invoke a
psrpcore.types.HostMethodIdentifiermethod. It is up to the client to send this information to the higher layer and send back a response if required.- property method_identifier: HostMethodIdentifier
The method that needs to be invoked.
- 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.RunspacePoolHostResponseAction 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 error: ErrorRecord | None
The error record if the host call failed.
- property method_identifier: HostMethodIdentifier
The method that was invoked.
- 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.ConnectRunspacePoolmessage. The client adjusts the Runspace Pool min/max limits and the higher layer can process the data as required.
- 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.RunspacePoolStateMsgAction 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
Brokenand 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
ClientHostResponderis 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.EnterNestedPrompthost 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.ExitNestedPrompthost 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 thoughset_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.FlushInputBufferhost 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.GetBackgroundColorhost 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:
- get_buffer_contents(left: int, top: int, right: int, bottom: int) int
GetBufferContents Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetBufferContentshost 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.
- get_buffer_size() int
GetBufferSize Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetBufferSizehost 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:
- get_current_culture() int
GetCurrentCulture Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetCurrentCulturehost 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:
- get_current_ui_culture() int
GetCurrentUICulture Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetCurrentUICulturehost 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:
- get_cursor_position() int
GetCursorPosition Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetCursorPositionhost 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:
- get_cursor_size() int
GetCursorSize Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetCursorSizehost 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:
- get_foreground_color() int
GetForegroundColor Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetForegroundColorhost 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:
- get_instance_id() int
GetInstanceId Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetInstanceIdhost 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:
- get_is_runspace_pushed() int
GetIsRunspacePushed Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetIsRunspacePushedhost 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:
- get_key_available() int
GetKeyAvailable Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetKeyAvailablehost 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:
- get_max_physical_window_size() int
GetMaxPhysicalWindowSize Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetMaxPhysicalWindowSizehost 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:
- get_max_window_size() int
GetMaxWindowSize Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetMaxWindowSizehost 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:
- get_name() int
GetName Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetNamehost 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:
- get_version() int
GetVersion Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetVersionhost 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:
- get_window_position() int
GetWindowPosition Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetWindowPositionhost 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:
- get_window_size() int
GetWindowSize Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetWindowSizehost 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:
- get_window_title() int
GetWindowTitle Request.
Sends the
psrpcore.types.HostMethodIdentifier.GetWindowTitlehost 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:
- notify_begin_application() None
NotifyBeginApplication Request.
Sends the
psrpcore.types.HostMethodIdentifier.NotifyBeginApplicationhost 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.NotifyEndApplicationhost 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.PopRunspacehost 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.Prompthost 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:
- prompt_for_choice(caption: str, message: str, choices: List[ChoiceDescription], default_choice: int = -1) int
PromptForChoice Request.
Sends the
psrpcore.types.HostMethodIdentifier.PromptForChoicehost 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,
-1means no default.
- Returns:
The call id for the request.
- Return type:
- 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, orpsrpcore.types.HostMethodIdentifier.PromptForCredential2host 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:
- 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.PromptForChoiceMultipleSelectionhost 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:
- Returns:
The call id for the request.
- Return type:
- read_key(options: ~psrpcore.types._host.ReadKeyOptions = <ReadKeyOptions.IncludeKeyDown: 4>) int
ReadKey Request.
Sends the
psrpcore.types.HostMethodIdentifier.ReadKeyhost 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:
- read_line() int
ReadLine Request.
Sends the
psrpcore.types.HostMethodIdentifier.ReadLinehost 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:
- read_line_as_secure_string() int
ReadLineAsSecureString Request.
Sends the
psrpcore.types.HostMethodIdentifier.ReadLineAsSecureStringhost 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:
- 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.ScrollBufferContentshost 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.SetBackgroundColorhost 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.SetBufferContents1host 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.SetBufferContents2host call to set the contents of the host buffer.The
contentsvalue is a list of a list ofpsrpcore.types.BufferCellwhere 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.SetBufferSizehost 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.
- set_cursor_position(x: int, y: int) None
SetCursorPosition Request.
Sends the
psrpcore.types.HostMethodIdentifier.SetCursorPositionhost 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.
- set_cursor_size(size: int) None
SetCursorSize Request.
Sends the
psrpcore.types.HostMethodIdentifier.SetCursorSizehost 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.SetForegroundColorhost 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.SetShouldExithost 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.SetWindowPositionhost 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.
- set_window_size(width: int, height: int) None
SetWindowSize Request.
Sends the
psrpcore.types.HostMethodIdentifier.SetWindowSizehost 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.
- set_window_title(title: str) None
SetWindowTitle Request.
Sends the
psrpcore.types.HostMethodIdentifier.SetWindowTitlehost call to change the title of the host windowThis 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.Write1orpsrpcore.types.HostMethodIdentifier.Write2host 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.WriteDebugLinehost 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.WriteErrorLinehost 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, orpsrpcore.types.HostMethodIdentifier.WriteLine2host 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.WriteProgresshost 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.WriteVerboseLinehost 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.WriteWarningLinehost 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.PipelineStatemessage 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.PipelineHostCallmessage 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:
- stop() None
Stops the pipeline.
Stops a running pipeline and generates a
psrpcore.types.PipelineStatemessage 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.
- 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.RunspacePoolStateMsgthat 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.RunspacePoolHostCallmessage 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:
- 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.PSSecureStringobjects can be serialized. This generates apsrpcore.types.PublicKeyRequestmessage 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- boolWhether the max request worked or not.
SetMinRunspacesEvent- boolWhether the min request worked or not.
ResetRunspaceStateEvent- boolWhether the reset request worked or not.
GetRunspaceAvailabilityEvent- intThe number of runspaces that are available
- 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.UserEventmessage 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.RunspacePoolStateMsgthat 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.SessionCapabilityAction 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.SessionCapabilitymessage that must be sent back to the client.
- 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.SetMaxRunspacesAction Required:
The client sends this when trying to adjust the maximum available runspaces in a pool.
- 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.SetMinRunspacesAction Required:
The client sends this when trying to adjust the minimum available runspaces in a pool.
- 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.RunspaceAvailabilityAction Required: Send to higher layer
The server sends this message in resposne to a
psrpcore.types.SetMaxRunspaces,psrpcore.types.SetMinRunspaces, orpsrpcore.types.ResetRunspaceStatemessage. The client automatically adjusts the runspace limits based on the response.
- 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.UserEventAction 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.
- 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.VerboseRecordMsgAction 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.WarningRecordMsgAction 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.