powershell - 是否有写入提示缓冲区的命令/程序/Cmdlet?

标签 powershell

我正在尝试查看是否可以将命令的输出写入提示缓冲区以允许进一步编辑?像这样的东西,Write-PromptBuffer是所需的命令:

PS C:\> echo "foo bar" | Write-PromptBuffer
PS C:\> foo bar

相当于 zsh 对 print -z 所做的事情(见 http://zsh.sourceforge.net/Guide/zshguide03.html)

我这样做的主要动机是:
PS C:\> Get-Content (Get-PSReadLineOption).HistorySavePath | fzf

这会将选定的(在 fzf 术语中接受)条目“转储”为提示符中的可编辑命令。

(注意:我熟悉 PSFzf ,但我正在尝试找到一个通用命令来执行此操作,因为我还有其他可以从中受益的用例)

最佳答案

PSReadLine 模块可以插入缓冲区,例如

[Microsoft.PowerShell.PSConsoleReadLine]::Insert("foo bar")

但是,因为这是为了编辑当前行缓冲区而不是下一行,所以你需要这样做
#pipeline to variable $myBuffer function
function Write-PromptBuffer {
    param (  
        [parameter(ValueFromPipeline, ValueFromRemainingArguments = $true)]
        $global:myBuffer
        )
}
#Add a PSReadLineKeyHandler to insert $myBuffer
Set-PSReadLineKeyHandler -Key Alt+x `
    -ScriptBlock {
    param($key, $arg)   # The arguments are ignored in this example
    #write to buffer
    [Microsoft.PowerShell.PSConsoleReadLine]::Insert($myBuffer)
}

现在用一个字符串填充 $myBuffer 并用 Alt+w 调用它
PS C:\> echo "foo bar" | Write-PromptBuffer
PS C:\> foo bar

或者不漂亮,你可以使用 SendKeys
function Write-PromptBuffer {
    param (  
        [parameter(ValueFromPipeline, ValueFromRemainingArguments = $true)]
        $myBuffer
        )
    (new-object -com wscript.shell).SendKeys($myBuffer)
}

希望这可以帮助,

关于powershell - 是否有写入提示缓冲区的命令/程序/Cmdlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59688574/

相关文章:

c# - 为什么某些属性和方法在 Powershell 中可用,但在 C# 中不可用

.net - Powershell - 处理 Windows 窗体事件

arrays - 在 PowerShell 中将数组追加到数组数组

powershell - 如果以开头的文本文件中删除行

powershell - 如何在 PowerShell 中向 Azure CLI 提供 SAS token

javascript - 等效于 Powershell 中的 Javascript encodeURI?

powershell - ImageMagick @filename 引用多个输出

azure - 通过 Powershell Runbook 从 ARM 模板部署 Azure VM,无需下载模板

api - Powershell Invoke-RestMethod

Azure 自动化 - 如何公共(public) webhook 来运行脚本?