就像我说的,这段代码适用于PowerShell版本2,但不适用于PowerShell版本5。
function wait
{
$compte = 0
Write-Host "To continue installation and ignore configuration warnings type [y], type any key to abort"
While(-not $Host.UI.RawUI.KeyAvailable -and ($compte -le 20))
{
$compte++
Start-Sleep -s 1
}
if ($compte -ge 20)
{
Write-Host "Installation aborted..."
break
}
else
{
$key = $host.ui.rawui.readkey("NoEcho,IncludeKeyup")
}
if ($key.character -eq "y")
{Write-Host "Ignoring configuration warnings..."}
else
{Write-Host "Installation aborted..."
}}
答案 0 :(得分:2)
Seth,谢谢您的解决方案。我扩展了您提供的示例,并希望将其反馈给社区。 p>
这里的用例有些不同-我有一个循环,检查是否可以迁移VM阵列,以及该检查是否有任何故障,操作员可以对其进行补救直到检查清除,或者他们可以选择“ GO”,并将那些失败的VM排除在操作之外。如果输入了GO以外的内容,则状态将保留在循环中。
这样做的一个缺点是,如果操作员无意中按下了某个键,则脚本将被Read-Host阻止,并且可能不会立即被注意到。如果这对任何人来说都是一个问题,我相信他们可以解决;-)
Write-Host "Verifying all VMs have RelocateVM_Task enabled..."
Do {
$vms_pivoting = $ph_vms | Where-Object{'RelocateVM_Task' -in $_.ExtensionData.DisabledMethod}
if ($vms_pivoting){
Write-Host -ForegroundColor:Red ("Some VMs in phase have method RelocateVM_Task disabled.")
$vms_pivoting | Select-Object Name, PowerState | Format-Table -AutoSize
Write-Host -ForegroundColor:Yellow "Waiting until this is resolved -or- type GO to continue without these VMs:" -NoNewline
$secs = 0
While ((-not $Host.UI.RawUI.KeyAvailable) -and ($secs -lt 15)){
Start-Sleep -Seconds 1
$secs++
}
if ($Host.UI.RawUI.KeyAvailable){
$input = Read-Host
Write-Host ""
if ($input -eq 'GO'){
Write-Host -ForegroundColor:Yellow "NOTICE: User prompted to continue migration without the blocked VM(s)"
Write-Host -ForegroundColor:Yellow "Removing the following VMs from the migration list"
$ph_vms = $ph_vms | ?{$_ -notin $vms_pivoting} | Sort-Object -Property Name
}
}
} else {
Write-Host -ForegroundColor:Green "Verified all VMs have RelocateVM_Task method enabled."
}
} Until(($vms_pivoting).Count -eq 0)
答案 1 :(得分:1)
official文档或Read-Host -?
会说明无法以这种方式使用Read-Host
。没有可能的参数告诉它以某种超时运行。
但是various其他questions详细说明了如何在PowerShell中执行此操作(通常使用C#)。
这个想法似乎是在用户使用$Host.UI.RawUI.KeyAvailable
按键时检查,并在超时期间检查。
一个简单的工作示例如下:
$secondsRunning = 0;
Write-Output "Press any key to abort the following wait time."
while( (-not $Host.UI.RawUI.KeyAvailable) -and ($secondsRunning -lt 5) ){
Write-Host ("Waiting for: " + (5-$secondsRunning))
Start-Sleep -Seconds 1
$secondsRunning++
}
您可以使用$host.UI.RawUI.ReadKey
获取已按下的键。如果您需要比简单的按钮更复杂的输入,这个解决方案可能是不可接受的。另见: