Powershell 字符串长度验证

标签 powershell cmdlets cmdlet

我创建了一个非常简单的 HelloWorld.ps1接受 Name 的 Power-shell 脚本参数,验证其长度,然后打印一条 hello 消息,例如,如果您通过 JohnName ,它应该打印 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"

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

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

    最佳答案

    问题 - 使用错误的运算符

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

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

    如何验证字符串长度?

    您可以使用 -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!"
    

    关于Powershell 字符串长度验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46421158/

    相关文章:

    tsql - Invoke-Sqlcmd有时会报告TSQL错误,有时却不会。

    powershell - 如何创建一个cmdlet?

    powershell - 较短版本的 powershell cmdlet 参数

    powershell - 如何在管道上的cmdlet之间传递常用的Powershell命令行参数?

    c# - 如何托管Powershell脚本或应用程序,以便可通过WSManConnectionInfo访问它? (例如Office 365)

    c# - 在Powershell Cmdlet中使用 Entity Framework 核心吗?

    powershell - 使用 PowerShell 向服务添加凭据

    powershell - 在PowerShell控制台中使用ANSI/VT100代码输出彩色文本

    powershell - 将脚本部署到目标环境后,如何保证不被修改?

    powershell - 相当于Linux的powershell “mkdir -p”?