为何PowerShell提示符要求用户重复输入两次响应?
问题原因
- 误用PowerShell内置自动变量
$input:$input是PowerShell专门用于接收管道输入的变量,用来存储用户输入会触发异常逻辑,导致重复输入。 Write-Error输出干扰:Write-Error将错误信息输出到stderr,与Write-Output的stdout输出混淆,引发额外提示行为。
修正后的代码
:GET_SUFFIX REM Prompt the user for the suffix using PowerShell for /f "delims=" %%a in ('powershell -Command "& { $valid = $false; while (-not $valid) { $userInput = Read-Host 'Enter the Suffix (6 to 10 numbers)' ; if ($userInput -match '^\d{6,10}$') {$valid = $true; Write-Output $userInput } else { Write-Host 'Invalid input, please try again.' -ForegroundColor Red } } }"') do set "var5=%%a" REM code continues here if the suffix is valid echo Suffix is valid: %var5%
修改说明
- 重命名变量:将
$input改为$userInput,避开PowerShell内置变量,彻底解决重复输入问题。 - 简化验证逻辑:正则
^\d{6,10}$已确保输入是6-10位纯数字,移除多余的-and $input -notmatch '[^\d]'条件。 - 替换错误输出方式:用
Write-Host替代Write-Error,错误信息直接打印到控制台,不会干扰Write-Output的有效输出,消除提示冒号后多余空格的问题。
内容的提问来源于stack exchange,提问作者Owlyn
相关产品推荐
相关产品推荐

