Nicholas Adkins
Nicholas Adkins

Reputation: 41

Beginner Problems with Equals Operator

everyone trying to learn Powershell off and on and I'm stuck on this problem. I cannot seem to find an equals operator that this code will accept at the = true portion . Ive tried -eq, =, ==, and === . Trying to get the Msg box to pop up if this Test-path command returns a true condition.

$wshell = New-Object -ComObject Wscript.Shell

If( Test-Path 'C:\wmw\~$test.xlsx' **= True)**
{
     $wshell.Popup("Hey $Env:ComputerName This file is in use!",0,"test")}
else

{$wshell.Popup("Hey $Env:ComputerName This file is not in use!",0,"test")}

Upvotes: 3

Views: 3976

Answers (1)

Joey
Joey

Reputation: 354576

First of all, the literal for true is $true in PowerShell. And the operator for equality comparison is -eq. Then there is the issue that parameters to cmdlets start with - and you'd need to wrap the command in parentheses. Otherwise -eq would be interpreted as a (non-existent) parameter to Test-Path. So putting that all together:

If( (Test-Path 'C:\wmw\~$test.xlsx') -eq $True) { ... }

or, since if just needs a value that can be coerced to a boolean you don't even need the explicit comparison in most cases:

if (Test-Path 'C:\wmw\~$test.xlsx') { ... }

One hint for future exploration of the shell: Read the error messages. Most of the time they are helpful.

Omitting the parentheses and using -eq tells you about the fact that it's interpreted as a parameter:

Test-Path : A parameter cannot be found that matches parameter name 'eq'.

Same with = which is interpreted as a parameter value here:

Test-Path : A positional parameter cannot be found that accepts argument '='.

Using parentheses correctly and using -eq breaks the parser, admittedly:

You must provide a value expression following the '-eq' operator.
Unexpected token 'True' in expression or statement.
Missing closing ')' after expression in 'if' statement.
Unexpected token ')' in expression or statement.

Using parentheses and = is helpful again:

The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property.

Upvotes: 8

Related Questions