如何解决提升 powershell 脚本以管理员身份运行时,为什么 read-host 在提示用户之前接受键盘输入?
我正在运行一个 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"
如果您在脚本的第一部分运行时在键盘上输入任何内容,之前 read-host 语句被执行,键盘输入被“保存”,并出现在 read -host 当 read-host "input text here" 文本出现在屏幕上时提示。
当我摆脱以管理员身份运行时,read-host 仅在脚本到达该代码行时才接受输入。
有谁知道如何防止 read-host 在提示用户之前记录键盘输入?
我假设您可以通过修改 run-as-admin 代码或添加一些代码来解决此问题,以在脚本的前半部分暂时禁用键盘输入,然后在 read-host 语句之前重新启用输入。>
解决方法
我不认为这个问题与您是否运行高架有关。
假设您在 控制台(终端)中运行,您可以按如下方式清除键盘缓冲区(改编自 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'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。