powershell 使用Read-Host输入多行

vsdwdz23  于 2023-10-18  发布在  Shell
关注(0)|答案(5)|浏览(158)

有没有一种方法可以使用Read-Host小工具来捕获多行?
我现在的方法有点笨拙(而且不太有效):

PS> Send-MailMessage -SmtpServer 'smtp.domain.xxx' -From 'First Last <[email protected]>' -To 'First Last <[email protected]>' -Subject 'Testing' -Body (Read-Host 'Enter text')
Enter text: line one `n line two `n line three

生成的电子邮件正文不是三行:
line onen line two n line three

flvlnr44

flvlnr441#

$x = while (1) { read-host | set r; if (!$r) {break}; $r}

空行结束输入。

nue99wik

nue99wik2#

我知道这是晚了,但我真的很喜欢@majkinetor的答案,但它仍然需要改进,因为输入不会被采取。我这样改进了答案:

while (1) 
  {
    read-host | set r
    set test -value ($test+"`n"+$r)
    if (!$r) {break}
  }
$test = $test.trim()

它做了几乎相同的事情,$r是每行输入,但随后它将其添加到变量$test。这实际上也会保存输入。如果你想允许换行符,我只需要添加

$test = $test.replace("<br>","")

这将使<br>作为一个回车符,但你可以把它改为任何你喜欢的东西,比如:

$test = $test.replace("Whatever you want","")
$test = $test.replace("CRLF","")
$test = $test.replace("Break","")
cbeh67ev

cbeh67ev3#

尝试这样的东西,你只是有(读主机)

(@(While($l=(Read-Host).Trim()){$l}) -join("`n"))

您以一个仅包含空白/空格的行退出循环。
你可以使用$_而不是一个真实的变量,但我觉得这“令人毛骨悚然”,所以我不这样做。

3qpi33ja

3qpi33ja4#

一个轻度优化的函数,用于将多行输入读取到字符串中:

function ReadMultiLineInput() {
    # optimize capturing the first line
    $inputText = Read-Host
    if (!$inputText) { return "" }

    # capture each subsequent line
    while ($r = Read-Host) {
        # exit when an empty line is entered
        if (!$r) { break }

        $inputText += "`n$r"
    }

    return $inputText
}

输出逗号分隔字符串的用法示例:

$multilineInput = ReadMultiLineInput
$csvInput = $multilineInput -replace "`n", ","
s4n0splo

s4n0splo5#

没有办法简单地使用Read-Host,你需要发挥创造力。
我有一个非常复杂的函数可以解决这个问题。它可以在一个特殊的组合键(Ctrl + Q)、3个换行符或大约5秒的不活动时退出。
它基于“Elavarasan Muthuvalavan - Lee”提供的脚本:Waiting for user input with a timeout

function Read-HostTimed {
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $false, ValueFromPipeline = $true)]
        [string]$Prompt  
    )
    Begin {
        $lines = ''
        $count = 0
        $sleepTimer = 5 # in milliseconds
        $loopCount = 300
        $coefficient = 3.33333 # just a hip-shot value to take into account the time taken by the loop to execute.
        $seconds = [math]::Round((($loopCount * $sleepTimer) * $coefficient) / 1000)
        $QuitKey = 81 # Character code for 'q' key.
        $exitKeyCombo = "Ctrl + 'q'"
        $exitOnNReturns = 2 # exits on n + 1 returns
        Write-Host ("Input completes in ${seconds}s or when pressing $exitKeyCombo!")
    }
    Process {
        if ($Prompt) {
            Write-Host "${Prompt}: " -NoNewline
        }
        while ($count -lt $loopCount) {
            if ($host.UI.RawUI.KeyAvailable) {
                $key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
                # For Key Combination: eg., press 'LeftCtrl + q' to quit.
                if (($key.VirtualKeyCode -eq $QuitKey) -and ($key.ControlKeyState -eq "LeftCtrlPressed")) {
                    Write-Host -ForegroundColor Yellow ("Input saved.")
                    break
                }

                if ($key.Character -in @("`r", "`n")) {
                    Write-Host
                    if ($lines.Length -ge $exitOnNReturns -and $lines.Substring($lines.Length - $exitOnNReturns, $exitOnNReturns) -eq "`n"*$exitOnNReturns) {
                        break
                    }
                    $lines += "`n"
                }
                elseif ($key.Character -eq "`b") {
                    Write-Host -NoNewline "`b `b"
                    if ($lines) {
                        $lines = $lines.Substring(0, $lines.Length - 1)
                    }
                }
                else {
                    Write-Host $key.Character -NoNewline
                    $lines += $key.Character
                }
                
                # reset exit counter
                $count = 0
            }
            #Do operation every loop
            $count++
            Write-Verbose ("Key: " + $key.VirtualKeyCode + " | Count: " + $count)
            Start-Sleep -Milliseconds $sleepTimer
        }
    }
    End {
        return $lines.trim()
    }
}

相关问题