我想访问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
}
您唯一的问题是关于如何调用全局函数的语法混淆:
$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
脚本块调用(可能是临时的)脚本文件。另请注意,事件操作块通常将输出写入成功输出流,而不是直接写入具有Write-Host
的主机 - 如果它们需要生成输出 - 可以通过Receive-Job
cmdlet按需收集它。
您可以在Action scriptblock中明确指定您的函数。像这样
#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 {
#Describe your function here
function global:myFunction (){
Write-Host "myFunction"
}
#There call your function
global:myFunction
}