How to call a function from anonymous?

I have this script below and somehow I cannot call a function from this anonymous. I need to call the mail function to send a notification about 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 

The event is caught, the host record writes fine, but the test function is not called.

+4
source share
2 answers

This is not a problem calling a function from "anonymous" (called a script block).

What happens here is that when you point the action to Register-ObjectEvent , it sets the task and sends the action as a command for the task. When an event occurs and the task runs, he does not know what a test function is.

If you really do the Get-Job and see the job, you will see that it worked. The easiest solution is to embed the code. Either you have a function in your session, or by defining it using the global scope:

 function global:test { Write-Host "send email" } 

or manually just defining it in the console or adding to your profile.

Alternatively, you can add a function to the script, say test.ps1 , period, enter it in your $action - . path\to\test.ps1 . path\to\test.ps1 , and then call test :

 $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" . c:\test.ps1 test } 
+7
source

This is problem. Once the event is fired, the script is no longer in scope and therefore cannot see the test function. There are two ways to fix this:

  • Place the test in the global scope:

    global function: test {Write-Host "send email"}

  • Dot-Source script, so the test will be injected into the parent area:

    .. \ YourScript.ps1

0
source

All Articles