[英]When elevating a powershell script to run as an admin, why does read-host accept keyboard input before the user is prompted?
I'm running a PS 5.1 script that automatically elevates to run with admin privileges.我正在运行一个 PS 5.1 脚本,该脚本会自动提升为以管理员权限运行。 The first part of the script runs a 3-minute check to make sure the environment is set up properly.
脚本的第一部分运行 3 分钟检查以确保环境设置正确。 The second part of the script asks for user input via read-host.
脚本的第二部分通过读取主机请求用户输入。
# Elevate script to run as admin
param([switch]$Elevated)
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false) {
if ($elevated) {
# tried to run as admin, did not work, aborting
} else {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-nologo -noprofile -ExecutionPolicy Bypass -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}
# Example enviornment check that takes a minute to run
if (-Not (Get-PackageProvider -ListAvailable -Name "NuGet" -ErrorAction SilentlyContinue)) {
write-host "blah"
}
Read-Host "input text here"
If you type anything on your keyboard while the first part of the script is running, before the read-host statement is executed, the keyboard input is 'saved', and it appears in the read-host prompt when the read-host "input text here" text appears on the screen.如果您在脚本的第一部分运行时在键盘上键入任何内容,则在执行 read-host 语句之前,键盘输入将被“保存”,并且当 read-host “输入”时它会出现在 read-host 提示符中text here”文本出现在屏幕上。
When I get rid of the run as admin code, read-host only accepts input when the script reaches that line of code.当我摆脱以管理员身份运行时,read-host 仅在脚本到达该代码行时才接受输入。
Does anyone know how to prevent read-host from recording keyboard input before prompting the user?有谁知道如何防止读取主机在提示用户之前记录键盘输入?
I assume you can fix this by modifying the run-as-admin code or adding some code to temporarily disable keyboard input during the first half of the script, then re-enabling input right before the read-host statement.我假设您可以通过修改 run-as-admin 代码或添加一些代码以在脚本的前半部分临时禁用键盘输入,然后在 read-host 语句之前重新启用输入来解决此问题。
I don't think the issue is connected to whether you're running elevated or not.我不认为这个问题与您是否正在运行提升有关。
Assuming you're running in a console (terminal), you can clear the keyboard buffer as follows (adapted from this C# answer ):假设您在控制台(终端)中运行,您可以按如下方式清除键盘缓冲区(改编自此 C# 答案):
# Simulate a long-running command.
# Start typing while the script is sleeping.
Start-Sleep 2
# Clear any accumulated keystrokes.
# Without this, these keystrokes would fill the edit buffer
# of the Read-Host command below.
while ([Console]::KeyAvailable) { $null = [Console]::ReadKey($true) }
Read-Host 'Enter text'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.