【问题标题】:Powershell String Length ValidationPowershell 字符串长度验证
【发布时间】:2018-03-07 08:45:14
【问题描述】:

我创建了一个非常简单的HelloWorld.ps1 Power-shell 脚本,它接受Name 参数,验证其长度,然后打印一条问候消息,例如,如果您将John 传递为Name,它应该打印Hello John!.

这是 Power-shell 脚本:

param (
    [parameter(Mandatory=$true)]
    [string]
    $Name
)
# Length Validation
if ($Name.Length > 10) {
    Write-Host "Parameter should have at most 10 characters."
    Break
}
Write-Host "Hello $Name!"

这是执行它的命令:

.\HelloWorld.ps1 -Name "John"

奇怪的行为是每次我执行它时:

  • 它不执行验证,因此它接受长度超过 10 个字符的Name 参数。
  • 每次我执行它时,它都会创建并更新一个名为 10 的文件,没有任何扩展名。

我的脚本有什么问题,如何在 PowerShell 中验证字符串长度?

【问题讨论】:

    标签: powershell cmdlets cmdlet


    【解决方案1】:

    问题 - 使用错误的运算符

    使用错误的运算符是 PowerShell 中的常见错误。实际上>output redirection operator,它将左操作数的输出发送到右操作数中的指定文件。

    例如$Name.Length > 10 将在名为10 的文件中输出Name 的长度。

    如何验证字符串长度?

    您可以这样使用-gt,即greater than operator

    if($Name.Length -gt 10)
    

    使用ValidateLength 属性进行字符串长度验证

    你可以这样使用[ValidateLength(int minLength, int maxlength)]属性:

    param (
        [ValidateLength(1,10)]
        [parameter(Mandatory=$true)]
        [string]
        $Name
    )
    Write-Host "Hello $Name!"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      相关资源
      最近更新 更多