要求用户填充字段 (Powershell)

Requiring users to populate field (Powershell)

我在 powershell 中有一个片段,它从平面文件中读取问题并提示用户提供布尔值或字符串响应(即你喜欢飞行汽车吗?你为什么喜欢跳伞?)。所有答案都写入 .xls 以供稍后使用到数据库。

我可以让脚本为没有 select 布尔答案(即 A、B、C 或 "Yes"、"No")的用户重复问题。然而让用户提供一个字符串(简短)答案)有点棘手。

$Question7 = Get-Content -path $PSScriptRoot\src\Question7.txt -raw

Write-Host $Question7 -ForegroundColor Yellow
$reason_for_hobby = Read-Host -Prompt "Please write in the answer"
Writ-Host "Answer: $reason_for_hobby" -ForegroundColor Green

Add-Member -inputObject $infoObject -memberType NoteProperty -name "HBYREASON" - 
value $reason_for_hobby

我想弄清楚如何强制用户提供至少 215 个字符的回复,如果没有提供则重复问题。

谢谢,注意安全。

您可以通过简单的 while 循环实现此目的(而 $reason_for_hobby 的重复字符少于 215 个):

while ($reason_for_hobby.Length -lt 215){
    $reason_for_hobby = Read-Host -Prompt "Please write in the answer"
}

但是,如果变量 $reason_for_hobby 之前未初始化,则 do-while 循环会更好(执行一次并在 $reason_for_hobby 少于 215 个字符时重复):

do{
    $reason_for_hobby = Read-Host -Prompt "Please write in the answer"
}while ($reason_for_hobby.Length -lt 215)