我正在尝试制定这个菜单(示例)。我尝试了多种选择,但由于某种原因,没有一个计时器耗尽。
function Show-SimpleMenu {
Clear-Host
Write-Host "Simple Menu Options:"
Write-Host "1. Option 1"
Write-Host "2. Option 2"
Write-Host "3. Option 3"
Write-Host "Q. Quit"
$timeout = 10
$timer = [System.Diagnostics.Stopwatch]::StartNew()
while ($true) {
$elapsedSeconds = [math]::Floor($timer.Elapsed.TotalSeconds)
$remainingSeconds = $timeout - $elapsedSeconds
if ($remainingSeconds -le 0) {
Write-Host "Timeout: Automatically selecting Option 1."
Option1
break
}
Write-Host "Time Remaining: $remainingSeconds seconds"
$selection = Read-Host "Enter your selection"
switch ($selection) {
'1' {
Option1
break
}
'2' {
Option2
break
}
'3' {
Option3
break
}
'Q' {
Write-Host "Exiting..."
return
}
default {
Write-Host "Invalid selection."
}
}
}
}
function Option1 {
Write-Host "Option 1 selected"
}
function Option2 {
Write-Host "Option 2 selected"
}
function Option3 {
Write-Host "Option 3 selected"
}
# Call the menu function
Show-SimpleMenu
但即使使用 Write-Progress 和 Start-Sleep 也不起作用。 单独运行计时器就可以了。
我现在才使用 powershell 几个月。
我想创建一个菜单供用户选择。 如果他们不选择某个选项,则在 x 秒后选择选项 1。
我觉得我有某种使命。尝试从 Powershell ISE 和 Windows Powershell 5 运行
如果您在作业中运行计时器,然后让它向活动窗口发送击键,那么应该可以工作。
function Show-Menu {
Write-OutPut @'
Press 1
Press 2
'@
$TimeOut = Start-Job {
$Null = [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
sleep -Seconds 10
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
}
$choice = Read-Host 'Enter your selection'
Remove-Job $TimeOut -Force
if (!$choice) {
Write-Output 'Selection timed out'
return
}
$choice
}
Show-Menu
请参阅 MS Learn - System.Windows.Forms - SendKeys 类 和 SpiceWorks - 与窗口交互的脚本,了解有关
SendWait
的更多详细信息。