为什么我的局部变量为null?

时间:2016-08-09 07:02:51

标签: powershell

我正在使用脚本来轮询文件夹。将文件放入此文件夹后,会向收件人发送电子邮件。

以下是代码:

$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

为什么$name不能用作Send-MailMessage中的参数(它扩展为null),而在Write-Host中将其用作参数可以正常工作?

1 个答案:

答案 0 :(得分:4)

有一个错字,带我好几次才找到它。

$name = $Event.SourceVentArgs.Name

应该是:

$name = $Event.SourceEventArgs.Name

很难说为什么你可能曾经有过$ name的值才能写入主机。