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

问题描述 投票:0回答:1

我正在尝试实现一个包含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
}

我在Write-Output语句之前添加了if语句,该语句确认$Program -match "Report1"返回了$true,但是if语句中的任何内容似乎都没有得到评估。我该怎么办?

powershell if-statement events filesystemwatcher scriptblock
1个回答
1
投票

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

if ($condition) {
    else {
    }
}

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

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

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

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"
}

...,看看是否可行。请注意,我在调用周围添加了()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参数,使其等效于您在-match条件下使用if运算符。请注意,如果您打算在if语句中执行精确的字符串比较,则可以使用例如if ($Program -eq "Report1") {进行不区分大小写的比较。如果您打算执行子字符串比较,则可以使用if ($Program -like "*Report1*") {代替-match运算符。

© www.soinside.com 2019 - 2024. All rights reserved.