Note: I'm assuming you're only interested in text selected in the current console window.
There is no perfect solution on Windows that I'm aware of[1], but you can approximate one, which, however, requires the user's cooperation, in the form right-clicking after making a selection.
The solution below works in both regular console windows (conhost.exe
) and Windows Terminal:
In regular console windows, "Quick Edit" mode should be enabled, so as to allow direct selection of text with the mouse.
To make the solution work, the user must copy the selection to the clipboard, which later allows you to retrieve the clipboard's content if no direct input was supplied. This is easily achieve by right-clicking (anywhere inside the window) after making a selection, which the prompt message must instruct the user to do.
Here's an example:
# Since the selection can only be obtained via the clipboard and we don't want preexisting
# clipboard content to interfere with the operation, we clear the clipboard first.
Set-Clipboard ''
# Define the prompt string to use with Read-Host containing instructions.
$prompt = @'
Enter a value and press Enter
- OR -
Select a string in this console window, RIGHT-CLICK and then press Enter
'@
# Prompt for user input until it is non-blank, either by direct input or via the selection.
do {
$userInput = Read-Host $prompt
if (-not $userInput) { # No direct input, try to get the selection from the clipboard.
$userInput = Get-Clipboard
}
} while (-not $userInput.Trim())
Write-Verbose -Verbose @"
You entered or selected:
«$userInput»
"@
[1] While (non-PowerShell-friendly) techniques exist in principle to query a Windows console's selection (involving the - "softly" deprecated - GetConsoleSelectionInfo
WinAPI function), or, more generally the cross-application Windows Accessibility API that allows "spying on" UIs, as shown in this answer), these techniques cannot be used by code that directly, synchronously executes in the console window itself, because typing or submitting a command invariably involves automatic clearing of the selection before returning control to the shell / a running porgram. In regular console windows - but not in Windows Terminal - the first Enter keypress after having made a selection actually copies the selection to the clipboard and then clears the selection and returns control to the shell / running program, so that pressing Enter twice instead of right-clicking and then pressing Enter works too.
Terminals on macOS also clear the selection first.
By contrast, on Linux at least X-Window-based terminals retain the selection in this case (as verified with the Gnome Terminal that ships with Ubuntu 18.04), which, as your question suggests, can be combined with the (installable on demand) xsel
utility to programmatically query the selection.