【问题标题】:PowerShell Read-Host outputting input to consolePowerShell Read-Host 将输入输出到控制台
【发布时间】:2021-11-04 15:53:39
【问题描述】:

我在 PowerShell 5.1 中编码,在循环中使用 Read-Host 时遇到了一个奇怪的问题。出于某种原因,当我按照下面的代码向 Read-Host 输入内容时,我总是在我的 PowerShell ISE 控制台上输出它。有没有办法刷新输入缓冲区以免发生这种情况?

代码:

function Test-Read{
    for ($num = 1 ; $num -le 3 ; $num++){
     Read-Host -Prompt "Test Prompt"
    }
}

输出:

Test Prompt: a
a
Test Prompt: b
b
Test Prompt: c
c

谢谢, 极光

【问题讨论】:

    标签: powershell


    【解决方案1】:

    在 PowerShell 中,单个语句的所有输出都将“冒泡”到调用者(最终是屏幕缓冲区),除非被抑制或分配。

    将Read-Host的字符串输出赋值给一个变量,或者将调用结果转换为[void]:

    function Test-Read{
        for ($num = 1 ; $num -le 3 ; $num++){
            # $null is a special automatic variable - assigning to it won't affect it, much like piping to NUL in cmd or `/dev/null` on a UNIX/POSIX system
            $null = Read-Host -Prompt "Test Prompt"
        }
    }
    

    或

    function Test-Read{
        for ($num = 1 ; $num -le 3 ; $num++){
            [void](Read-Host -Prompt "Test Prompt")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多