PowerShellEditorServices icon indicating copy to clipboard operation
PowerShellEditorServices copied to clipboard

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

Open itfranck opened this issue 4 years ago • 1 comments

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].

itfranck avatar Jun 06 '21 16:06 itfranck

This is interesting but a bit obscure to get fixed for the time being. I've marked it as up-for-grabs in case someone else wants to take a look.

andyleejordan avatar Jun 14 '21 21:06 andyleejordan