ProfessionalAmateur
ProfessionalAmateur

Reputation: 4563

Powershell giving an error when trying to use -and in an If statement

I'm getting the error:

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

when running this test script.

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    
}

Why doesn't it like my use of -and? If I remove the first evaluation of string.length the statement works as expected.

Upvotes: 2

Views: 534

Answers (1)

Poorkenny
Poorkenny

Reputation: 1246

I can't say exactly why it doesn't like your syntax, but this will work:

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

That forces PowerShell to use the output of the expression between parentheses.

I also fixed the function calls. The PowerShell syntax states that functions are called without parentheses, and by separating arguments with spaces.

Upvotes: 4

Related Questions