function - 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
}
解决方案
您唯一的问题是关于如何调用全局函数的语法混淆:
$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
推荐阅读
- php - 在线访问 xampp 服务器而不会被黑客入侵
- reactjs - 反应加载状态不显示
- reactjs - 通知用户新版本的 React App 可用的最佳实践?
- reactjs - 从 redux-thunk 获取租金时未定义租金?
- python - 使用窗口函数后无法理解时间的输出值?
- boost - Boost:named_mutex 是否需要磁盘 IO?
- spring - 使用 Spring Security 进行身份验证后,如何处理用户按下后退按钮?
- .net - 我们可以在 .NET Framework ASP.NET Web API 中使用 Entity Framework Core 吗?如果有怎么办?
- laravel - 关于heroku中日志的一些困惑
- c# - 在 T-SQL 中编写这个 C# 函数