2014-12-13 52 views
-1

在命令提示符窗口中,我會引發以下爲迭代循環:超時讀主機在PowerShell中

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

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

有沒有人知道在Powershell中做到這一點的方法?現在,我只是等待它(下面的最後一行)。

我已經設置了我的腳本來爲我的妻子在電視和PC之間切換。我之前和之後爲我的妻子打印,我想繞過自己。



這裏是我的情況對當前的腳本:

$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 
+2

這是否解決您的問題? http://stackoverflow.com/questions/150161/waiting-for-user-input-with-a-timeout或http://thecuriousgeek.org/?p=253 – Matt 2014-12-13 04:46:17

+0

至少從我的測試,這似乎等待在接受輸入前x秒。我想在x秒後讀取輸入OR超時。 – krmarshall87 2014-12-13 14:40:49

+0

首先,只是暫停/睡覺。 '$ key = $ host.ui.rawui.readkey(「NoEcho,IncludeKeyUp」)上的第二個錯誤' – krmarshall87 2014-12-13 14:58:22

回答

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

測試,一件好事,因爲它證明只是淡淡的沒有價值的比我預期的坦白。

+0

至少從我的測試來看,這似乎在接受輸入前等待x秒。我想在x秒後讀取輸入OR超時。 – krmarshall87 2014-12-13 14:54:56

+1

只需雙倍檢查,@ krmarshall87,並在PowerShell 4.0上它似乎有適當的時間響應;設置一個50秒的延遲並立即打字讓我在出現字符前等待1-2秒。 – 2014-12-13 15:21:31

+0

謝謝。我會在幾天內檢查我什麼時候回到辦公室。我可能會使用v3。欣賞它! – krmarshall87 2014-12-14 18:10:38