简体   繁体   中英

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. The first part of the script runs a 3-minute check to make sure the environment is set up properly. 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.

When I get rid of the run as admin code, read-host only accepts input when the script reaches that line of code.

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.

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 ):

# 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM