Use Read-Host to enter multiple lines

时间:2016-04-15 15:17:25

标签: powershell

Is there a way to use the Read-Host cmdlet to capture multiple lines?

My current approach is a bit awkward (and doesn't really work):

PS> Send-MailMessage -SmtpServer 'smtp.domain.xxx' -From 'First Last <flast@domain.xxx>' -To 'First Last <first.last@company.com>' -Subject 'Testing' -Body (Read-Host 'Enter text')
Enter text: line one `n line two `n line three

Resulting email body isn't three lines:

line one `n line two `n line three

3 个答案:

答案 0 :(得分:1)

尝试这样的地方(Read-Host)

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

使用仅空白/空白行退出循环。

你可以使用$_而不是真正的变量,但我发现&#34;令人毛骨悚然的&#34;所以我不这样做。

答案 1 :(得分:0)

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

空行完成输入。

答案 2 :(得分:0)

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

import math
def round_nearest(num, a):
    return round(round(num / a) * a, -int(math.floor(math.log10(a))))
round_nearest(1.145, 0.05)
>>> round_nearest(1.145, 0.05)
1.15

它几乎做同样的事情,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>