psrpcore.types

The .NET type code.

Contains the public entrypoint for all the .NET/Pwsh type code that is used to exchange objects between Python and PowerShell.

class psrpcore.types.ApartmentState(value)

System.Management.Automation.Runspaces.ApartmentState enum.

Specifies the apartment state of a Thread. It is documented in PSRP under [MS-PSRP] 2.2.3.7 ApartmentState.

Note

This is an auto-generated Python class for the System.Threading.ApartmentState .NET class.

MTA = 1

The thread will create and enter a single-threaded apartment.

MaxValue = 2147483647
MinValue = -2147483648
STA = 0

The thread will create and enter a multi-threaded apartment.

Unknown = 2

The ApartmentState property has not been set.

class psrpcore.types.ApplicationPrivateData(ApplicationPrivateData: PSPrimitiveDictionary)

APPLICATION_PRIVATE_DATA Message.

Data private to the application using the PowerShell Remoting Protocol on the server and client, which is passed by the protocol without interpretation. Message is defined in MS-PSRP 2.2.2.13 APPLICATION_PRIVATE_DATA.

Parameters:

ApplicationPrivateData (PSPrimitiveDictionary) – Private data that the higher layer provides to the server when a RunspacePool is created.

class psrpcore.types.BufferCell(Character: PSChar | None = None, ForegroundColor: ConsoleColor | None = None, BackgroundColor: ConsoleColor | None = None, BufferCellType: BufferCellType | None = None)

BufferCell.

Represents the contents of a cell of a host’s screen buffer. It is documented in PSRP under [MS-PSRP] 2.2.3.28 BufferCell. but the PSRP documentation represents how this value is serialized under host method invocations not the .NET type.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.BufferCell .NET class.

Parameters:
  • Character (PSChar | None) – Character visible in the cell.

  • ForegroundColor (ConsoleColor | None) – Foreground color.

  • BackgroundColor (ConsoleColor | None) – Background color.

  • BufferCellType (BufferCellType | None) – Type of the buffer cell.

class psrpcore.types.BufferCellType(value)

System.Management.Automation.Host.BufferCellType enum flags.

Defines three types of BufferCells to accommodate for hosts that use up to two cells to display a character in some languages such as Chinese and Japanese. It is documented in PSRP under [MS-PSRP] 2.2.3.29 BufferCellType.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.BufferCellType .NET class.

Complete = 0

Character occupies one BufferCell.

Leading = 1

Character occupies two BufferCells and this is the leading one.

MaxValue = 2147483647
MinValue = -2147483648
Trailing = 2

Preceded by a Leading BufferCell.

class psrpcore.types.ChoiceDescription(Label: PSString, HelpMessage: PSString | None = None)

ChoiceDescription.

Provides a description of a choice for use by HostMethodIdentifier.PromptForChoice.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.ChoiceDescription .NET class.

Parameters:
  • Label (PSString) – Human friendly message to describe the choice.

  • HelpMessage (PSString | None) – Help details of the choice.

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

Signifies what stream the object is associated with in serialize_clixml().

DEBUG = 'debug'

Debug stream

ERROR = 'error'

Error stream

INFORMATION = 'information'

Information stream

OUTPUT = 'output'

Output stream

PROGRESS = 'progress'

Progress stream

VERBOSE = 'verbose'

Verbose stream

WARNING = 'warning'

Warning stream

class psrpcore.types.CommandMetadataCount(*args: Any, **kwargs: Any)

CommandMetadataCount.

Special data type used by the command metadata messages. It is documented in PSRP under [MS-PSRP] 2.2.3.21 CommandMetadataCount.

Parameters:

Count (PSInt) – The count.

class psrpcore.types.CommandOrigin(value)

System.Management.Automation.CommandOrigin enum.

Defines the dispatch origin of a command. It is documented in PSRP under [MS-PSRP] 2.2.3.30 CommandOrigin.

Note

This is an auto-generated Python class for the System.Management.Automation.CommandOrigin .NET class.

Internal = 1

The command was dispatched by the PowerShell engine.

MaxValue = 2147483647
MinValue = -2147483648
Runspace = 0

The command was submited via a runspace.

class psrpcore.types.CommandTypes(value)

System.Management.Automation.CommandTypes enum flags.

Defines the types of commands that PowerShell can execute. It is documented in PSRP under [MS-PSRP] 2.2.3.19 CommandType.

Note

This is an auto-generated Python class for the System.Management.Automation.CommandTypes .NET class.

Alias = 1

Aliases create a name that refers to other command types.

All = 383

All possible command types.

Application = 32

Any existing application (can be console or GUI).

Cmdlet = 8

A cmdlet.

Configuration = 256

A configuration.

ExternalScript = 16

A PowerShell script (*.ps1 file).

Filter = 4

Script filters that are defined by a script block.

Function = 2

Script functions that are defined by a script block.

MaxValue = 2147483647
MinValue = -2147483648
Script = 64

A script that is built into the runspace configuration.

class psrpcore.types.ConnectRunspacePool(MinRunspaces: PSInt | None = None, MaxRunspaces: PSInt | None = None)

CONNECT_RUNSPACEPOOL Message.

Connect to a RunspacePool. Message is defined in MS-PSRP 2.2.2.29 CONNECT_RUNSPACEPOOL.

Note

This message is only used in ProtocolVersion>=2.2 (PowerShell v3.0+).

Parameters:
  • MinRunspaces (PSInt | None) – Minimum number of runspaces in the Runspace Pool.

  • MaxRunspaces (PSInt | None) – Maximum number of runspaces in the RUnspace Pool.

class psrpcore.types.ConsoleColor(value)

System.ConsoleColor enum.

Specifies constants that define foreground and background colors for the console. This is also documented under [MS-PSRP] 2.2.3.3 Color but in the HostInfo default data format.

Note

This is an auto-generated Python class for the System.ConsoleColor .NET class.

Black = 0
Blue = 9
Cyan = 11
DarkBlue = 1
DarkCyan = 3
DarkGray = 8
DarkGreen = 2
DarkMagenta = 5
DarkRed = 4
DarkYellow = 6
Gray = 7
Green = 10
Magenta = 13
MaxValue = 2147483647
MinValue = -2147483648
Red = 12
White = 15
Yellow = 14
class psrpcore.types.ControlKeyStates(value)

System.Management.Automation.Host.ControlKeyStates enum flags.

Defines the state of the control key. It is documented in PSRP under [MS-PSRP] 2.2.3.27 ControlKeyStates.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.ControlKeyStates .NET class.

CapsLockOn = 128

The capslock light is on.

EnhancedKey = 256

The key is enhanced.

LeftAltPressed = 2

The left alt key is pressed.

LeftCtrlPressed = 8

The left ctrl key is pressed.

MaxValue = 2147483647
MinValue = -2147483648
NumLockOn = 32

The numlock light is on.

RightAltPressed = 1

The right alt key is pressed.

RightCtrlPressed = 4

The right ctrl key is pressed.

ScrollLockOn = 64

The scrolllock light is on.

ShiftPressed = 16

The shift key is pressed.

none = 0

No control key state.

class psrpcore.types.Coordinates(X: PSInt, Y: PSInt)

Represents an x,y coordinate pair. It is documented under [MS-PSRP] 2.2.3.1 Coordinates but the PSRP documentation represents how this value is serialized under HostDefaultData not the .NET type.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.Coordinates .NET class.

Parameters:
  • X (PSInt) – X coordinate (0 is the leftmost column).

  • Y (PSInt) – Y coordinate (0 is the topmost row).

class psrpcore.types.CreatePipeline(NoInput: bool, ApartmentState: ApartmentState, RemoteStreamOptions: RemoteStreamOptions, AddToHistory: bool, HostInfo: HostInfo, PowerShell: PSObject, IsNested: bool)

CREATE_PIPELINE Message.

Creates a command pipeline and invoke it in the specified RunspacePool. Message is defined in MS-PSRP 2.2.2.10 CREATE_PIPELINE.

Parameters:
  • NoInput (bool) – Whether the pipeline will take input.

  • ApartmentState (ApartmentState) – Apartment state provided by the higher layer.

  • RemoteStreamOptions (RemoteStreamOptions) – Stream options that indicate how an application must treat messages from the PowerShell streams.

  • AddToHistory (bool) – Whether the higher layer is to add the pipeline to the history field of the runspace.

  • HostInfo (HostInfo) – The host information.

  • PowerShell (PSObject) – The pipeline information to create.

  • IsNested (bool) – Whether the higher layer is to run the pipeline in nested or steppable mode.

class psrpcore.types.DebugRecord(*args: Any, **kwargs: Any)

DebugRecord.

A debug record in the PSInformationalBuffers. This represents the System.Management.Automation.DebugRecord .NET type.

class psrpcore.types.DebugRecordMsg(*args: Any, **kwargs: Any)

DEBUG_RECORD Message.

Debug record from a command pipeline on the server. Message is defined in MS-PSRP 2.2.2.22 DEBUG_RECORD.

class psrpcore.types.EncryptedSessionKey(EncryptedSessionKey: PSString)

ENCRYPTED_SESSION_KEY Message.

Defines the encrypted session key calculated by the server. The value is encrypted using the public key that was sent by the client in the PublicKey message. Message is defined in MS-PSRP 2.2.2.4 - ENCRYPTED_SESSION_KEY.

Note

The session key is encrypted using the RSAES-PKCS-v1_5 encryption scheme.

Parameters:

EncryptedSessionKey (PSString) – The base64 encoding of the 256-bit AES encrypted session key.

class psrpcore.types.EndOfPipelineInput

END_OF_PIPELINE_INPUT Message.

Close the input collection for the command pipeline on the server. Message is defined in MS-PSRP 2.2.2.18 END_OF_PIPELINE_INPUT.

class psrpcore.types.ErrorCategory(value)

System.Management.Automation.ErrorCategory enum.

Errors reported by PowerShell will be in one of these categories. It is documented in PSRP under [MS-PSRP] 2.2.3.9 ErrorCategory.

Note

This is an auto-generated Python class for the System.Management.Automation.ErrorCategory .NET class.

AuthenticationError = 28

Could not authenticate the user to the service.

CloseError = 2
ConnectionError = 27

The operation depends on a network connection that cannot be established or maintained.

DeadlockDetected = 4
DeviceError = 3
FromStdErr = 24

A non-PowerShell command reported an error to its STDERR pipe.

InvalidArgument = 5
InvalidData = 6
InvalidOperation = 7
InvalidResult = 8
InvalidType = 9
LimitsExceeded = 29

Internal limits prevent the operation from being executed.

MaxValue = 2147483647
MetadataError = 10
MinValue = -2147483648
NotEnabled = 31

The operation attempted to use functionality that is currently disabled.

NotImplemented = 11
NotInstalled = 12
NotSpecified = 0

No error category is specified, or the error category is invalid.

ObjectNotFound = 13

Object can not be found (file, directory, computer, system resource, etc.).

OpenError = 1
OperationStopped = 14
OperationTimeout = 15
ParserError = 17
PermissionDenied = 18

Operation not permitted.

ProtocolError = 26

The contract of a protocol is not being followed.

QuotaExceeded = 30

Controls on the use of traffic or resources prevent the operation from being executed.

ReadError = 22
ResourceBusy = 19
ResourceExists = 20
ResourceUnavailable = 21
SecurityError = 25

Used for security exceptions.

SyntaxError = 16
WriteError = 23
class psrpcore.types.ErrorCategoryInfo(Category: ErrorCategory | None = <ErrorCategory.NotSpecified: 0>, Activity: PSString | None = None, Reason: PSString | None = None, TargetName: PSString | None = None, TargetType: PSString | None = None)

ErrorCategoryInfo.

Contains auxiliary information about an ErrorRecord. This is the actual .NET type System.Management.Automation.ErrorCategoryInfo.

Parameters:
  • Category (ErrorCategory | None) – The error category.

  • Activity (PSString | None) – Description of the operation which encountered the error.

  • Reason (PSString | None) – Description of the error.

  • TargetName (PSString | None) – Description of the target object.

  • TargetType (PSString | None) – Description of the type of the target object.

class psrpcore.types.ErrorDetails(Message: PSString | None = None, RecommendedAction: PSString | None = None)

ErrorDetails.

ErrorDetails represents additional details about an ErrorRecord, starting with a replacement Message. Clients can use ErrorDetails when they want to display a more specific message than the one contained in a particular Exception, without having to create a new Exception or define a new Exception class. This is the actual .NET type System.Management.Automation.ErrorDetails.

Parameters:
  • Message (PSString | None) – Message with replaces Message in Exception.

  • RecommendedAction (PSString | None) – Describes the recommended action in the event this error occurs. This can be empty if not applicable.

class psrpcore.types.ErrorRecord(*args: Any, **kwargs: Any)

ErrorRecord.

The data type that represents information about an error. It is documented in PSRP under [MS-PSRP] 2.2.3.15 ErrorRecord. The invocation specific properties are documented under [MS-PSRP] 2.2.3.15.1 InvocationInfo. This is the actual .NET type System.Management.Automation.ErrorRecord

Parameters:
  • Exception (PSObject) – An exception describing the error.

  • TargetObject (PSObject | None) – The object against which the error occurred.

  • FullyQualifiedErrorId (PSString | None) – String which uniquely identifies this error condition.

  • CategoryInfo (ErrorCategoryInfo) – Information regarding the ErrorCategory associated with this error.

  • ErrorDetails (ErrorDetails | None) – Additional information about the error.

  • InvocationInfo (InvocationInfo | None) – Identifies the cmdlet, script, or other command which caused the error.

  • PipelineIterationInfo (PSList | None) – The status of the pipeline when this record was created. Each entry represents the number of inputs the command[i] in the statement has processed when the record was created.

  • ScriptStackTrace (PSString | None) – The object against which the error occurred.

class psrpcore.types.ErrorRecordMsg(*args: Any, **kwargs: Any)

ERROR_RECORD Message.

Error record from a command pipeline on the server.. Message is defined in MS-PSRP 2.2.2.20 ERROR_RECORD.

class psrpcore.types.FieldDescription(Name: PSString, ParameterTypeName: PSString | None = None, ParameterTypeFullName: PSString | None = None, ParameterAssemblyFullName: PSString | None = None, Label: PSString | None = '', HelpMessage: PSString | None = '', IsMandatory: bool | None = True, DefaultValue: PSObject | None = None, Attributes: PSList | None = None)

FieldDescription.

Provides a description of a field for use by HostMethodIdentifier.Prompt.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.FieldDescription .NET class.

Parameters:
  • Name (PSString) – The name of the field.

  • ParameterTypeName (PSString | None) – Short name of the field value type.

  • ParameterTypeFullName (PSString | None) – Full name of the field value type.

  • ParameterAssemblyFullName (PSString | None) – .NET assembly name of the field value type.

  • Label (PSString | None) – Human friendly message to describe the field.

  • HelpMessage (PSString | None) – Help details of the field.

  • IsMandatory (bool | None) – The value must be supplied for this field.

  • DefaultValue (PSObject | None) – The default value, if any, for the field.

  • Attributes (PSList | None) – List of attributes that apply to the field.

class psrpcore.types.GetAvailableRunspaces(ci: PSInt64)

GET_AVAILABLE_RUNSPACES Message.

Get the number of available runspaces in a RunspacePool. Message is defined in MS-PSRP 2.2.2.11 GET_AVAILABLE_RUNSPACES.

Parameters:

ci (PSInt64) – The Call ID associated with this operation.

class psrpcore.types.GetCommandMetadata(Name: PSList | None = None, CommandType: CommandTypes | None = None, Namespace: PSList | None = None, ArgumentList: PSList | None = None)

GET_COMMAND_METADATA Message.

Get command metadata for commands available in a RunspacePool. Message is defined in MS-PSRP 2.2.2.14 GET_COMMAND_METADATA.

Parameters:
  • Name (PSList | None) – List of wildcard patterns specifying the command names that the server SHOULD return.

  • CommandType (CommandTypes | None) – The command types to search for.

  • Namespace (PSList | None) – The command namespaces containing the commands that the server SHOULD return.

  • ArgumentList (PSList | None) – Extra arguments passed to the higher layer above the PowerShell Remoting Protocol.

class psrpcore.types.HostDefaultData(ForegroundColor: ConsoleColor, BackgroundColor: ConsoleColor, CursorPosition: Coordinates, WindowPosition: Coordinates, CursorSize: PSInt, BufferSize: Size, WindowSize: Size, MaxWindowSize: Size, MaxPhysicalWindowSize: Size, WindowTitle: PSString)

HostInfo default data.

This defines the default data for a PSHost when creating a RunspacePool or Pipeline. This does not represent an actual .NET type but is an internal object representation used by PSRP itself. This type represents the hostDefaultData property documented at [MS-PSRP] 2.2.3.14 HostInfo.

Parameters:
  • ForegroundColor (ConsoleColor) – Color of the character on the screen buffer.

  • BackgroundColor (ConsoleColor) – Color behind characters on the screen buffer.

  • CursorPosition (Coordinates) – Cursor position in the screen buffer.

  • WindowPosition (Coordinates) – Position of the view window relative to the screen buffer.

  • CursorSize (PSInt) – Cursor size as a percentage 0..100.

  • BufferSize (Size) – Current size of the screen buffer, measured in character cells.

  • WindowSize (Size) – Current view window size, measured in character cells.

  • MaxWindowSize (Size) – Size of the largest window position for the current buffer.

  • MaxPhysicalWindowSize (Size) – Largest window possible ignoring the current buffer dimensions.

  • WindowTitle (PSString) – The titlebar text of the current view window.

class psrpcore.types.HostInfo(IsHostNull: bool | None = True, IsHostUINull: bool | None = True, IsHostRawUINull: bool | None = True, UseRunspaceHost: bool | None = True, HostDefaultData: HostDefaultData | None = None)

HostInfo.

Defines the PSHost information. Message is defined in [MS-PSRP] 2.2.3.14 HostInfo.

Parameters:
  • IsHostNull (bool | None) – Whether there is a PSHost False or not True.

  • IsHostUINull (bool | None) – Whether the PSHost implements the UI implementation methods False or not True.

  • IsHostRawUINull (bool | None) – Whether the PSHost UI implements the RawUI implementation methods False or not True.

  • UseRunspaceHost (bool | None) – When creating a pipeline, set this to True to get it to use the associated RunspacePool host.

  • HostDefaultData (HostDefaultData | None) – Host default data associated with the PSHost implementation. Can be None if not implemented.

class psrpcore.types.HostMethodIdentifier(value)

Host Method Identifier enum.

This is an enum class for the System.Management.Automation.Remoting.RemoteHostMethodId .NET class. It is documented in PSRP under [MS-PSRP] 2.2.3.17 Host Method Identifier.

The values are used in psrpcore.types.RunspacePoolHostCall and psrpcore.types.PipelineHostCall to identify what method should be invoked.

EnterNestedPrompt = 7
ExitNestedPrompt = 8
FlushInputBuffer = 47
GetBackgroundColor = 29
GetBufferContents = 50
GetBufferSize = 37
GetCurrentCulture = 4
GetCurrentUICulture = 5
GetCursorPosition = 31
GetCursorSize = 35
GetForegroundColor = 27
GetInstanceId = 3
GetIsRunspacePushed = 54
GetKeyAvailable = 45
GetMaxPhysicalWindowSize = 44
GetMaxWindowSize = 43
GetName = 1
GetRunspace = 55
GetVersion = 2
GetWindowPosition = 33
GetWindowSize = 39
GetWindowTitle = 41
MaxValue = 2147483647
MinValue = -2147483648
NotifyBeginApplication = 9
NotifyEndApplication = 10
PopRunspace = 53
Prompt = 23
PromptForChoice = 26
PromptForChoiceMultipleSelection = 56
PromptForCredential1 = 24
PromptForCredential2 = 25
PushRunspace = 52
ReadKey = 46
ReadLine = 11
ReadLineAsSecureString = 12
ScrollBufferContents = 51
SetBackgroundColor = 30
SetBufferContents1 = 48
SetBufferContents2 = 49
SetBufferSize = 38
SetCursorPosition = 32
SetCursorSize = 36
SetForegroundColor = 28
SetShouldExit = 6
SetWindowPosition = 34
SetWindowSize = 40
SetWindowTitle = 42
Write1 = 13
Write2 = 14
WriteDebugLine = 19
WriteErrorLine = 18
WriteLine1 = 15
WriteLine2 = 16
WriteLine3 = 17
WriteProgress = 20
WriteVerboseLine = 21
WriteWarningLine = 22
is_void() bool

Whether the method is a void method and doesn’t return data.

class psrpcore.types.InformationRecord(MessageData: PSObject | None = None, Source: PSString | None = None, TimeGenerated: PSDateTime | None = None, Tags: PSList | None = None, User: PSString | None = None, Computer: PSString | None = None, ProcessId: PSUInt | None = None, NativeThreadId: PSUInt | None = None, ManagedThreadId: PSUInt | None = None)

InformationRecord.

Defines a data structure used to represent informational context destined for the host or user. This represents the System.Management.Automation.InformationRecord .NET type.

Parameters:
  • MessageData (PSObject | None) – The message data for the informational record.

  • Source (PSString | None) – The source of the information record (script path, function name, etc.).

  • TimeGenerated (PSDateTime | None) – The time the informational record was generated.

  • Tags (PSList | None) – The tags associated with this informational record.

  • User (PSString | None) – The user that generated the informational record.

  • Computer (PSString | None) – THe computer that generated the informational record.

  • ProcessId (PSUInt | None) – The process that generated the informational record.

  • NativeThreadId (PSUInt | None) – The native thread that generated the informational record.

  • ManagedThreadId (PSUInt | None) – The managed thread that generated the informational record.

classmethod create(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) InformationRecord

Helper class for creating InformationRecords with defaults.

class psrpcore.types.InformationRecordMsg(MessageData: PSObject | None = None, Source: PSString | None = None, TimeGenerated: PSDateTime | None = None, Tags: PSList | None = None, User: PSString | None = None, Computer: PSString | None = None, ProcessId: PSUInt | None = None, NativeThreadId: PSUInt | None = None, ManagedThreadId: PSUInt | None = None)

INFORMATION_RECORD Message.

Information record from a command pipeline on the server. Message is defined in MS-PSRP 2.2.2.26 INFORMATION_RECORD.

Note

This message is only used in ProtocolVersion>=2.3 (PowerShell v5.1+).

Parameters:
  • MessageData (PSObject | None) – The message data for the informational record.

  • Source (PSString | None) – The source of the information record (script path, function name, etc.).

  • TimeGenerated (PSDateTime | None) – The time the informational record was generated.

  • Tags (PSList | None) – The tags associated with this informational record.

  • User (PSString | None) – THe user that generated the informational record.

  • Computer (PSString | None) – THe computer that generated the informational record.

  • ProcessId (PSUInt | None) – The process that generated the informational record.

  • NativeThreadId (PSUInt | None) – The native thread that generated the informational record.

  • ManagedThreadId (PSUInt | None) – The managed thread that generated the informational record.

class psrpcore.types.InformationalRecord(*args: Any, **kwargs: Any)

PowerShell InformationalRecord.

InformationalRecord (that is Debug, Warning, or Verbose) is a structure that contains additional information that a pipeline can output in addition to the regular data output. It is documented in PSRP under [MS-PSRP] 2.2.3.16 InformationalRecord. The invocation specific properties are documented under [MS-PSRP] 2.2.3.15.1 InvocationInfo. This also represents the System.Management.Automation.InformationalRecord .NET type.

Parameters:
  • Message (PSString | None) – The message writen by the command that created this record.

  • InvocationInfo (InvocationInfo | None) – The invocation info of the command that created this record.

  • PipelineIterationInfo (PSList | None) – The status of the pipeline when this record was created.

class psrpcore.types.InitRunspacePool(MinRunspaces: PSInt, MaxRunspaces: PSInt, PSThreadOptions: PSThreadOptions, ApartmentState: ApartmentState, HostInfo: HostInfo, ApplicationArguments: PSPrimitiveDictionary)

INIT_RUNSPACEPOOL Message.

Defines the Runspace Pool initialization data. Message is defined in MS-PSRP 2.2.2.2 INIT_RUNSPACEPOOL.

Parameters:
  • MinRunspaces (PSInt) – The minimum number of runspaces in the Runspace Pool.

  • MaxRunspaces (PSInt) – The maximum number of runspaces in the Runspace Pool.

  • PSThreadOptions (PSThreadOptions) – Thread options provided by the higher layer.

  • ApartmentState (ApartmentState) – Apart state provided by the higher layer.

  • HostInfo (HostInfo) – Host information.

  • ApplicationArguments (PSPrimitiveDictionary) – Application arguments provided by the higher layer.

class psrpcore.types.InvocationInfo(BoundParameters: PSDict | None = None, CommandOrigin: CommandOrigin | None = None, DisplayScriptPosition: ScriptExtent | None = None, ExpectingInput: bool | None = None, HistoryId: PSInt64 | None = None, InvocationName: PSString | None = None, Line: PSString | None = None, MyCommand: PSObject | None = None, OffsetInLine: PSInt | None = None, PipelineLength: PSInt | None = None, PipelinePosition: PSInt | None = None, PositionMessage: PSString | None = None, PSCommandPath: PSString | None = None, PSScriptRoot: PSString | None = None, ScriptLineNumber: PSInt | None = None, ScriptName: PSString | None = None, UnboundArguments: PSList | None = None)

InvocationInfo.

Describes how and where this command was invoked. This is the actual .NET type System.Management.Automation.InvocationInfo.

Parameters:
  • BoundParameters (PSDict | None) – Dictionary of parameters that were bound for this script or command.

  • CommandOrigin (CommandOrigin | None) – Command was being invoked inside the runspace or if it was an external request.

  • DisplayScriptPosition (ScriptExtent | None) – The position for the invocation or error.

  • ExpectingInput (bool | None) – The command is expecting input.

  • HistoryId (PSInt64 | None) – History that represents the command, if unavailable this will be -1.

  • InvocationName (PSString | None) – Command name used to invoke this script. If invoked through an alias then this would be the alias name.

  • Line (PSString | None) – The text of the line that contained this cmdlet invocation.

  • MyCommand (PSObject | None) – Basic information about the command.

  • OffsetInLine (PSInt | None) – Command’s character offset in that line. If the command was executed directly through the host interfaces, this will be -1.

  • PipelineLength (PSInt | None) – How many elements are in the containing pipeline.

  • PipelinePosition (PSInt | None) – Which element this command was in the containing pipeline.

  • PositionMessage (PSString | None) – Formatted message indicating where the cmdlet appeared in the line.

  • PSCommandPath (PSString | None) – The full path to the command from where it was being invoked.

  • PSScriptRoot (PSString | None) – The directory from where the command was being invoked.

  • ScriptLineNumber (PSInt | None) – The line number in the executing script that contains this cmdlet.

  • ScriptName (PSString | None) – The name of the script containing the cmdlet.

  • UnboundArguments (PSList | None) – The list of arguments that were not bound to any parameter.

class psrpcore.types.KeyInfo(VirtualKeyCode: PSInt | None = None, Character: PSChar | None = None, ControlKeyState: ControlKeyStates | None = None, KeyDown: bool | None = None)

KeyInfo.

Represents information of a keystroke. It is documented in PSRP under [MS-PSRP] 2.2.3.26 KeyInfo.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.KeyInfo .NET class.

Parameters:
  • VirtualKeyCode (PSInt | None) – A virtual key code that identifies the given key in a device-independent manner.

  • Character (PSChar | None) – Character corresponding to the pressed keys.

  • ControlKeyState (ControlKeyStates | None) – State of the control keys.

  • KeyDown (bool | None) – True if the event was generated when a key was pressed.

class psrpcore.types.NETException(Message: PSString, Data: PSDict | None = None, HelpLink: PSString | None = None, HResult: PSInt | None = None, InnerException: PSObject | None = None, Source: PSString | None = None, StackTrace: PSString | None = None, TargetSite: PSString | None = None)

.NET Exception.

Represents a .NET System.Exception type. It isn’t documented in MS-PSRP but is used when creating an ErrorRecord or just as a base of another exception type.

Parameters:
  • Message (PSString) – Message that describes the current exception.

  • Data (PSDict | None) – User defined information about the exception.

  • HelpLink (PSString | None) – A link to the help file associated with this exception.

  • HResult (PSInt | None) – A coded numerical value that is assigned to a specific exception.

  • InnerException (PSObject | None) – Exception instance that caused the current exception.

  • Source (PSString | None) – Name of the application or the object that causes the error.

  • StackTrace (PSString | None) – String representation of the immediate frames on the call stack.

  • TargetSite (PSString | None) – Method that throws the current exception.

class psrpcore.types.PSAliasProperty(name: str, alias: str, ps_type: type | None = None)

Alias Property

This is a property that gets a value based on another property or attribute of the PSObject. It is designed to replicate the functionality of PSAliasProperty. During serialization the alias property will just copy the value of the target it is pointing to. You cannot set a value to an alias property, see PSScriptProperty which allows the caller to define a way to get and set properties on an object dynamically.

Note

When an object that has an alias property is deserialized, the property is converted to a PSNoteProperty and the alias will no longer exist.

Parameters:
  • name (str) – The name of the property.

  • alias (str) – The name of the property or attribute to point to.

  • ps_type (type | None) – If set, the property value will be casted to this PSObject type.

alias

The target of the alias.

Type:

str

copy() PSAliasProperty

Create a copy of the property.

psrpcore.types.PSBool

alias of bool

class psrpcore.types.PSByte(*args: Any, **kwargs: Any)

The Unsigned byte primitive type.

This is the unsigned byte primitive type which represents the following types:

Python: int

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.6 Unsigned Byte

.NET: System.Byte

While this represents an int in Python it is artificially limited to values between 0 and 255 like a Byte on .NET.

MaxValue = 255
MinValue = 0
class psrpcore.types.PSByteArray(*args: Any, **kwargs: Any)

The Byte Array primitive type.

This is the byte array primitive type which represents the following types:

Python: bytes

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.17 Array of Bytes

.NET: System.Byte[]

class psrpcore.types.PSChar(*args: Any, **kwargs: Any)

The Char primitive type.

This is the char primitive type which represents the following types:

Python: int

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.2 Character

.NET: System.Char

A char in .NET represents a UTF-16 codepoint from u0000 to uFFFF. The codepoint may represent an invalid unicode character, say it’s 1 half of a surrogate pair, but it’s still a valid Char. A PSChar can be initialized just like an int() as long as the value is from 0 to 65535 inclusive. A PSChar can also be initialized from a single string character like PSChar(‘a’), any byte strings will be encoded as UTF-8 when getting the character. If a decimal value is used as a string then the PSChar instance will be the value of that codepoint of the character and not the decimal value itself.

class psrpcore.types.PSCredential(UserName: PSString, Password: PSSecureString)

PSCredential.

Represents a username and a password. It is documented in PSRP under [MS-PSRP] 2.2.3.25 PSCredential. It also represents the System.Management.Automation.PSCredential .NET type.

Note

To be able to serialize this object, a session key is exchanged between the host and the peer. If the peer does not support the session key exchange then this cannot be serialized.

Parameters:
  • UserName (PSString) – The username for the credential.

  • Password (PSSecureString) – The password for the credential.

class psrpcore.types.PSCredentialTypes(value)

System.Management.Automation.PSCredentialTypes enum flags.

Defines the valid types of credentials. Used by HostMethodIdentifier.PromptForCredential2 calls.

Note

This is an auto-generated Python class for the System.Management.Automation.PSCredentialTypes .NET class.

Default = 3

Default credentials (Generic | Domain).

Domain = 2

Credentials valid for a domain.

Generic = 1

Generic credentials.

MaxValue = 2147483647
MinValue = -2147483648
class psrpcore.types.PSCredentialUIOptions(value)

System.Management.Automation.PSCredentialUIOptions enum flags.

Defines the options available when prompting for credentials. Used by HostMethodIdentifier.PromptForCredential2 calls.

Note

This is an auto-generated Python class for the System.Management.Automation.PSCredentialUIOptions .NET class.

AlwaysPrompt = 2

Always prompt, even if a persisted credential was available.

Default = 1

Validates the username, but not its existence or correctness.

MaxValue = 2147483647
MinValue = -2147483648
ReadOnlyUsername = 3

Username is read-only, and the user may not modify it.

ValidateUserNameSyntax = 1

Validates the username, but not its existence or correctness.

none = 0

Performs no validation.

class psrpcore.types.PSCryptoProvider

Serizliation crypto provider

The CryptoProvider used by the serializer to encrypt and decrypt psrpcore.types.PSSecureString values. The method used to encrypt and decrypt these values differs across implementations.

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

class psrpcore.types.PSCustomObject(*args: Any, **kwargs: Any)

This is a PSCustomObject that can be created with an arbitrary amount of extended properties. It acts like a generic property bag and is designed to replicate the PSCustomObject syntax in PowerShell:

$obj = [PSCustomObject]@{
    Property = 'value'
}

Examples

>>> obj = PSCustomObject(Property='value')
>>> print(obj.Property)
abc

Note

Using PSTypeName as a parameter will define a custom PS type name for the instance. It will not add a property with the name PSTypeName.

class psrpcore.types.PSDateTime(*args: Any, **kwargs: Any)

The Date/Time primitive type.

This is the datetime primitive type which represents the following types:

Python: obj:datetime.datetime

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.4 Date/Time

.NET: System.DateTime

This extends the Python datetime.datetime class and adds a nanosecond attribute to track the nanoseconds. While the class can have a nanosecond precision, a serialized DateTime object can only go up to a .NET Tick which is 100s of nanoseconds.

classmethod strptime(date_string: str, format: str) PSDateTime

string, format -> new datetime parsed from a string (like time.strptime()).

class psrpcore.types.PSDecimal(*args: Any, **kwargs: Any)

The Decimal primitive type.

This is the decimal primitive type which represents the following types:

Python: decimal.Decimal

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.16 Decimal

.NET: System.Decimal

class psrpcore.types.PSDict(*args: Any, **kwargs: Any)

The Dictionary complex type.

This is the dictionary complex type which represents the following types:

Python: dict

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.2.6.4 Dictionaries

.NET: System.Collections.Hashtable

class psrpcore.types.PSDictBase(*args: Any, **kwargs: Any)

The base dictionary type.

This is the base dictionary PSObject type that all dictionary like objects should inherit from. It cannot be instantiated directly and is meant to be used as a base class for any .NET dictionary types.

Note

While you can implement your own custom dictionary .NET type like System.Collections.Generic.Dictionary<TKey, TValue>, any dictionary based .NET types will be deserialized by the remote PowerShell runspace as System.Collections.Hashtable. This .NET type is represented by PSDict.

class psrpcore.types.PSDouble(*args: Any, **kwargs: Any)

The Double primitive type.

This is the double primitive type which represents the following types:

Python: float

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.15 Double

.NET: System.Double

class psrpcore.types.PSDuration(*args: Any, **kwargs: Any)

The Duration primitive type.

This is the duration primitive type which represents the following types:

Python: datetime.timedelta

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.5 Duration

.NET: System.TimeSpan

This extends the Python datetime.timespan class and adds a nanoseconds attribute to track the nanoseconds. While the class can have a nanosecond precision, a serialized Duration object can only go up to a .NET Tick which is 100s of nanoseconds.

max = PSDuration(days=10675199, seconds=10085, microseconds=477580, nanoseconds=700)
min = PSDuration(days=-10675200, seconds=76314, microseconds=522419, nanoseconds=200)
resolution = PSDuration(nanoseconds=100)
class psrpcore.types.PSEnumBase(value)

The base enum PSObject type.

This is the base enum PSObject type that all enum complex objects should inherit from. Any objects that inherit PSEnumBase and require a base type that is not PSInt should set base_type=… when declaring the class.

An example enum would look like:

@PSType(["System.MyEnum"])
class MyEnum(PSEnumBase):
    Label = 1
    Other = 2

@PSType(["System.MyUIntEnum"])
class MyUIntEnum(PSEnumBase, base_type=PSUInt):
    Label = 1
    Other = 0xFFFFFFFF

A user of that enum would then access it like MyEnum.Label or MyEnum.Other. This class is designed for enums that allow only 1 value, if you require a flag like enum, use PSFlagBase as the base type.

MaxValue = 2147483647
MinValue = -2147483648
class psrpcore.types.PSFlagBase(value)

The base flags enum PSObject type.

This is like PSEnumBase but supports having multiple values set like [Flags] on an enum in .NET. Using any bitwise operations will preserve the type so MyFlags.Flag1 | MyFlags.Flag2 will still be an instance of MyFlags.

Like PSEnumBase, an implementing type can set base_type to another PS integer type if the base integer type is not Int32. An example flag enum would look like:

@PSType(["System.MyFlags"])
class MyFlags(PSFlagBase):
    Flag1 = 1
    Flag2 = 2
    Flag3 = 4

@PSType(["System.MyUIntFlags"])
class MyUIntFlags(PSFlagBase, base_type=PSUInt):
    Flag1 = 1
    Flag2 = 2
    Flag3 = 4
    All = 0xFFFFFFFF
MaxValue = 2147483647
MinValue = -2147483648
class psrpcore.types.PSGuid(*args: Any, **kwargs: Any)

The GUID/UUID primitive type.

This is the GUID/UUID primitive type which represents the following types:

Python: uuid.UUID

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.18 GUID

.NET: System.Guid

int
is_safe
class psrpcore.types.PSIEnumerable(*args: Any, **kwargs: Any)

The IEnumerable complex type.

This is the IEnumerable complex type which represents the following types:

Python: list

Native Serialization: no

PSRP: N/A - Mentioned in PSList

.NET System.Collections.IEnumerable

class psrpcore.types.PSInt(*args: Any, **kwargs: Any)

The Signed int primitive type.

This is the signed int primitive type which represents the following types:

Python: int

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.11 Signed Int

.NET: System.Int32

While this represents an int in Python it is artificially limited to values between -2147483648 and 2147483647 like an Int32 on .NET.

MaxValue = 2147483647
MinValue = -2147483648
class psrpcore.types.PSInt16(*args: Any, **kwargs: Any)

The Signed short primitive type.

This is the signed short primitive type which represents the following types:

Python: int

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.9 Signed Short

.NET: System.Int16

While this represents an int in Python it is artificially limited to values between -32768 and 32767 like an Int16 on .NET.

MaxValue = 32767
MinValue = -32768
class psrpcore.types.PSInt64(*args: Any, **kwargs: Any)

The Signed long primitive type.

This is the signed long primitive type which represents the following types:

Python: int

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.13 Signed Long

.NET: System.Int64

While this represents an int in Python it is artificially limited to values between -9223372036854775808 and 9223372036854775807 like an Int64 on .NET.

MaxValue = 9223372036854775807
MinValue = -9223372036854775808
class psrpcore.types.PSInvocationState(value)

PSInvocationState enum.

Defines the current state of the Pipeline. It is documented in PSRP under [MS-PSRP] 2.2.3.5 PSInvocationState.

Note

This is an auto-generated Python class for the System.Management.Automation.PSInvocationState .NET class.

Completed = 4

Pipeline has completed executing a command.

Disconnected = 6

Pipeline is in disconnected state.

Failed = 5

Pipeline completed abnormally due to an error.

MaxValue = 2147483647
MinValue = -2147483648
NotStarted = 0

Pipeline has not been started

Running = 1

Pipeline is executing.

Stopped = 3

Pipeline is completed due to a stop request.

Stopping = 2

Pipeline is stopping execution.

class psrpcore.types.PSList(*args: Any, **kwargs: Any)

The List complex type.

This is the queue complex type which represents the following types:

Python: list

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.2.6.3 List

.NET: System.Collections.ArrayList

class psrpcore.types.PSListBase(*args: Any, **kwargs: Any)

The base list type.

This is the base list PSObject type that all list like objects should inherit from. It cannot be instantiated directly and is meant to be used as a base class for any .NET list types.

Note

While you can implement your own custom list .NET type like System.Collections.Generic.List<T>, any list based .NET types will be deserialized by the remote PowerShell runspace as System.Collections.ArrayList. This .NET type is represented by PSList.

class psrpcore.types.PSNoteProperty(name: str, value: ~typing.Any | None = <class 'psrpcore.types._base._UnsetValue'>, mandatory: bool = False, ps_type: type | None = None)

Note Property

This is a property that stores a value as a name-value pair. Is is designed to replicate the functionality of PSNoteProperty and is typically the type of property to use when creating a PSObject.

Note

See PSPropertyInfo for more information on the mandatory argument.

Parameters:
  • name (str) – The name of the property.

  • value (Any | None) – The property value to set, if omitted the default is None.

  • mandatory (bool) – The property must be defined when creating a PSObject.

  • ps_type (type | None) – If set, the property value will be casted to this PSObject type.

copy() PSNoteProperty

Create a copy of the property.

class psrpcore.types.PSObject

The base PSObject type.

This is the base PSObject type that all PS object classes must inherit. It controls all the behaviour around getting and setting attributes that are based on PowerShell properties in a way that is similar to PowerShell itself.

When initialised directly this is a plain object without any properties. User add_member() to add new properties dynamically.

property PSAdapted: None

A dict of all the adapted properties.

property PSBase: None

The raw .NET object without the extended type system properties.

property PSExtended: None

A dict of all the extended properties.

PSObject = <psrpcore.types._base.PSObjectMeta object>

Class and instance attribute that defines the objects ETS.

property PSTypeNames: List[str]

Shortcut to PSObject.type_names, one of PowerShell’s reserved properties.

class psrpcore.types.PSPrimitiveDictionary(*args: Any, **kwargs: Any)

Primitive Dictionary.

A primitive dictionary represents a dictionary which contains only objects that are primitive types. While Python does not place any limitations on the types this object can contain, trying to serialize a PSPrimitiveDictionary with complex types to PowerShell will fail. The types that are allowed can be found at [MS-PSRP] 2.2.3.18 Primitive Dictionary.

class psrpcore.types.PSPropertyInfo(name: str, mandatory: bool = False, ps_type: type | None = None, value: ~typing.Any | None = <class 'psrpcore.types._base._UnsetValue'>, getter: ~typing.Callable[[~psrpcore.types._base.PSObject], ~typing.Any] | None = None, setter: ~typing.Callable[[~psrpcore.types._base.PSObject, ~typing.Any], None] | None = None)

Base metadata for an object property.

This is an abstract class that defines the property behaviour when it comes to getting and setting a property. There are three types of properties that have been implemented:

PSAliasProperty:

A property that points to another property, or Python attribute. This essentially creates a getter that calls ps_object[‘target’].

PSNoteProperty:

A property that contains it’s own value like a normal attribute/property in Python.

PSScriptProperty:

A property that uses a callable to get and optionally set a value on the ps_object.

The mandatory option controls whether the default __init__() function added to PSObjects without their own __init__() will validate that property was specified by the caller. This has no control over the serialization behaviour and any classes that define their own __init__() need to do their own validation.

Parameters:
  • name (str) – The name of the property.

  • mandatory (bool) – The property must be defined when creating a PSObject.

  • ps_type (type | None) – If set, the property value will be casted to this PSObject type.

  • value (Any | None) – The default value to set for the property.

  • getter (Callable[[PSObject], Any] | None) – A callable to get the property value based on the caller’s desired logic. Must not be set with value.

  • setter (Callable[[PSObject, Any], None] | None) – A callable to set the property value based on the caller’s desired logic. Must not be set with value.

name

See args.

Type:

str

ps_type

See args.

Type:

type

mandatory

See args.

Type:

bool

abstract copy() PSPropertyInfo

Create a copy of the property.

get_value(ps_object: PSObject) Any

Get the property value.

Gets the value of the property. If the property value is a callable then the value is invoked with the ps_object as an argument and the resulting value is casted to the ps_type if it is set.

Parameters:

ps_object (PSObject) – The PSObject instance the property is on. This is used when invoking a getter callable.

Returns:

The value of the property.

Return type:

(Any)

property getter: Callable[[PSObject], Any] | None

Returns the getter callable for the property if one was set.

set_value(value: Any, ps_object: PSObject) None

Set the property value.

Sets the value of the property to the value specified. The value will be casted to the property’s ps_type if defined unless it is a callable or None. Trying to set None on a mandatory property will also fail.

Parameters:
  • value (Any) – The value to set on the property.

  • ps_object (PSObject) – The PSObject instance the property is on. This is used when invoking the setter callable.

property setter: Callable[[PSObject, Any], None] | None

Returns the setter callable for the property if one was set.

class psrpcore.types.PSQueue(*args: Any, **kwargs: Any)

The Queue complex type.

This is the queue complex type which represents the following types:

Python: queue.Queue

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.2.6.2 Queue

.NET: System.Collections.Queue

class psrpcore.types.PSQueueBase(*args: Any, **kwargs: Any)

The base queue type.

This is the base queue PSObject type that all queue like objects should inherit from. It cannot be instantiated directly and is meant to be used as a base class for any .NET queue types.

Note

While you can implement your own custom queue .NET type like System.Collections.Generic.Queue<T>, any queue based .NET types will be deserialized by the remote PowerShell runspace as System.Collections.Queue. This .NET type is represented by PSQueue.

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

PSRP Mesage types.

The PowerShell Remoting Protocol message types identifiers. Each value corresponds to a PSRP message type and the unique identifier for that type.

ApplicationPrivateData = 135177

ApplicationPrivateData

ConnectRunspacePool = 65544

ConnectRunspacePool

CreatePipeline = 135174

CreatePipeline

DebugRecord = 266247

DebugRecordMsg

EncryptedSessionKey = 65542

EncryptedSessionKey

EndOfPipelineInput = 266243

EndOfPipelineInput

ErrorRecord = 266245

ErrorRecordMsg

GetAvailableRunspaces = 135175

GetAvailableRunspaces

GetCommandMetadata = 135178

GetCommandMetadata

InformationRecord = 266257

InformationRecordMsg

InitRunspacePool = 65540

InitRunspacePool

PipelineHostCall = 266496

PipelineHostCall

PipelineHostResponse = 266497

PipelineHostResponse

PipelineInput = 266242

PipelineInput

PipelineOutput = 266244

PipelineOutput

PipelineState = 266246

PipelineState

ProgressRecord = 266256

ProgressRecordMsg

PublicKey = 65541

PublicKey

PublicKeyRequest = 65543

PublicKeyRequest

ResetRunspaceState = 135180

ResetRunspaceState

RunspaceAvailability = 135172

RunspaceAvailability

RunspacePoolHostCall = 135424

RunspacePoolHostCall

RunspacePoolHostResponse = 135425

RunspacePoolHostResponse

RunspacePoolInitData = 135179

RunspacePoolInitData

RunspacePoolState = 135173

RunspacePoolState

SessionCapability = 65538

SessionCapability

SetMaxRunspaces = 135170

SetMaxRunspaces

SetMinRunspaces = 135171

SetMinRunspaces

UserEvent = 135176

UserEvent

VerboseRecord = 266248

VerboseRecordMsg

WarningRecord = 266249

WarningRecordMsg

classmethod get_message_id(msg: Type[PSObject]) PSRPMessageType
class psrpcore.types.PSSByte(*args: Any, **kwargs: Any)

The Signed byte primitive type.

This is the signed byte primitive type which represents the following types:

Python: int

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.7 Signed Byte

.NET: System.SByte

While this represents an int in Python it is artificially limited to values between -128 and 127 like an SByte on .NET.

MaxValue = 127
MinValue = -128
class psrpcore.types.PSScriptBlock(*args: Any, **kwargs: Any)

The ScriptBlock primitive type.

This is the PowerShell ScriptBlock primitive type which represents the following types:

While the primitive type represents a ScriptBlock in PowerShell there are some limitations when it comes to sending a scriptblock over a remote PSSession. The PSRP server will automatically convert the instance to a string so this type is mostly useless.

class psrpcore.types.PSScriptProperty(name: str, getter: Callable[[PSObject], Any], setter: Callable[[PSObject, Any], None] | None = None, mandatory: bool = False, ps_type: type | None = None)

Script Property

This is a property that can get and optionally set another property or attribute of a PSObject at runtime. It is designed to replicate the functionality of PSScriptProperty.

The getter callable must be a callable that has only 1 argument that is the PSObject the property is a member of. This allows the caller to retrieve a property of the PSObject at runtime or any other source as needed.

The setter callable must be a callable that has only 2 arguments, the first being the value that needs to be set and the second is the PSObject the property is a member of. A setter must be defined on the property for a value to be set.

Parameters:
  • name (str) – The name of the property.

  • getter (Callable[[PSObject], Any]) – The callable to run when getting a value for this property.

  • setter (Callable[[PSObject, Any], None] | None) – The callable to run when setting a value for this property.

  • mandatory (bool) – The property must be defined when creating a PSObject.

  • ps_type (type | None) – If set, the property value will be casted to this PSObjec type.

copy() PSScriptProperty

Create a copy of the property.

class psrpcore.types.PSSecureString(*args: Any, **kwargs: Any)

The Secure String primitive type.

This is the PowerShell secure string primitive type which represents the following types:

Python: N/A

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.24 Secure String

.NET: System.Security.SecureString

It is designed to mark a string as a secure string which will be encrypted as it is serialized. The plaintext value can be retrieved using the PSSecureString.decrypt() function.

Note

Before a PSSecureString can be created or decrypted from the peer, the session key must be exchanged.

Note

There are no guarantees of security when using this class. It is only useful when trying to encrypt data as it goes over the wire rather than marking it as sensitive data in Python. Because the plaintext value is cached the data may remain behind in memory before Python cleans up the value.

Parameters:
  • value (str) – The plaintext value to encrypt (when cipher is None) or the encrypted value (when cipher is not None).

  • cipher (PSCryptoProvider | None) – The PSCryptoProvider cipher used to encrypt or decrypt the secure string. If omitted then the value specified is treated as the plaintext and will be encrypted during serialization.

decrypt() PSString

Decrypts a PSSecureString into the plaintext string.

class psrpcore.types.PSSingle(*args: Any, **kwargs: Any)

The Single primitive type.

This is the single primitive type which represents the following types:

Python: float

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.14 Float

.NET: System.Single

class psrpcore.types.PSStack(*args: Any, **kwargs: Any)

The Stack complex type.

This is the stack complex type which represents the following types:

Python: list

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.2.6.1 Stack

.NET: System.Collections.Stack

A stack is a last-in, first-out setup but Python does not have a native stack type so this just uses a list.

class psrpcore.types.PSStackBase(*args: Any, **kwargs: Any)

The base stack type.

This is the base stack PSObject type that all stack like objects should inherit from. It cannot be instantiated directly and is meant to be used as the base class for any .NET stack types. A stack is a last-in, first out collection but Python does not have a native stack type so this just replicates the a Python list.

Note

While you can implement your own custom stack .NET type like System.Collections.Generic.Stack<T>, any stack based .NET types will be deserialized by the remote PowerShell runspace as System.Collections.Stack. This .NET type is represented by PSStack.

class psrpcore.types.PSString(*args: Any, **kwargs: Any)

The String primitive type.

This is the string primitive type which represents the following types:

Python: str

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.1 String

.NET: System.String

class psrpcore.types.PSThreadOptions(value)

System.Management.Automation.Runspaces.PSThreadOptions enum.

Control whether a new thread is created when a command is executed within a Runspace. It is documented in PSRP under [MS-PSRP] 2.2.3.6 PSThreadOptions.

Note

This is an auto-generated Python class for the System.Management.Automation.Runspaces.PSThreadOptions .NET class.

Default = 0

Use the server thread option settings.

MaxValue = 2147483647
MinValue = -2147483648
ReuseThread = 2

Creates a new thread for the first invocation and then re-uses that thread in subsequent invocations.

UseCurrentThread = 3

Doesn’t create a new thread; the execution occurs on the thread that called Invoke.

UseNewThread = 1

Creates a new thread for each invocation.

class psrpcore.types.PSType(type_names: List[str] | None = None, adapted_properties: List[PSPropertyInfo] | None = None, extended_properties: List[PSPropertyInfo] | None = None, *, skip_inheritance: bool = False, rehydrate: bool = True, tag: str | None = None)

PSType class decorator.

This is a class decorator that should be added to any Python class that represents a .NET type. It modifies the class to use the PowerShell type system like extended properties. A class that uses this decorator must inherit from PSObject.

If the class also has a base PSType class it will inherit all the types and properties of that base class unless skip_inheritance=True is set.

Parameters:
  • type_names (List[str] | None) – A list of .NET types the class represents.

  • adapted_properties (List[PSPropertyInfo] | None) – A list of PSPropertyInfo to denote the native .NET properties the class has.

  • extended_properties (List[PSPropertyInfo] | None) – A list of PSPropertyInfo to denote the extended PowerShell properties the class has.

  • skip_inheritance (bool) – Skip inheriting the type and properties from the base class.

  • rehydrate (bool) – Registers the type for deserialisation.

  • tag (str | None) – Used internally to denote the CLIXML element tag value.

class psrpcore.types.PSUInt(*args: Any, **kwargs: Any)

The Unsigned int primitive type.

This is the unsigned integer primitive type which represents the following types:

Python: int

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.10 Unsigned Int

.NET: System.UInt32

While this represents an int in Python it is artificially limited to values between 0 and 4294967295 like a UInt32 on .NET.

MaxValue = 4294967295
MinValue = 0
class psrpcore.types.PSUInt16(*args: Any, **kwargs: Any)

The Unsigned short primitive type.

This is the unsigned short primitive type which represents the following types:

Python: int

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.8 Unsigned Short

.NET: System.UInt16

While this represents an int in Python it is artificially limited to values between 0 and 65535 like a UInt16 on .NET.

MaxValue = 65535
MinValue = 0
class psrpcore.types.PSUInt64(*args: Any, **kwargs: Any)

The Unsigned long primitive type.

This is the unsigned long primitive type which represents the following types:

Python: int

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.12 Unsigned Long

.NET: System.UInt64

While this represents an int in Python it is artificially limited to values between 0 and 18446744073709551615 like a UInt64 on .NET.

MaxValue = 18446744073709551615
MinValue = 0
class psrpcore.types.PSUri(*args: Any, **kwargs: Any)

The URI primitive type.

This is the URI primitive type which represents the following types:

Python: str

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.19 URI

.NET: System.Uri

While the primitive type represents a URI, this is merely a URI as a string in Python. You will need need to use a separate function to parse this URI like urllib.parse.urlparse().

class psrpcore.types.PSVersion(*args: Any, **kwargs: Any)

The Version primitive type.

This is the Version primitive type which represents the following types:

Python: N/A

Native Serialization: yes

PSRP: [MS-PSRP] 2.2.5.1.21 Version

.NET: System.Version

This is a custom implementation of a basic Version structure that matches the .NET System.Version class. A valid .NET Version must have the major and minor values defined as an integer and the build and revision are optional integer values.

This class is able to sort multiple PSVersions but not with other Python version structures.

Parameters:
  • version_str – The version as a string, e.g. ‘1.2’, ‘0.0.1’, ‘1.2.3.4’, ‘10.0.123.10’.

  • major – The major version when not using version_str.

  • minor – The minor version when not using version_str.

  • build – The optional build version when not using version_str.

  • revision – The optional revision when not using version_str.

major

See parameters.

Type:

int

minor

See parameters.

Type:

int

build

See parameters.

Type:

int, optional

revision

See parameters.

Type:

int, optional

class psrpcore.types.PSXml(*args: Any, **kwargs: Any)

The XML Document primitive type.

This is the XML Document primitive type which represents the following types:

Python: str

Native Serialization: no

PSRP: [MS-PSRP] 2.2.5.1.22 XML Document

.NET: System.Xml.XmlDocument

While the primitive type represents an XML Document, this is merely an XML value as a string in Python. You will still need to use an XML library to parse the value.

class psrpcore.types.PipelineHostCall(ci: PSInt64, mi: HostMethodIdentifier, mp: PSList)

PIPELINE_HOST_CALL Message.

Method call on the host associated with the pipeline invocation settings on the server. Message is defined in MS-PSRP 2.2.2.27 PIPELINE_HOST_CALL.

Parameters:
  • ci (PSInt64) – The Call ID associated with this operation.

  • mi (HostMethodIdentifier) – The host method identifier.

  • mp (PSList) – The parameters for the method.

class psrpcore.types.PipelineHostResponse(ci: PSInt64, mi: HostMethodIdentifier, mr: PSObject | None = None, me: ErrorRecord | None = None)

PIPELINE_HOST_RESPONSE Message.

Response from a host call executed on the client’s host. Message is defined in MS-PSRP 2.2.2.28 PIPELINE_HOST_RESPONSE.

Parameters:
  • ci (PSInt64) – The Call ID associated with this operation.

  • mi (HostMethodIdentifier) – The host method identifier.

  • mr (PSObject | None) – The return value of the method.

  • me (ErrorRecord | None) – Exception thrown by a host method invocation.

class psrpcore.types.PipelineInput

PIPELINE_INPUT Message.

Input to a command pipeline on the server. Message is defined in MS-PSRP 2.2.2.17 PIPELINE_INPUT. The actual object is the serialized object that is being sent as input.

class psrpcore.types.PipelineOutput

PIPELINE_OUTPUT Message.

Output of a command pipeline on the server. Message is defined in MS-PSRP 2.2.2.19 PIPELINE_OUTPUT. The actual object is the serialized object that is being outputted from the server.

class psrpcore.types.PipelineResultTypes(value)

System.Management.Automation.Runspaces.PipelineResultTypes enum flags.

Defines the types of streams coming out of a pipeline. It is documented in PSRP under [MS-PSRP] 2.2.3.31 PipelineResultTypes. .NET and MS-PSRP have separate values but .NET is used as it is the correct source. Technically the values are not designed as flags but there are some older APIs that combine Output | Error together.

Note

This is an auto-generated Python class for the System.Management.Automation.Runspaces.PipelineResultTypes .NET class.

All = 7

All streams.

Debug = 5

Debug stream.

Error = 2

Error stream.

Information = 6

Information stream.

MaxValue = 2147483647
MinValue = -2147483648
Null = 8

Redirect to nothing.

Output = 1

Output stream.

Verbose = 4

Verbose stream.

Warning = 3

Warning stream.

none = 0

Default streaming behaviour.

class psrpcore.types.PipelineState(PipelineState: PSInt, ExceptionAsErrorRecord: ErrorRecord | None = None)

PIPELINE_STATE Message.

State information of a command pipeline on the server. Message is defined in MS-PSRP 2.2.2.21 PIPELINE_STATE. The raw PipelineState values correlate to PSInvocationState.

Parameters:
  • PipelineState (PSInt) – State information of the command pipeline.

  • ExceptionAsErrorRecord (ErrorRecord | None) – The optional error record associated with the Pipeline state error.

class psrpcore.types.ProgressRecord(ActivityId: PSInt, Activity: PSString, StatusDescription: PSString, CurrentOperation: PSString | None = None, ParentActivityId: PSInt | None = -1, PercentComplete: PSInt | None = -1, RecordType: ProgressRecordType | None = <ProgressRecordType.Processing: 0>, SecondsRemaining: PSInt | None = -1)

ProgressRecord.

Defines a data structure used to represent the status of an ongoing operation at a point in time. This represents the System.Management.Automation.ProgressRecord .NET type.

Parameters:
  • Activity (PSString) – Description of the activity.

  • ActivityId (PSInt) – Id of the activity, used as a key for the linking of subordinate activities.

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

  • ParentActivityId (PSInt | None) – Id of the activity for which this is a subordinate.

  • PercentComplete (PSInt | None) – Percentage of total work for the activity that is completed.

  • RecordType (ProgressRecordType | None) – Type of record represented by this instance.

  • SecondsRemaining (PSInt | None) – Estimated time remaining until the activity is complete.

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

class psrpcore.types.ProgressRecordMsg(Activity: PSString | None = None, ActivityId: PSInt | None = None, StatusDescription: PSString | None = None, CurrentOperation: PSString | None = None, ParentActivityId: PSInt | None = None, PercentComplete: PSInt | None = None, Type: ProgressRecordType | None = None, SecondsRemaining: PSInt | None = None)

PROGRESS_RECORD Message.

Progress record from a command pipeline on the server. Message is defined in MS-PSRP 2.2.2.25 PROGRESS_RECORD.

Parameters:
  • Activity (PSString | None) – Description of the activity.

  • ActivityId (PSInt | None) – Id of the activity, used as a key for the linking of subordinate activities.

  • StatusDescription (PSString | None) – Current status of the operation, e.g. “35 of 50 items copied”.

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

  • ParentActivityId (PSInt | None) – Id of the activity for which this is a subordinate.

  • PercentComplete (PSInt | None) – Percentage of total work for the activity that is completed.

  • Type (ProgressRecordType | None) – Type of record represented by this instance.

  • SecondsRemaining (PSInt | None) – Estimated time remaining until the activity is complete.

class psrpcore.types.ProgressRecordType(value)

System.Management.Automation.ProgressRecordType enum.

Defines two types of progress record that refer to the beginning (or middle) and end of an operation.

Note

This is an auto-generated Python class for the System.Management.Automation.ProgressRecordType .NET class.

Completed = 1

Operation is complete.

MaxValue = 2147483647
MinValue = -2147483648
Processing = 0

Operation just started or is not yet complete.

class psrpcore.types.PublicKey(PublicKey: PSString)

PUBLIC_KEY Message.

Defines the public key created by the client used in the session key exchange. Message is defined in MS-PSRP 2.2.2.3 - PUBLIC_KEY.

Parameters:

PublicKey (PSString) – The base64 encoding of the PKCS1 formatted public key.

class psrpcore.types.PublicKeyRequest(*args: Any, **kwargs: Any)

PUBLIC_KEY_REQUEST Message.

This is a message that the server sends the client when it wants to start the encryption key exchange. Message is defined in MS-PSRP 2.2.2.5 - PUBLIC_KEY_REQUEST.

class psrpcore.types.ReadKeyOptions(value)

System.Management.Automation.Host.ReadKeyOptions enum flags.

Governs the behavior of HostMethodIdentifier.ReadKey.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.ReadKeyOptions .NET class.

AllowCtrlC = 1

Allow Ctrl-C to be processed as a keystroke, as opposed to causing a break event.

IncludeKeyDown = 4

Include key down events. One of IncludeKeyDown and IncludeKeyUp or both must be specified.

IncludeKeyUp = 8

Include key up events. One of IncludeKeyDown and IncludeKeyUp or both must be specified.

MaxValue = 2147483647
MinValue = -2147483648
NoEcho = 2

Do not display the character for the key in the window when pressed.

class psrpcore.types.Rectangle(Left: PSInt, Top: PSInt, Right: PSInt, Bottom: PSInt)

Rectangle.

Represents a rectangular region of the screen.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.Rectangle .NET class.

Parameters:
  • Left (PSInt) – Gets and sets the left side of the rectangle.

  • Top (PSInt) – Gets and sets the top of the rectangle.

  • Right (PSInt) – Gets and sets the right side of the rectangle.

  • Bottom (PSInt) – Gets and sets the bottom of the rectanngle.

class psrpcore.types.RemoteStreamOptions(value)

System.Management.Automation.RemoteStreamOptions enum flags.

Control whether InvocationInfo is added to items in the Error, Warning, Verbose and Debug streams during remote calls. It is documented in PSRP under [MS-PSRP] 2.2.3.8 RemoteStreamOptions.

Note

This is an auto-generated Python class for the System.Management.Automation.RemoteStreamOptions .NET class.

AddInvocationInfo = 15

InvocationInfo is added to all stream records.

AddInvocationInfoToDebugRecord = 4

InvocationInfo is added to any Debug InformationalRecord.

AddInvocationInfoToErrorRecord = 1

InvocationInfo is added to any ErrorRecord.

AddInvocationInfoToVerboseRecord = 8

InvocationInfo is added to any Verbose InformationalRecord.

AddInvocationInfoToWarningRecord = 2

InvocationInfo is added to any Warning InformationalRecord.

MaxValue = 2147483647
MinValue = -2147483648
none = 0

InvocationInfo is not added to any stream record.

class psrpcore.types.ResetRunspaceState(ci: PSInt64)

RESET_RUNSPACE_STATE Message.

Reset RunspacePool Runspace state. Message is defined in MS-PSRP 2.2.2.31 RESET_RUNSPACE_STATE.

Note

This message is only used in ProtocolVersion>=2.3 (PowerShell v5.1+).

Parameters:

ci (PSInt64) – The Call ID associated with this operation.

class psrpcore.types.RunspaceAvailability(SetMinMaxRunspacesResponse: PSObject, ci: PSInt64)

RUNSPACE_AVAILABILITY Message.

A response to either set maximum runspaces or set minimum runspaces in a RunspacePool or request for available runspaces in a RunspacePool. Message is defined in MS-PSRP 2.2.2.8 - RUNSPACE_AVAILABILITY.

Parameters:
  • SetMinMaxRunspacesResponse (PSObject) – A PSBool for a set min/max response or a PSInt64 for a get available response.

  • ci (PSInt64) – The Call ID the message is related to.

class psrpcore.types.RunspacePoolHostCall(ci: PSInt64, mi: HostMethodIdentifier, mp: PSList)

RUNSPACEPOOL_HOST_CALL Message.

Method call on the host associated with the RunspacePool on the server. Message is defined in MS-PSRP 2.2.2.15 RUNSPACEPOOL_HOST_CALL.

Parameters:
  • ci (PSInt64) – The Call ID associated with this operation.

  • mi (HostMethodIdentifier) – The host method identifier.

  • mp (PSList) – The parameters for the method.

class psrpcore.types.RunspacePoolHostResponse(ci: PSInt64, mi: HostMethodIdentifier, mr: PSObject | None = None, me: ErrorRecord | None = None)

RUNSPACEPOOL_HOST_RESPONSE Message.

Response from a host call executed on the client RunspacePool’s host. Message is defined in MS-PSRP 2.2.2.16 RUNSPACEPOOL_HOST_RESPONSE.

Parameters:
  • ci (PSInt64) – The Call ID associated with this operation.

  • mi (HostMethodIdentifier) – The host method identifier.

  • mr (PSObject | None) – The return value of the method.

  • me (ErrorRecord | None) – Exception thrown by a host method invocation.

class psrpcore.types.RunspacePoolInitData(MinRunspaces: PSInt, MaxRunspaces: PSInt)

RUNSPACEPOOL_INIT_DATA Message.

RunspacePool initialization data. Message is defined in MS-PSRP 2.2.2.30 RUNSPACEPOOL_INIT_DATA.

Note

This message is only used in ProtocolVersion>=2.2 (PowerShell v3.0+).

Parameters:
  • MinRunspaces (PSInt) – Minimum number of runspaces in the Runspace Pool.

  • MaxRunspaces (PSInt) – Maximum number of runspaces in the RUnspace Pool.

class psrpcore.types.RunspacePoolState(value)

RunspacePoolState enum.

Defines the current state of the Runspace Pool. It is documented in PSRP under [MS-PSRP] 2.2.3.4 RunspacePoolState and while it shares the same name as the .NET type System.Management.Automation.Runspaces.RunspacePoolState it has a few extra names and some values that do not match. The .NET enum is used here as that’s what PowerShell uses internally.

BeforeOpen = 0

Beginning state upon creation.

Broken = 5

The RunspacePool has been disconnected abnormally.

Closed = 3

The RunspacePool is closed.

Closing = 4

The RunspacePool is being closed.

Connecting = 8

The RunspacePool is being connected.

Disconnected = 7

The RunspacePool has been disconnected.

Disconnecting = 6

The RunspacePool is being disconnected.

MaxValue = 2147483647
MinValue = -2147483648
Opened = 2

The RunspacePool is created and valid.

Opening = 1

A RunspacePool is being created.

class psrpcore.types.RunspacePoolStateMsg(RunspaceState: PSInt, ExceptionAsErrorRecord: ErrorRecord | None = None)

RUNSPACEPOOL_STATE Message.

Defines the state of the RunspacePool. Message is defined in MS-PSRP 2.2.2.9 RUNSPACEPOOL_STATE. The raw RunspaceState values correlate to RunspacePoolState.

Parameters:
  • RunspaceState (PSInt) – The RunspacePool state information as an integer.

  • ExceptionAsErrorRecord (ErrorRecord | None) – The optional error record associated with the RunspacePool error.

class psrpcore.types.ScriptExtent(*args: Any, **kwargs: Any)

ScriptExtent.

A script extend used to customize the display of error location information. This is the actual .NET type System.Management.Automation.Language.ScriptExtent.

Parameters:
class psrpcore.types.ScriptPosition(File: PSString | None = None, LineNumber: PSInt | None = None, ColumnNumber: PSInt | None = None, Line: PSString | None = None, Offset: PSInt | None = None)

ScriptPosition.

Represents a single point in a script. This script may come from a file or interactive input. This is the actual .NET type System.Management.Automation.Language.ScriptPosition.

Parameters:
  • File (PSString | None) – The name of the file, or if the script did not come from a file, then null.

  • LineNumber (PSInt | None) – The line number of the position, with the value 1 being the first line.

  • ColumnNumber (PSInt | None) – The column number of the position, with the value 1 being the first column.

  • Line (PSString | None) – The complete text of the line that this position is included on.

Offset

Not used in pwsh.

Type:

PSInt

class psrpcore.types.SessionCapability(PSVersion: PSVersion, protocolversion: PSVersion, SerializationVersion: PSVersion, TimeZone: PSByteArray | None = None)

SESSION_CAPABILITY Message.

Defines the session capability and protocol versions. Message is defined in MS-PSRP 2.2.2.1 SESSION_CAPABILITY. The TimeZone property is a .NET type serialized to bytes as defined by MS-PSRP 2.2.3.10.1 CurrentSystemTimeZone.

Parameters:
  • PSVersion (PSVersion) – The version of the higher-layer application.

  • protocolversion (PSVersion) – The version of the PowerShell Remoting Protocol.

  • SerializationVersion (PSVersion) – The version of the serialization system.

  • TimeZone (PSByteArray | None) – The time zone of the client.

class psrpcore.types.SessionStateEntryVisibility(value)

System.Management.Automation.SessionStateEntryVisibility enum.

Defines the visibility of execution environment elements.

Note

This is an auto-generated Python class for the System.Management.Automation.SessionStateEntryVisibility .NET class.

MaxValue = 2147483647
MinValue = -2147483648
Private = 1

Entries are not visible to requests from outside the runspace.

Public = 0

Entries are visible to requests from outside the runspace.

class psrpcore.types.SetMaxRunspaces(MaxRunspaces: PSInt, ci: PSInt64)

SET_MAX_RUNSPACES Message.

Set maximum runspaces in a RunspacePool. Message is defined in MS-PSRP 2.2.2.6 - SET_MAX_RUNSPACES.

Parameters:
  • MaxRunspaces (PSInt) – The maximum runspaces in a pool.

  • ci (PSInt64) – The Call ID the message is related to.

class psrpcore.types.SetMinRunspaces(MinRunspaces: PSInt, ci: PSInt64)

SET_MIN_RUNSPACES Message.

Set minimum runspaces in a RunspacePool. Message is defined in MS-PSRP 2.2.2.7 - SET_MIN_RUNSPACES.

Parameters:
  • MinRunspaces (PSInt) – The minimum runspaces in a pool.

  • ci (PSInt64) – The Call ID the message is related to.

class psrpcore.types.Size(Width: PSInt, Height: PSInt)

Represents a width and height pair. It is documented under [MS-PSRP] 2.2.3.2 Size but the PSRP documentation represents how this value is serialized under HostDefaultData not the .NET type.

Note

This is an auto-generated Python class for the System.Management.Automation.Host.Size .NET class.

Parameters:
  • Width (PSInt) – The width of an area.

  • Height (PSInt) – The height of an area.

class psrpcore.types.UserEvent(EventIdentifier: PSInt | None = None, SourceIdentifier: PSString | None = None, TimeGenerated: PSDateTime | None = None, Sender: PSObject | None = None, SourceArgs: PSObject, MessageData: PSObject | None = None, ComputerName: PSString | None = None, RunspaceId: PSGuid | None = None)

USER_EVENT Message.

Report a user-defined event from a remote runspace. Message is defined in MS-PSRP 2.2.2.12 USER_EVENT.

Parameters:
  • EventIdentifier (PSInt | None) – The event identifier.

  • SourceIdentifier (PSString | None) – The source identifier.

  • TimeGenerated (PSDateTime | None) – The time when the event was generated.

  • Sender (PSObject | None) – The sender of the event.

  • SourceArgs (PSObject) – Event arguments.

  • MessageData (PSObject | None) – Message data associated with the event.

  • ComputerName (PSString | None) – Name of the computer where the event was fired.

  • RunspaceId (PSGuid | None) – The ID of the runspace.

class psrpcore.types.VerboseRecord(*args: Any, **kwargs: Any)

VerboseRecord.

A verbose record in the PSInformationalBuffers. This represents the System.Management.Automation.VerboseRecord .NET type.

class psrpcore.types.VerboseRecordMsg(*args: Any, **kwargs: Any)

VERBOSE_RECORD Message.

Verbose record from a command pipeline on the server. Message is defined in MS-PSRP 2.2.2.23 VERBOSE_RECORD.

class psrpcore.types.WarningRecord(*args: Any, **kwargs: Any)

WarningRecord.

A warning record in the PSInformationalBuffers. This represents the System.Management.Automation.WarningRecord .NET type.

class psrpcore.types.WarningRecordMsg(*args: Any, **kwargs: Any)

WARNING_RECORD Message.

Warning record from a command pipeline on the server. Message is defined in MS-PSRP 2.2.2.24 WARNING_RECORD.

psrpcore.types.add_alias_property(obj: PSObject | Type[PSObject], name: str, alias: str, ps_type: type | None = None, force: bool = False) None

Add an alias property to a PSObject.

Adds an alias as an extended property to a PSObject class or a specific instance of a class.

Parameters:
  • obj (PSObject | Type[PSObject]) – The PSObject to add the alias to.

  • name (str) – The name of the new alias property.

  • alias (str) – The alias target.

  • ps_type (type | None) – Optional PSObject type that the alias value will get casted to.

  • force (bool) – Overwrite the existing property True or fail False.

psrpcore.types.add_member(obj: PSObject | Type[PSObject], prop: PSPropertyInfo, force: bool = False) None

Add an extended property.

This can add an extended property to a PSObject class or a specific instance of a class. This replicates some of the functionality in Update-TypeData and Add-Member in PowerShell. If a property under the same name already exists under that PSObject then force=True is required to replace it. The same applies if there is an existing adapted property on the object.

See add_alias_property(), add_note_property(), and add_script_property() for simplified versions of this function.

Parameters:
  • obj (PSObject | Type[PSObject]) – The PSObject class or an instance of a PSObject class to add the extended property to.

  • prop (PSPropertyInfo) – The property to add to the object or class.

  • force (bool) – Overwrite the existing property True or fail False.

psrpcore.types.add_note_property(obj: PSObject | Type[PSObject], name: str, value: Any, ps_type: type | None = None, force: bool = False) None

Add a note property to a PSObject.

Adds a note property as an extended property to a PSObject class or a specific instance of a class. A note property is a simple key/value pair with a static value.

Parameters:
  • obj (PSObject | Type[PSObject]) – The PSObject to add the note property to.

  • name (str) – The name of the new note property.

  • value (Any) – The value of the new note property

  • ps_type (type | None) – Optional PSObject type that the value will get casted to.

  • force (bool) – Overwrite the existing property True or fail False.

psrpcore.types.add_script_property(obj: PSObject | Type[PSObject], name: str, getter: Callable[[PSObject], Any], setter: Callable[[PSObject, Any], None] | None = None, ps_type: type | None = None, force: bool = False) None

Add a script property to a PSObject.

Adds a script property as an extended property to a PSObject class or a specific instance of a class. A script property has a callable getter and optional setter function that is run when the property’s value is requested or set.

Parameters:
  • obj (PSObject | Type[PSObject]) – The PSObject to add the alias to.

  • name (str) – The name of the new alias property.

  • getter (Callable[[PSObject], Any]) – The callable to run when getting a value for this property.

  • setter (Callable[[PSObject, Any], None] | None) – The callable to run when setting a value for this property.

  • ps_type (type | None) – Optional PSObject type that the alias value will get casted to.

  • force (bool) – Overwrite the existing property True or fail False.

psrpcore.types.deserialize(value: Element, cipher: PSCryptoProvider, **kwargs: Any) bool | PSObject | None

Deserialize CLIXML to a Python object.

Deserializes a CLIXML XML Element from .NET to a Python object.

Parameters:
  • value (Element) – The CLIXML XML Element to deserialize to a Python object.

  • cipher (PSCryptoProvider) – The Runspace Pool cipher to use for SecureStrings.

  • kwargs (Any) – Optional parameters to sent to the FromPSObjectForRemoting method on classes that use that.

Returns:

The CLIXML as an XML Element object.

Return type:

Optional[Union[bool, PSObject]]

psrpcore.types.deserialize_clixml(clixml: str, cipher: PSCryptoProvider, preserve_streams: bool = False) list[Any | tuple[Any, ClixmlStream]]

Deserialize a CLIXML string to Python objects.

Deserializes a CLIXML CML string produced by pwsh -OutputFormat xml into the Python objects they represent. The string can start with the known CLIXML prefix ‘#< CLIXMLn’ as the code will strip it out if present.

The raw CLIXML string can be from stdout of pwsh -OutputFormat xml or from output of:

[System.Management.Automation.PSSerialize]::Serialize($value)

When preserve_streams=True, the stream name is denoted by the S XML attribute. If the attribute does not exist or is set to an unknown value it will be automatically converted to OUTPUT.

Parameters:
  • clixml (str) – The CLIXML string from PowerShell.

  • cipher (PSCryptoProvider) – The Runspace Pool cipher to use for SecureStrings.

  • preserve_stream – Output each object as a tuple with the first value being the deserialized object and the second value being the ClixmlStream as annotated by the S XML attribute.

Returns:

The list of Python objects that were created from the CLIXML string. Each entry will be a tuple if preserve_streams=True.

Return type:

list[Any]

psrpcore.types.ps_isinstance(obj: PSObject, other: Type[PSObject] | Tuple[Type[PSObject], ...] | str | Tuple[str, ...], ignore_deserialized: bool = False) bool

Checks the inheritance of a PSObject.

This checks if a PSObject is an instance of another PSObject. Instead of checking based on the Python inheritance rules it checks based on the .NET TypeNames set for that instance. The check will loop through the PSTypeNames of the obj passed in and see if any of those types match the first PSTypeName of any of the other objects referenced.

If check_deserialized=True, then any types starting with Deserialized. will also match against the non-deserialized types, e.g. Deserialized.System.Collections.Hashtable will be an instance of System.Collections.Hashtable.

Parameters:
  • obj (PSObject) – The object to check if it is inherited from the other types.

  • other (Type[PSObject] | Tuple[Type[PSObject], ...] | str | Tuple[str, ...]) – The type to check if obj is inherited from. Can also be a list of .NET types as a string.

  • ignore_deserialized (bool) – Whether to treat Deserialized.* instances as they would be serialized.

Returns:

Whether the obj is inherited from any of the other types in .NET.

Return type:

bool

psrpcore.types.serialize(value: Any | None, cipher: PSCryptoProvider, **kwargs: Any) Element

Serialize the Python object to CLIXML.

Serializes a Python object to a CLIXML element for use in .NET.

Parameters:
  • value (Any | None) – The value to serialize.

  • cipher (PSCryptoProvider) – The Runspace Pool cipher to use for SecureStrings.

  • kwargs (Any) – Optional parameters to sent to the ToPSObjectForRemoting method on classes that use that.

Returns:

The CLIXML as an XML Element object.

Return type:

ElementTree.Element

psrpcore.types.serialize_clixml(value: Any | tuple[Any | None, ClixmlStream] | None, cipher: PSCryptoProvider) str

Serializes the Python object(s) to a CLIXML string.

Serializes the provided value to a CLIXML string that can be used independently to PSRemoting. The value provided can be used with:

[System.Management.Automation.PSSerialize]::Deserialize($value)

If the provided value is a list each entry will be appended to the root Objs element. To serialize the list as a PowerShell list/array object in the Objs element, wrap the value inside another list.

value = [1, 2, 3]
serialize_clixml([value], cipher)

Each value provided can also be a tuple of 2 elements where the first elements is the value to serialize and the second element is the stream to associate it with based on the psrpcore.types.ClixmlStream value. PowerShell accepts the following types with each stream:

OUTPUT - Any

ERROR - psrpcore.types.ErrorRecord or str

DEBUG, VERBOSE, WARNING - str

INFORMATION - psrpcore.types.InformationRecord or str

PROGRESS - psrpcore.types.ProgressRecord

Using a string with he ERROR, DEBUG, VERBOSE, WARNING, and INFORMATION CLIXML stream will result in a record with that string message. Using other types will result in the object being casted to a string or undefined behaviour.

Parameters:
Returns:

The CLIXML string.

Return type:

str