我正在尝试找到一种方法,让类似于Read-Host的东西来询问用户是否要输出到列出的文件中。这样,我希望他们按y或n,然后代码继续,而不是先按y/n,再按enter。目前,这一切都运行良好,但这并不完全是我想要的。
我尝试过查看Readkey和SendKeys (为用户按回车键),但都不起作用,因为它们似乎只有在用户在Read-Host上按回车键后才能执行。我对Powershell还很陌生,所以我不能完全确定这是否真的可行,我花了太多的时间搜索/测试,以找到一个有效的答案。如果我要使用Write-Host或其他工具来执行此操作,它需要不显示在日志中。
我已经在下面的脚本中包含了必要的部分。它主要是询问用户文件位置是否正确。如果是,则按y并将其用于输出,否则,如果按下n,则加载FolderBrowserDialog以供他们选择所需的文件夹。
我还应该注意到,这都是在Tee-object中完成的,因为这段代码决定了Tee-object输出的位置。
$OutputYN = Read-Host "Do you want the output file generated to $startDirectory\FolderList.txt? (Y/N)"
If (“y”,”n” -notcontains $OutputYN) {
Do {
$OutputYN = Read-Host "Please input either a 'Y' for yes or a 'N' for no"
} While (“y”,”n” -notcontains $OutputYN)
}
if ($OutputYN -eq "Y") {
$OutputLoc = $startDirectory
}
elseif ($OutputYN -eq "N") {
$OutputLocDir = New-Object System.Windows.Forms.FolderBrowserDialog
$OutputLocDir.Description = "Select a folder for the output"
$OutputLocDir.SelectedPath = "$StartDirectory"
if ($OutputLocDir.ShowDialog() -eq "OK") {
$OutputLoc = $OutputLocDir.SelectedPath
$OutputLoc = $OutputLoc.TrimEnd('\')
}
} 编辑:
我应该说得更清楚一点。我也尝试过消息框类型的东西,但我真的更喜欢用户输入y或n的方式,我对用户必须点击的弹出框不太感兴趣。如果这是不可能的,那就随它去吧。
发布于 2020-12-26 17:11:10
Readkey是正确的方式。
使用以下内容作为模板。
:prompt while ($true) {
switch ([console]::ReadKey($true).Key) {
{ $_ -eq [System.ConsoleKey]::Y } { break prompt }
{ $_ -eq [System.ConsoleKey]::N } { return }
default { Write-Error "Only 'Y' or 'N' allowed!" }
}
}
write-host 'do it' -ForegroundColor Green:prompt为外部循环(while)提供了一个名称,可以在switch语句中使用该名称,以便完全通过break prompt直接中断(而不是在switch语句中)。
另一种选择(适用于Windows):使用MessageBox。
Add-Type -AssemblyName PresentationFramework
$messageBoxResult = [System.Windows.MessageBox]::Show("Do you want the output file generated to $startDirectory\FolderList.txt?" , 'Question' , [System.Windows.MessageBoxButton]::YesNo , [System.Windows.MessageBoxImage]::Question)
switch ($messageBoxResult) {
{ $_ -eq [System.Windows.MessageBoxResult]::Yes } {
'do this'
break
}
{ $_ -eq [System.Windows.MessageBoxResult]::No } {
'do that'
break
}
default {
# stop
return # or EXIT
}
}发布于 2020-12-26 16:10:55
不确定是否可以在控制台中执行此操作。但是,当我需要用户写出一个特定集合的答案时,我会使用do-until循环,如下所示:
Do {
$a = Read-Host "Y / N"
} until ( 'y', 'n' - contains $a ) 发布于 2020-12-26 18:26:39
试试这个:
$title = 'Question'
$question = 'Do you want the output file generated to $startDirectory\FolderList.txt?'
$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'Yes'
} else {
Write-Host 'No'
}https://stackoverflow.com/questions/65454348
复制相似问题