Sty*_*ris 1 windows terminal powershell windows-console
这本质上就是我想做的:
Write-Host "Enter username: " -NoNewLine
$username = Read-Host -NoNewLine
if ($username -eq "") {
Write-Host "None"
}
Run Code Online (Sandbox Code Playgroud)
如果用户什么都不输入,那么这将是我想要的输出:Enter username: None
然而,我一直无法找到一种方法来读取用户输入而不生成新行,并且-NoNewLine
不能与 Read-Host 一起使用。
您应该能够通过首先使用PSHostRawUserInterface.CursorPosition属性记录终端光标的位置来完成此操作,该属性可以在$host.UI.RawUI.CursorPosition
提示输入用户名并确定为空后,将光标重置回原来的位置,然后输出所需的文本。
示例代码:
# Output the prompt without the new line
Write-Host "`rEnter username: " -NoNewLine
# Record the current position of the cursor
$originalPosition = $host.UI.RawUI.CursorPosition
# Prompt for the username
$username = Read-Host
# Check the response with the IsNullOrWhiteSpace function to also account for empty strings
if ([string]::IsNullOrWhiteSpace($username)) {
# Set the position of the cursor back to where it was before prompting the user for a response
[Console]::SetCursorPosition($originalPosition.X,$originalPosition.Y)
# Output the desired text
Write-Host "None"
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
363 次 |
最近记录: |