Skip to content

$Context.CurrentFile.GetText not compatible with $Context.SelectedRange #1496

Open
@itfranck

Description

@itfranck

In the Powershell 5.1 version, the following code do not work:

$Context = $psEditor.GetEditorContext()
$Context.CurrentFile.GetText($context.SelectedRange)

This seems to be a type error

Cannot find an overload for "GetText" and the argument count: "1".
At line:1 char:1
+ $text = $Context.CurrentFile.GetText($context.SelectedRange)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Solution is to do the following

    $Context = $psEditor.GetEditorContext()
    $Range = [Microsoft.PowerShell.EditorServices.Extensions.FileRange]::new($context.SelectedRange.Start,$context.SelectedRange.End)
    $Context.CurrentFile.GetText($Range)

I would expect the $Context.SelectedRange to work directly with the GetText method which take a FileRange as argument.

That does not end there.
When working with Powershell 7.2, the Microsoft.PowerShell.EditorServices.Extensions.FileRange type does not exist so not only the way you'd expect it to work does not work but also the workaround of creating a new object of the aforementionned type manually and pasting value from the context range do not work either.

The error in a PS 7,2 VSCode session with GetText and $Context.SelectedRange

MethodException: Cannot find an overload for "GetText" and the argument count: "1".

The error in a PS 7.2 VSCode session when trying to create a filerange object manually

InvalidOperation: Unable to find type [Microsoft.PowerShell.EditorServices.Extensions.FileRange].

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions