每个人都试图断断续续地学习 Powershell,而我却被这个问题困住了。我似乎找不到此代码将在 = true 部分接受的等于运算符。 我试过 -eq、=、== 和 ===。 如果此测试路径命令返回真条件,则尝试弹出消息框。
$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")}
最佳答案
首先,true
在 PowerShell 中的字面量是 $true
。而相等比较的运算符是-eq
。然后是 cmdlet 的参数以 -
开头的问题,您需要将命令括在括号中。否则 -eq
将被解释为 Test-Path
的(不存在的)参数。所以把它们放在一起:
If( (Test-Path 'C:\wmw\~$test.xlsx') -eq $True) { ... }
或者,由于 if
只需要一个可以强制转换为 bool 值的值,因此在大多数情况下您甚至不需要显式比较:
if (Test-Path 'C:\wmw\~$test.xlsx') { ... }
future 探索 shell 的一个提示:阅读错误消息。大多数时候它们很有用。
省略括号并使用 -eq
告诉您它被解释为参数的事实:
Test-Path : A parameter cannot be found that matches parameter name 'eq'.
与 =
相同,在此处被解释为参数值:
Test-Path : A positional parameter cannot be found that accepts argument '='.
正确使用括号和使用 -eq
会破坏解析器,无可否认:
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.
使用括号和 =
再次有用:
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.
关于powershell - 等于运算符的初学者问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35020802/