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.