title: Calling a variable that has been set inside a foreach - powershell
body: <p>Very basic question i'm sorry but I'm sure I had this down before. I want to just know how I can access the variable from inside a <code>foreach</code>. For example in this simple code, it just echos $username but not the exact name i'm after...however if you put echo <code>$user</code> it looks like it can read the <code>foreach</code> and the csv.</p>
  
  <pre><code>add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
  
  $ExSession = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri http://dlonsexh05.server.local/PowerShell/ –Authentication Kerberos
  
  import-PSSession $Exsession -AllowClobber
  
  $users= import-csv 'C:\Surface Pro\users.csv'
  
  foreach ($user in $users){
  
  $duedate = $user.DueDate
  $Username = $user.Name
  $email = $user.EmailAddress
  
  
  $smtpServer = "dlonsexh05.server.local"
  $smtpFrom = "helpdesk@server.com"
  $smtpTo = $email
  $messageSubject = "$username your laptop is due back on $duedate"
  $SMTPPort = "587"
  
  
  
  $message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
  $message.Subject = $messageSubject
  
  $smtp = New-Object Net.Mail.SmtpClient($smtpServer)
  $smtp.Send($message)
  Remove-PSSession $Exsession
  
  break
  
  }
  </code></pre>