Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell字符串长度验证_Powershell_Cmdlets_Cmdlet - Fatal编程技术网

Powershell字符串长度验证

Powershell字符串长度验证,powershell,cmdlets,cmdlet,Powershell,Cmdlets,Cmdlet,我创建了一个非常简单的HelloWorld.ps1powershell脚本,它接受Name参数,验证其长度,然后打印一条hello消息,例如,如果您将John传递为Name,它应该打印hello John 下面是powershell脚本: param ( [parameter(Mandatory=$true)] [string] $Name ) # Length Validation if ($Name.Length > 10) { Write-Host "

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

下面是powershell脚本:

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"
奇怪的行为是每次我执行它时:

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

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

问题-使用错误的运算符

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

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

如何验证字符串长度?

您可以使用以下哪种方式:

if($Name.Length -gt 10)
param (
    [ValidateLength(1,10)]
    [parameter(Mandatory=$true)]
    [string]
    $Name
)
Write-Host "Hello $Name!"
使用
ValidateLength
属性进行字符串长度验证

可以通过以下方式使用属性:

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