首页 > 解决方案 > filesystemwatcher事件函数powershell中的访问函数

问题描述

我想访问 filesystemwatcher 创建的事件函数中的函数。我尝试使用全局函数,但从未在控制台上看到输出。

#Script Parameters
param(
    [Parameter(Mandatory=$True, position=1)]
    [String]$path
)

#Global Function
function global:myFunction (){
    Write-Host "myFunction"
}

#FileSystemWatcher properties
$fsw = New-Object System.IO.FileSystemWatcher 
$fsw.Path = $path
$fsw.Filter = ""
$fsw.IncludeSubDirectories = $True  
$fsw.EnableRaisingEvents = $True

#Created event function
Register-ObjectEvent -InputObject $fsw -EventName Created -Action{  
  $global:myFunction #trying to access global function
} 

标签: functionpowershellscopeglobal-variables

解决方案


您唯一的问题是关于如何调用全局函数的语法混淆:

$global:myFunction # WRONG - looks for *variable*

查找在全局范围内命名的变量。myFunction

省略$调用函数

global:myFunction # OK - calls function

也就是说,鉴于默认情况下给定会话中的所有范围都看到全局定义,您不需要global:范围说明符 - 只需调用myFunction

  • 您唯一需要global:明确的是当前范围或祖先范围中是否有不同 myFunction的定义,并且您希望显式定位全局定义。
    如果没有global:,这种不同的定义将遮蔽(隐藏)全局定义。

把它们放在一起:

# Script Parameters
param(
    [Parameter(Mandatory=$True, position=1)]
    [String]$path
)

# Global Function
function global:myFunction {
  param($FullName)
  Write-Host "File created: $FullName" 
}

# FileSystemWatcher properties
$fsw = New-Object System.IO.FileSystemWatcher 
$fsw.Path = $path
$fsw.Filter = ""
$fsw.IncludeSubDirectories = $True  
$fsw.EnableRaisingEvents = $True

# Created-event function
$eventJob = Register-ObjectEvent -InputObject $fsw -EventName Created -Action {  
  myFunction $EventArgs.FullPath  # Call the global function.
}

请注意,我已扩展代码以通过myFunction自动$EventArgs变量将新创建文件的完整文件名传递给 。


替代品

由于名称冲突的可能性,从脚本修改全局范围可能会出现问题,尤其是因为即使在脚本终止后全局定义仍然存在。

因此,请考虑:

  • 要么:将函数代码myFunction直接移动到-Action脚本块中。

  • 或:从脚本块调用(可能是临时的)脚本文件。-Action

另请注意,事件操作块通常将输出写入成功输出流,而不是直接写入主机——如果它们需要产生输出——可以通过cmdletWrite-Host按需收集。Receive-Job


推荐阅读