powershell -and运算符,带有Test-Path语法错误

时间:2017-05-18 21:29:13

标签: powershell syntax-error operators

在下面的代码中,我可以使用-and运算符来创建复合if语句,但是在使用带-and的Test-Path时会出现语法错误。

使用-and和Test-Path等命令的正确方法是什么?

$a = 1
$b = 1
$c = 1
if ($a -eq $b -and $a -eq $c ) {
    write-host "Variables are equal."
}
$path1 = "C:\Windows"
$path2 = "C:\Users"
if (Test-Path $path1 -and Test-Path $path2) {
    write-host "paths exist."
}

2 个答案:

答案 0 :(得分:3)

如果你在Test-Path的用法中放置括号,那么它就可以了,即

$path1 = "C:\Windows"
$path2 = "C:\Users"
if ((Test-Path $path1) -and (Test-Path $path2)) {
    write-host "paths exist."
}

答案 1 :(得分:2)

DeanOC's helpful answer提供了有效的解决方案。

至于 为什么需要括号(括号)

PowerShell有 两种基本解析模式

  • 参数模式,与传统的 shell一样

  • 表达式模式,与传统的编程语言类似。

正在运行Get-help about_Parsing会介绍这些模式。

  • Test-Path $path1Test-Path $path2 隔离参数模式下解析。

  • 运营商-and只能在表达式模式下使用。

  • 为了在表达式模式下使用参数模式Test-Path命令的输出,它们必须包含在(...)中:

    • 使用 (...)强制使用新的解析上下文

    • 给定解析上下文的 1st 标记确定它是以参数还是表达式模式解析。

要考虑的另一件事是 PowerShell对集合 的普遍支持,这通常允许您在更高的抽象级别上运行

$paths = "C:\Windows", "C:\Users" # define *array* of input paths
if ((Test-Path $paths) -notcontains $False) { # See if ALL paths exist.
  "ALL paths exist."
}
  • Test-Path接受要测试的路径的数组,并输出相应的数组布尔值,表示相应的存在。

    < / LI>
  • 运算符-notcontains测试LHS数组中的非成员资格;换句话说:如果Test-Path返回的 no 布尔值为$False,则暗示所有输入路径都存在。

  • 请注意,Write-Host是故意省略的,因为将内容发送到PowerShell的成功流(类似于 stdout < / em>在传统的shell中),你根本不需要显式输出命令,相反,Write-Host实际绕过成功流 - 请参阅{ {3}}