PowerShell中的读取主机超时 [英] Timeout of Read-Host in Powershell

查看:15
本文介绍了PowerShell中的读取主机超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

choice /c:abcdefghijklmnopqrstuvwxyz1234567890 /n /t:1 /d:0 
sleep 1
在Unix中,我会使用:read -t 5 $input

有人知道在PowerShell中做这件事的方法吗?现在,我只是在等待(下面的最后一行)。

我已将我的脚本设置为在电视和PC之间为我的妻子切换。我为我的妻子打印了一张事前和事后的记录,我想自己绕过它。



以下是我当前的上下文脚本:

 $file_location = "C:Userskrmar_000Documentsaudio.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

推荐答案

这不完全是链接答案的复制,但非常接近。为了方便起见,这里有完整的功能(大致基于相同的功能):

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 }      
}

进行了测试,这也是一件好事,因为事实证明它只是比我坦率地预期的稍微小了一点。

这篇关于PowerShell中的读取主机超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆