Peter Rundqvist Peter Rundqvist - 7 months ago 28
PowerShell Question

Why is my local variable null?

I'm working with a script for polling a folder. Once a file is dropped in this folder, an e-mail is sent to a recipient.

Here's the code:

$folder = "D:\\temptest"
$filter = "*.txt"

$fsw = New-Object System.IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubDirectories = $false
NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite'

$actionToRun = {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceVentArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated

Write-Host $name # --> Here $name contains the file name

$Recipient = "Peter Rundqvist <to address>"
$Sender = "SocSupport <from address>"
$Subject = "New document"
$Body = $name # --> But here, $name is null

Send-MailMessage -To $Recipient -From $Sender -Subject $Subject -Body $Body -SmtpServer "some mail server"

$onCreated = Register-ObjectEvent -InputObject $fsw -EventName Created -SourceIdentifier FileCreated -Action $actionToRun

Why is it that
cannot be used as a parameter in the
(it expands as null), whereas using it as a parameter in
works just fine?


There's a typo, took me a good few runs to find it.

$name = $Event.SourceVentArgs.Name

Should be:

$name = $Event.SourceEventArgs.Name

It's hard to say why you might have ever had a value in $name to be able to write to the host.