Powershell循环返回一些不正确的值,但不是全部

时间:2018-07-09 12:40:28

标签: .net powershell

我有一个针对目录运行并在其中查找文件的脚本。然后,根据文件名中包含内部扩展名的一部分,它将通过电子邮件将文件发送给关联的用户。我有90%的工作正常,它将通过电子邮件将正确的文件发送给正确的人,但是电子邮件主题行中的变量是错误的。例如,用于Bob的文件转到Bob,但是电子邮件主题行指示Joe以及Joe的呼叫的CallerID。

$Path = 'c:\test2'
$delim = '-'
$delim2 = '@'
$Port = "587"
$SMTPUsername = "voicemails@test.com"
$EncryptedPasswordFile = "c:\test\voicemails.com.securestring"
$SecureStringPassword = Get-Content -Path $EncryptedPasswordFile | ConvertTo-SecureString
$EmailCredential = New-Object -TypeName Management.Automation.PSCredential($SMTPUsername,$SecureStringPassword )
$DestFolder = 'C:\test2\Processed'
#phone extensions & associated email address
$extensions = @{
  '1000'= 'joe@test.com';
  '23' = 'bob@test.com';
  '765'= 'alice@test.com'
    }
$File = Get-ChildItem $Path -Name
$File | Foreach-object {
    $FirstName = $null
    $nameArray = $_.Split($delim)
    $newName = $nameArray[2]+" "+($nameArray[0].substring(0,8))
    $ext = $nameArray[3]
    $callerID = $nameArray[2]
    $Datestamp = ($nameArray[0].substring(0,8))
    $emailAddress = $extensions[$ext]
    $FirstNameArray = $emailAddress.Split($delim2)
    $FirstName = $FirstNameArray[0]
     $SMTPMessage = @{
        To = $emailAddress
        From = 'voicemails@test.com'
        Subject = $Subject
        Smtpserver = '192.168.1.9'
        }
    $SMTPBody = 'Voicemail redirected message'
    $Subject = "Call Recording on $Datestamp from ($CallerID) to $FirstName"
    Send-MailMessage -Credential $EmailCredential @SMTPMessage -Body $SMTPBody -Attachments $_ -Port $Port
}

我正在针对一些示例文件名运行

  • 20180705072823-1530804495.22-15555552367-1000-Inbound.wav

  • 20180705072823-1530804495.22-15555551234-23-Inbound.wav

  • 20180705072823-1530804495.22-15555557791-765-Inbound.wav

我尝试将每个循环的值设置为$ null,但没有区别。

1 个答案:

答案 0 :(得分:2)

之所以会发生这种情况,是因为哈希表是在设置$subject之前初始化的。

$SMTPMessage = @{
    To = $emailAddress
    From = 'voicemails@test.com'
    Subject = $Subject # Uses old $subject
    Smtpserver = '192.168.1.9'
    }
# Set new subject
$Subject = "Call Recording on $Datestamp from ($CallerID) to $FirstName"

用于说明目的的简单示例:

$subject = "Subject 1"
$SMTPMessage = @{
    To = 'Rec 1'
    Subject = $subject
}
$SMTPMessage

$SMTPMessage = @{
    To = 'Rec 2'
    Subject = $subject
}
$subject = "Subject 2"
$SMTPMessage

Name                           Value
----                           -----
To                             Rec 1
Subject                        Subject 1
To                             Rec 2
Subject                        Subject 1 # Uses the value before reassignment