Skip to content

Instantly share code, notes, and snippets.

@fluttr
Last active February 12, 2018 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fluttr/f0283eb0f133e6aa0264977956657a73 to your computer and use it in GitHub Desktop.
Save fluttr/f0283eb0f133e6aa0264977956657a73 to your computer and use it in GitHub Desktop.
Waits $TimeoutSeconds for user input and then returns input if any.
function waitForUserInput([parameter(mandatory=$true)][int]$TimeoutSeconds, [string]$Prompt){
$counter = 0
while($counter++ -lt $TimeoutSeconds){
if(-not [console]::KeyAvailable){
Start-Sleep -Seconds 1
} else {
$input = Read-Host -Prompt "$Prompt"
break
}
}
if($input){
Write-Output "$input"
}
}
$ReportFileName = 'c:\whatever\some.file'
$UserInputTimeoutSeconds = 3
# ask user for custom report prefix
echo "Press any key in $UserInputTimeoutSeconds seconds to specify custom report name..."
$customPrefix = waitForUserInput -TimeoutSeconds $UserInputTimeoutSeconds -Prompt "Report prefix"
$customPrefix = $customPrefix -replace '[^\w]',''
if($customPrefix){
$reportDir = Split-Path -Parent $ReportFileName
$reportSuffix = Split-Path -Leaf $ReportFileName
$ReportFileName = "$reportDir\${customPrefix}_$reportSuffix"
}
# ...
@fluttr
Copy link
Author

fluttr commented Feb 12, 2018

[console]::KeyAvailable does not working in PowerShell ISE. Try it in real console.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment