FileSystemWatcher 中的 If 语句在 Powershell 中不起作用

If statement within FileSystemWatcher Not working in Powershell

我正在尝试实现一个 FileSystemWatcher,其中包含一个 if 语句,该语句评估并传递给它的参数,但它似乎没有评估。我犯错了吗?这是代码:

Function Auto-Watcher
{
    param ($folder, $filter, $Program)

    $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
        IncludeSubdirectories = $true
        EnableRaisingEvents = $true
    }

    Write-Host "Watching $folder for creation or moving of $filter files..."

    $changeAction = {
        $path = $Event.SourceEventArgs.FullPath
        $name = $Event.SourceEventArgs.Name
        $changeType = $Event.SourceEventArgs.ChangeType
        $timeStamp = $Event.TimeGenerated

        if ($Program -match "Report1") {
            Write-Host $Path "Ready for Report1 Generation"
            else {
                if ($Program -match "Report2") {
                    Write-Host Split-Path $Path "Ready for Report2 Generation"
                    else {
                        write-output "Error, not capable of matching identical strings"
                    }
                }
            }
        }

        Write-Host "The file $name was $changeType at $timeStamp"
    }
    Register-ObjectEvent $Watcher -EventName "Created" -Action $changeAction
}

我在 if 语句之前添加了 Write-Output 语句,确认 $Program -match "Report1" 正在返回 $true,但 if 语句中似乎没有任何内容待评估。我能做什么?

您的 if/else 结构在 $changeAction 中不正确。两个 else 块都在 内部 应该是它们关联的 if 块。也就是说,你有这个...

if ($condition) {
    else {
    }
}

...什么时候应该是这样...

if ($condition) {
    # $true branch
} else {
    # $false branch
}

尝试像这样在 $changeAction 中定义 if 结构...

if ($Program -match "Report1") {
    Write-Host $Path "Ready for Report1 Generation"
} elseif ($Program -match "Report2") {
    Write-Host (Split-Path $Path) "Ready for Report2 Generation"
} else {
    Write-Output "Error, not capable of matching identical strings"
}

...看看是否可行。请注意,我在对 Split-Path $Path 的调用周围添加了 () 以便对其进行评估并将结果传递给 Write-Host.

您也可以使用 switch 语句重写上面的内容...

switch -Regex ($Program) {
    "Report1" {
        Write-Host $Path "Ready for Report1 Generation"
        break
    }
    "Report2" {
        Write-Host (Split-Path $Path) "Ready for Report2 Generation"
        break
    }
    Default {
        Write-Output "Error, not capable of matching identical strings"
        break
    }
}

我添加了 -Regex 参数,使其等同于您在 if 条件下使用 -match 运算符。请注意,如果您的意图是在 if 语句中执行精确的字符串比较,您可以使用,例如,if ($Program -eq "Report1") { 来执行不区分大小写的比较。如果您的意图是执行子字符串比较,您可以使用 if ($Program -like "*Report1*") { 而不是 -match 运算符。