Powershell 在 If 语句中尝试使用 -and 时出错

标签 powershell if-statement

我收到错误:

You must provide a value expression on the right-hand side of the '-and' operator.
At C:\shippinginterface\test.ps1:28 char:39
+     if (($TicketNumber.length -gt 0) -and <<<<  IsNumeric($TicketNumber) -and IsNotVoid($DateOut))
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : ExpectedValueExpression

运行此测试脚本时。

function IsNumeric($value) {
   return ($($value.Trim()) -match "^[-]?[0-9.]+$")
}

function IsNotVoid($value) {
    $VoidPattern = [regex]"(?i)void"
    return !$VoidPattern.Match($value).Success
}

############################
# START TEST
############################

$TicketNumber = "12345"
$DateOut = "3/14/2013"

## Verify there is a numeric ticket number, and row is not void for any reason
if (($TicketNumber.length -gt 0) -and IsNumeric($TicketNumber) -and IsNotVoid($DateOut))
{
    write-host $intRow " " $TicketNumber    
}

为什么它不喜欢我使用-and?如果我删除 string.length 的第一个评估,则该语句将按预期工作。

最佳答案

我不能确切地说为什么它不喜欢你的语法,但这会起作用:

if (($TicketNumber.length -gt 0) -and (IsNumeric $TicketNumber) -and (IsNotVoid $DateOut))

这会强制 PowerShell 使用括号之间的表达式的输出。

我还修复了函数调用。 PowerShell 语法规定,调用函数时不使用括号,并用空格分隔参数。

关于Powershell 在 If 语句中尝试使用 -and 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15688779/

相关文章:

mysql - "if"查询mysql

更改 if 语句

powershell - 在json文件数组上使用test-json

Powershell 查找 7 天后过期的用户

powershell - 将多个证书从同一 KeyVault 添加到新的 VMSS

javascript - 我想根据特定条件更改状态

javascript - 我的 javascript 函数逻辑有什么问题?

powershell - 从 powershell 中的目录获取 ssl 证书指纹

powershell - 尝试 Catch 在 Powershell 脚本中不起作用

python - 使用 for 循环创建 if-elif 语句