exception - PowerShell : use parameter validation without throwing exception

标签 exception powershell command-line-arguments

我想以这种方式调用 PowerShell 脚本:script.ps1 -path mypath\to\files\ -days 6 -hours 0
要验证命令行参数,我可以手动完成,也可以依靠 param句法 :

Param (
    [Parameter(Mandatory=$true )] [string] $path,
    [Parameter(Mandatory=$false)] [int]    $days,
    [Parameter(Mandatory=$false)] [int]    $hours
)



如果我使用 param句法 :
  • 参数定义必须是脚本中的第一行(不包括注释)。好的,对我来说不是问题
  • 如果参数不正确,我无法捕捉到错误(例如显示自定义错误消息)


  • 当使用错误的参数调用脚本时,我想显示自定义错误消息。
    是否有可能以及如何在参数错误的情况下捕获异常?

    最佳答案

    所以好吧,不能使用 param AND 来捕获相关的异常。

    关于exception - PowerShell : use parameter validation without throwing exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12481662/

    相关文章:

    c# - 为什么这个内联if错了?

    exception - typescript 2 - 在三元/条件运算符表达式中抛出

    c# - 在出现 OnlyOnFaulted 的情况下使用 TPL 时出现未处理的异常

    python - Django 模型中 int() 的文字无效

    git - jekyll 服务器已打开但未重新生成

    powershell - 使用 cmdets 将文件上传到 Azure 上的存储

    powershell - 如何在 Powershell Get-Process 中实现 'Wait' 模式

    python - 从 Windows 命令行运行 Python 脚本,未传递参数

    c# - 在没有管理员权限的情况下使用 'schtasks' 调度任务 C#

    c++ - boost program_options : help vs. 有意义的选项