powershell - 使用 Write-Warning "Some Message"-WarningAction 时如何处理所有情况

标签 powershell

我有一个脚本,我多次调用外部命令。

我首先检查传递给外部命令的输出文件夹,如果该文件夹存在,我想提示用户:

Write-Warning "Do you want to override $somefolder" -WarningAction Inquire

这非常有效,并向用户显示以下内容:

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

请参阅此处的文档: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.1

在上面的 Y 继续中,H 停止,S 执行这种奇怪的暂停操作,用户可以退出到 shell 运行一些命令并输入 exit 来恢复脚本。奇怪但整洁。

我的问题是,如果用户回答“A”(表示“全部是”),他们每次都会继续收到提示。显然这不是用户期望的行为。

我们如何正确处理“A”的情况,以便如果用户选择“A”,我的脚本中就不再提示他们。

以下是演示该问题的代码片段:

for ($i = 0; $i -lt 10; $i++) {
    Write-Warning "Do you want to override $somefolder" -WarningAction Inquire
    "Pretend to do something here"
}

在上面,如果用户在第一个问题后按“A”,则应跳过接下来的 9 个提示。如何最好地处理这个问题?

注意:显然还有其他方法可以在 PowerShell 中提示和捕获用户的输入。我的问题是关于使用 Write-Warning "Some Message"-WarningAction Inquire ,它看起来是为了处理我正在寻找的内容而设计的,但我不知道他们想让我如何使用“A”选项。

最佳答案

好问题。不久前,MVP Kirk Munro 在 PowerShell GitHub 跟踪器上创建了一个关于 inconsistent ActionPreference.Inquire feature 的问题。 。 他的范围比较广,我这里只引用相关部分:

There is no "Yes to All" functionality for these messages from Inquire. "Yes to All" is really "Silently Continue", except for these messages it's not silent at all. For everything except non-terminating errors, the message is displayed first. For non-terminating errors, the message is displayed after the Inquire prompt. So "Yes to All" aka "SilentlyContinue" is just broken.

接下来,Bruce Pay 的评论可以解读为对您问题的回答:

BTW - the context of these prompts is the current command/pipeline, not the script running the pipeline.

因此,对所有操作的查询"is"无法按预期工作。

我认为没有立即发生变化,这个问题只是作为 future 的里程碑添加的。

关于powershell - 使用 Write-Warning "Some Message"-WarningAction 时如何处理所有情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67067687/

相关文章:

windows - Windows PowerShell 和 CMD.exe 中的 PerlIO

无法识别 Powershell 导入的模块命令

powershell - 使用非字符串作为 $env : variable

azure - 运行在 PowerShell 中编码的 Azure Functions 时出现 Connect-AzAccount 错误

azure - Get-AzWebApp : The term 'Get-AzWebApp' is not recognized as the name of a cmdlet, 函数 - Azure Devops

用于检查输入和返回数据类型的 Powershell 函数未返回正确的值

parsing - 使用 Powershell 读取/解析二进制文件

powershell - VS Code 上的 [pwsh] 和 [Powershell 集成控制台] 有什么区别?

Powershell 选择字符串 : Get results by named regex group

powershell - 尝试使用PowerShell获取进程数