powershell - How can I implement Get-Credential with a timeout -
in of scripts have fall-back approach getting pscredential object via get-credential
cmdlet. useful when running scripts interactively, esp. during testing etc.
if & when run these scripts via task scheduler, i'd ensure don't stuck waiting interactive input , fail if don't have necessary credentials. note should never happen if task set run under correct application account.
does know of approach allow me prompt input with timeout (and presumably null credential object) script doesn't stuck?
happy consider more general case read-host
instead of get-credential
.
i use similar in of scripts based around timeout on read-host, code here :
function read-hosttimeout { # description: mimics built-in "read-host" cmdlet adds expiration timer # receiving input. not support -assecurestring # set parameters. keeping prompt mandatory # original param( [parameter(mandatory=$true,position=1)] [string]$prompt, [parameter(mandatory=$false,position=2)] [int]$delayinseconds=5, [parameter(mandatory=$false,position=3)] [string]$defaultvalue = 'n' ) # math convert delay given milliseconds # , divide sleep value correct delay # timer value can set $sleep = 250 $delay = ($delayinseconds*1000)/$sleep $count = 0 $chararray = new-object system.collections.arraylist write-host -nonewline "$($prompt): " # while loop waits first key pressed input , # exits. if timer expires returns null while ( (!$host.ui.rawui.keyavailable) -and ($count -lt $delay) ){ start-sleep -m $sleep $count++ if ($count -eq $delay) { "`n"; return $defaultvalue} } # retrieve key pressed, add char array storing # keys pressed , write same line prompt $key = $host.ui.rawui.readkey("noecho,includekeyup").character $chararray.add($key) | out-null # comment out if want "no echo" of user types write-host -nonewline $key # block script keeps reading key. every time # key pressed, checks if it's carriage return. if so, exits # loop , returns string. if not stores key pressed , # checks if it's backspace , necessary cursor # moving , blanking out of backspaced character, resumes # writing. $key = $host.ui.rawui.readkey("noecho,includekeyup") while ($key.virtualkeycode -ne 13) { if ($key.virtualkeycode -eq 8) { $chararray.add($key.character) | out-null write-host -nonewline $key.character $cursor = $host.ui.rawui.get_cursorposition() write-host -nonewline " " $host.ui.rawui.set_cursorposition($cursor) $key = $host.ui.rawui.readkey("noecho,includekeyup") } else { $chararray.add($key.character) | out-null write-host -nonewline $key.character $key = $host.ui.rawui.readkey("noecho,includekeyup") } } write-host "" $finalstring = -join $chararray return $finalstring }
Comments
Post a Comment