为什么带有多个-AND条件的If语句不能正常运行?

 收藏

我想在Powershell If语句中满足多个条件,并试图使用-AND运算符来实现它,但它似乎只是直接跳转到else子句。

在下面的代码中,我要确保两个文件夹都没有文件,并且“ watcher.txt”文件存在。

$Success = "C:\temp\Success"
$Failed = "C:\temp\failed"
$watcher = "C:\temp\watcher.txt"

$directoryInfo3 = get-childitem "$Success\\*" -file | Measure-Object
$directoryInfo3.count
$directoryInfo4 = get-childitem "$Failed\\*" -file | Measure-Object
$directoryInfo4.count
    if ((test-path -path $Watcher) -AND 
        ($directoryInfo3 -eq 0) -AND 
        ($directoryInfo4 -eq 0)){
         Write-host "Success folder and Failed folder are empty, and Watcher file exists."}
         else
         {Write-host "Not complete yet, rechecking folders."}

如果所有三个语句都为真,那么我应该看到“成功文件夹和失败文件夹为空,并且存在监视程序文件”。

相反,我看到的是“尚未完成,正在重新检查文件夹”。不管条件是什么,即使这三个条件都成立。

回复
  • ousman 回复

    You will need to call $directoryInfo3.count for the statement to result in true. i.e.:

    PS C:\> $dir = gci c:\temp\ -file | measure
    PS C:\> $dir
    
    
    Count    : 36
    Average  :
    Sum      :
    Maximum  :
    Minimum  :
    Property :
    
    PS C:\> $dir -eq 36
    False
    PS C:\> $dir.count -eq 36
    True
    

  • 妖怪 回复

    As you don't seem to be interested in the count or content of the Get-ChildItem,
    you could use Test-Path for all 3 conditions

    ## Q:\Test\2019\05\30\SO_56373080.ps1
    $Success =  "C:\temp\Success"       
    $Failed  =  "C:\temp\failed"       
    $watcher =  "C:\temp\watcher.txt"  
    
    if ( (Test-Path -Path $Watcher   -PathType Leaf) -AND 
        !(Test-Path -Path $Success\* -PathType Leaf) -AND 
        !(Test-Path -Path $Failed\*  -PathType Leaf)){
        Write-host "Success folder and Failed folder are empty, and Watcher file exists."
    } else {
        Write-host "Not complete yet, rechecking folders."
    }
    

    Here ! = Not inverses the boolean result.