我正在尝试实现一个包含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
语句中的任何内容似乎都没有得到评估。我该怎么办?
您的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
运算符。