Вместо использования Read-Host
вы также можете использовать графический всплывающий метод Wscript.Shell
, чтобы показать окно сообщений, которое автоматически отключается через определенное количество секунд:
function Show-Popup {
Param (
[Parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullorEmpty()]
[string]$Message,
[string]$Title = 'Please choose..',
[ValidateSet('OK','OKCancel','AbortRetryIgnore','YesNoCancel','YesNo','RetryCancel')]
[string]$Buttons='OK',
[ValidateSet('Error','Question','Warning','Information' )]
[string]$Icon='Information',
[ValidateSet('First','Second','Third' )]
[string]$DefaultButton = 'First', # as seen from left to right
[int]$SecondsToWait = $null
)
# get the numeric value for the $Buttons (0..5)
[uint32]$typeFlags = [array]::IndexOf(@('OK','OKCancel','AbortRetryIgnore','YesNoCancel','YesNo','RetryCancel'), $Buttons)
# add the numeric value for the $Icon (16, 32, 48, 64)
$typeFlags += 16 * ([array]::IndexOf(@('Error','Question','Warning','Information'), $Icon) + 1)
# add the value for the default button
$typeFlags += 256 * ([array]::IndexOf(@('First','Second','Third','Fourth'), $DefaultButton))
try {
$objShell = New-Object -ComObject Wscript.Shell -ErrorAction Stop
# show the popup and convert the returned int value to string
switch ($objShell.Popup($Message, $SecondsToWait, $Title, $typeFlags)) {
1 { return 'OK ' }
2 { return 'Cancel ' }
3 { return 'Abort ' }
4 { return 'Retry ' }
5 { return 'Ignore ' }
6 { return 'Yes ' }
7 { return 'No' }
default { return 'TimeOut' } # -1
}
}
catch {
Write-Warning "Could not create Wscript.Shell object. `r`n$($_.Exception.Message)"
}
finally {
if ($objShell) {
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objShell) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
$objShell = $null
}
}
}
С этой функцией вызовите ее как:
$answer = Show-Popup -Message 'Do you want to uninstall SoundRecoder app?' -Buttons YesNo -Icon Question -DefaultButton Second -SecondsToWait 10
if ($answer -eq 'TimeOut') {
Write-Host "You did not respond.."
}
else {
Write-Host "You answered $answer"
}
Это будет отображаться так:
Примечание: я запускаю это на голландском компьютере, поэтому «Да» и «Нет» переводятся как «Ja» и «Ни»