以管理员身份将 powershell 脚本提升到 运行 时,为什么 read-host 在提示用户之前接受键盘输入?

When elevating a powershell script to run as an admin, why does read-host accept keyboard input before the user is prompted?

我正在 运行创建一个 PS 5.1 脚本,它会自动提升到 运行 并具有管理员权限。脚本的第一部分 运行 进行了 3 分钟的检查,以确保环境设置正确。脚本的第二部分通过读取主机请求用户输入。

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

如果您在脚本的第一部分 运行ning 时在键盘上键入任何内容, 读取主机语句执行之前,键盘输入是'saved',当读取主机“在此处输入文本”文本出现在屏幕上时,它出现在读取主机提示中。

当我去掉 运行 as admin 代码时,读取主机仅在脚本到达该行代码时才接受输入。

有谁知道如何防止读取主机在提示用户之前记录键盘输入?

我假设您可以通过修改 运行-as-admin 代码或添加一些代码在脚本的前半部分暂时禁用键盘输入来解决此问题,然后在读取之前重新启用输入-主机声明。

我认为这个问题与您是否运行升高无关。

假设您 运行 在 控制台 (终端)中,您可以按如下方式清除键盘缓冲区(改编自 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'