Skip to content

Instantly share code, notes, and snippets.

@tahir-hassan
Created February 27, 2022 23:39
Show Gist options
  • Save tahir-hassan/61a0c0a48130fc311798304db61097be to your computer and use it in GitHub Desktop.
Save tahir-hassan/61a0c0a48130fc311798304db61097be to your computer and use it in GitHub Desktop.
`PSConsoleReadLine` has a `GetSelectionState` method but no `SetSelectionState` method. `Set-PSConsoleReadLineSelectionState` will enable you to set the selection state and also specify if the selection was done backwards or forwards (by default it is forwards).
Function Set-PSConsoleReadLineSelectionState
{
param(
[Parameter(Mandatory)][int]$Start,
[Parameter(Mandatory)][int]$Length,
[ValidateSet('Backward', 'Forward')][string]$Direction='Forward'
)
$startCursorPosition,$selectChar = switch ($Direction)
{
'Backward' {
$Start + $Length; [Microsoft.PowerShell.PSConsoleReadLine]::SelectBackwardChar
}
'Forward' {
$Start; [Microsoft.PowerShell.PSConsoleReadLine]::SelectForwardChar
}
};
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($startCursorPosition);
[Microsoft.PowerShell.PSConsoleReadLine]::SetMark($null, $null);
(1..$Length) | ForEach-Object {
$selectChar.Invoke($null, $null);
}
}
<#
To select the first five characters do:
Set-PSConsoleReadLineSelectionState 0 5 Forward
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment