I have this script below and somehow cannot call function from this anonymous one.
I need to call mail function to send notification on this event.
function test
{
Write-Host "send email"
}
$action = {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp"
test
}
$folder = 'C:\temp'
$filter = '*.*'
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $true
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated - Action $action
Event is caught, write-host writes fine but test function is not called.
It is not exactly an issue of calling a function from an “anonymous one” ( called a scriptblock).
What is happening here is that when you specify an action to
Register-ObjectEvent, it sets up a job and sends the action as the command for the job. When the event occurs and the job runs, it has no clue what the test function is.If you actually do
Get-Joband see the job, you will see that it has failed. Easiest solution is to inline the code. Or have the function in your session, by either defining it withglobalscope:or manually just defining it in you console or adding it to your profile.
Alternatively, you can add the function to a script, say
test.ps1, dot source it in your$action–. path\to\test.ps1and then calltest: