基本上,我想检查是否存在目录,如果不退出,则运行此部分。
我的脚本是:
$Path = Test-Path c:tempFirst
if ($Path -eq "False")
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq "true")
{
Write-Host " what the smokes"
}
但它一无所获。
错误源于Test-Path
的返回值是布尔类型。
因此,不要将其与布尔值的字符串表示进行比较,而是与实际的$false
/$true
值进行比较像这样,
$Path = Test-Path c:tempFirst
if ($Path -eq $false)
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq $true)
{
Write-Host " what the smokes"
}
另外,请注意,在这里您可以使用else
语句。
或者,您可以使用@user9569124答案中提出的语法,
$Path = Test-Path c:tempFirst
if (!$Path)
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path)
{
Write-Host " what the smokes"
}
在比较操作中,PowerShell会自动将第二个操作数转换为第一个操作数的类型。由于您将布尔值与字符串进行比较,因此字符串将强制转换为布尔值。空字符串将被强制转换为$false
,非空字符串将强制转换为$true
。Jeffrey Snover写了一篇文章"布尔值和运算符">关于这些自动转换,您可以查看更多详细信息。
因此,这种行为具有(看似矛盾的(效果,每次比较都会评估变量的价值:
PS C:\>$false-eq"false">falsePS C:\>$false-eq"True">falsePS C:\>$true-eq"False">truePS C:\>$true-eq"true">true
本质上,这意味着如果您的Test-Path
语句评估为$false
,则两个条件都不匹配。
正如其他人所指出的,你可以通过将变量与实际布尔值进行比较来解决这个问题,或者只使用变量本身(因为它已经包含了一个可以直接计算的布尔值(。但是,您需要小心后一种方法。在这种情况下,这不会有什么不同,但在其他情况下,将不同的值自动转换为相同的布尔值可能不是所需的行为。例如,$null
、0、空字符串和空数组都被解释为布尔值$false
,但根据代码中的逻辑,它们可能具有完全不同的语义。
此外,不需要首先将Test-Path
的结果存储在变量中。您可以将表达式直接放入条件中。由于只有两个可能的值(文件/文件夹要么存在,要么不存在(,因此不需要进行两次比较,因此您的代码可以简化为这样的值:
if (Test-Path 'C:tempFirst') {
Write-Host 'what the smokes'
} else {
Write-Host 'notthere' -ForegroundColor Yellow
}
如果我没有弄错,可以简单地说:
if($Path)
或if(!$Path)
但我可能错了,因为我不能测试atm。
此外,还有可用的Test-Path
cmdlet。不幸的是,在不了解案例和场景的情况下,我无法描述差异或提出最合适的方法。
【编辑以澄清答案】
$Path = "C:"
if($Path)
{
write-host "The path or file exists"
}
else
{
write-host "The path or file isn't there silly bear!"
}
希望这能增加清晰度。使用此方法,不需要cmdlet。如果返回的布尔值符合测试的条件(在这种情况下,如果路径C:
存在(,它将自动为您解释并运行代码块。较长文件路径中的文件也是如此,C:............file.txt
为了让一些事情变得清楚,请始终使用测试路径(或带有Leaf的测试路径来检查文件(。
我测试过的示例:
$File = "c:pathfile.exe"
$IsPath = Test-Path -Path $File -PathType Leaf
# using -Not or ! to check if a file doesn't exist
if (-Not(Test-Path -Path $File -PathType Leaf)) {
Write-Host "1 Not Found!"
}
if (!(Test-Path -Path $File -PathType Leaf)) {
Write-Host "2 Not Found!"
}
# using -Not or ! to check if a file doesn't exist with the result of Test-Path on a file
If (!$IsPath) {
Write-Host "3 Not Found!"
}
If (-Not $IsPath) {
Write-Host "4 Not Found!"
}
# $null checks must be to the left, why not keep same for all?
If ($true -eq $IsPath) {
Write-Host "1 Found!"
}
# Checking if true shorthand method
If ($IsPath) {
Write-Host "2 Found!"
}
if (Test-Path -Path $File -PathType Leaf) {
Write-Host "3 Found!"
}