Powershell中的Read-Host超时

时间:2014-12-13 03:21:47

标签: powershell sleep

在命令提示符中,我将以下内容抛入迭代循环:

choice /c:abcdefghijklmnopqrstuvwxyz1234567890 /n /t:1 /d:0 
sleep 1

在Unix中,我使用:read -t 5 $input

有谁知道在Powershell中做到这一点的方法?现在,我只是等一下(下面的最后一行)。

我设置了我的脚本,为我的妻子在电视和电脑之间切换。我为我的妻子打印了一个前后,我想为自己绕过它。



这是我目前的上下文脚本:

 $file_location = "C:\Users\krmar_000\Documents\audio.out"
 $current = gc $file_location
 Write-Host "Current Audio output: " -ForegroundColor White -NoNewline
 Write-Host $current -ForegroundColor Red

 Write-Host "Changing..." -ForegroundColor Yellow

 if ( $current -eq "Speakers” )
 {
     nircmd.exe mutesysvolume 0
     nircmd.exe setsysvolume 65535

     nircmd.exe setdefaultsounddevice “AMD HDMI Output”
     "AMD HDMI Output" | Out-File -filepath $file_location
 #    [System.Windows.Forms.MessageBox]::Show("TV Speakers enabled","Speaker Flip")

     Write-Host "TV Speakers enabled" -ForegroundColor Green
 }
 elseif ( $current -eq "AMD HDMI Output” )
 {
     nircmd.exe mutesysvolume 0
     nircmd.exe setsysvolume 52428

     nircmd.exe setdefaultsounddevice “Headset”
     "Speakers" | Out-File -filepath $file_location
 #    [System.Windows.Forms.MessageBox]::Show("Headset Speakers enabled","Speaker Flip")

     Write-Host "Headset Speakers enabled" -ForegroundColor Green
 }
 else
 {
     nircmd.exe setdefaultsounddevice “Speakers”
     "Speakers" | Out-File -filepath $file_location
 #    [System.Windows.Forms.MessageBox]::Show("Headset Speakers enabled","Speaker Flip")    

     Write-Host "Headset Speakers enabled" -ForegroundColor Green 
 }
 Start-Sleep -Seconds 5

1 个答案:

答案 0 :(得分:0)

这并不是链接答案的愚蠢,但它非常接近。为方便起见,这里的全部功能(基于相同):

function Read-HostWithDelay {
  param([Parameter(Mandatory=$true)][int]$Delay, [string]$Prompt, [Switch]$AsSecureString)
  [int]$CSecDelayed = 0
  do {
    [bool]$BReady = $host.UI.RawUI.KeyAvailable
    [Threading.Thread]::Sleep(1000)
  } while (!$BReady -and ($CSecDelayed++ -lt $Delay))
  if ($BReady -and $Prompt) { Read-Host $Prompt -AsSecureString:$AsSecureString }
  # No, Read-Host will not in fact handle null parameter binding (-Prompt:$Prompt) properly. Who knows why not.
  elseif ($BReady) { Read-Host -AsSecureString:$AsSecureString }      
}

经过测试,也是一件好事,因为事实证明这只是一种比我坦率的预期更为微不足道的事情。