如果我理解正确,您正在寻找在 PowerShell 7.1 中在Read-Host 中实现的两个未功能:
注意:Read-Host 目前是准系统。为 PowerShell 本身提供丰富的交互式命令行编辑体验的模块是 PSReadLine,如果它的功能(包括持久历史记录和修改编辑缓冲区)可以提供给 的用户代码使用,那就太好了通用提示 - 请参阅 GitHub proposal #881。
通过Read-Host 显示这些增强功能可能是最好的选择,或者至少可以在那里实现预填充编辑缓冲区的功能:请参阅GitHub proposal #14013。
请参阅下面的 (a) 和 (b) 的有限自定义实现。
(a) 目前只能通过 workaround,并且只能在 Windows 上,在 常规控制台窗口 和 Windows终端(它在obsolescentPowerShell ISE 中不工作(足够可靠)谢谢CFou.,在 Visual Studio Code 的集成终端中它仅当您在启动调试会话后立即单击将焦点放在它上面时才有效):
# The (default) value to pre-fill the Read-Host buffer with.
$myVar = 'This is a default value.'
# Workaround: Send the edit-buffer contents as *keystrokes*
# !! This is not 100% reliable as characters may get dropped, so we send
# !! multiple no-op keys first (ESC), which usually works.
(New-Object -ComObject WScript.Shell).SendKeys(
'{ESC}' * 10 + ($myVar -replace '[+%^(){}]', '{$&}')
)
$myVar = Read-Host 'Enter a value' # Should display prompt with value of $myVar
注意:-replace 操作对于转义默认值中的字符是必要的,否则对.SendKeys() 具有特殊意义。
(b) 要求你实现自己的持久化机制,显而易见的选择是使用文件:
这是一个简单的方法,只存储最近输入的值。
- 每个提示支持多个历史值也将支持
Read-Host 中的recall,例如使用向上箭头和向下箭头循环浏览历史,这是不 从 PowerShell 7.1 开始支持。
# Choose a location for the history file.
$historyFile = "$HOME/.rhhistory"
# Read the history file (which uses JSON), if it exists yet.
$history = Get-Content -Raw -ErrorAction Ignore $historyFile | ConvertFrom-Json
$defaultValue = 'This is a default value.'
# Get the 'myVar' entry, if it exists, otherwise create it and use the default value.
$myVar =
if (-not $history) { # no file yet; create the object to serialize to JSON later
$history = [pscustomobject] @{ myVar = '' }
$defaultValue
} elseif (-not $history.myVar) { # file exists, but has no 'myVar' entry; add it.
$history | Add-Member -Force myVar ''
$defaultValue
} else { # return the most recently entered value.
$history.myVar
}
# Prompt the user.
(New-Object -ComObject WScript.Shell).SendKeys(
'{ESC}' * 10 + ($myVar -replace '[+%^(){}]', '{$&}')
)
$myVar = Read-Host 'Enter a value'
# Validate the value...
# Update the history file with the value just entered.
$history.myVar = $myVar
$history | ConvertTo-Json > $historyFile