filesystemwatcher事件函数powershell中的访问函数

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

我想访问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
} 
function powershell scope global-variables
2个回答
0
投票

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

$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按需收集它。


0
投票

您可以在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
}
© www.soinside.com 2019 - 2024. All rights reserved.