Member 14077673 Ответов: 1

Вводимые пользователем данные из предыдущих запусков скрипта переносятся вперед


Привет,

Я написал сценарий Powershell ниже. Он рисует форму с пользовательскими полями ввода, метками и кнопками. Он получает пользовательский ввод через текстовые поля и сохраняет введенные текстовые значения в переменные. Переменные помещаются в определенные поля шаблона HTML-формы. Шаблон текста сообщения, используемых в Send-MailMessage используется.

Таким образом, пользователь вводит значения в текстовые поля и нажимает кнопку - в зависимости от того, какая кнопка, он выполняет другой командлет Send-MailMessage с другим телом сообщения, переменными и т. д.

По большей части это работает. Но у него есть одна существенная ошибка, которую я не могу понять. Когда я выполняю его в первый раз, он рисует форму, позволяет мне ввести свои входные данные и нажать нужную кнопку. Затем не отправляет электронное письмо. Когда я выполняю его во второй раз (и, скажем, на этот раз я ввожу разные текстовые значения в поля ввода), он действительно отправляет электронное письмо, но только содержащее текстовые значения, которые я ввел с моей первоначальной попытки.

Каждый раз, когда я запускаю скрипт, он использует значения ввода текста, которые я предоставил во время моей предыдущей попытки. Если я закрываю Powershell ISE и снова открываю его, он очищает все переменные и поэтому не имеет предыдущих значений для использования.

Это произошло с аналогичным сценарием, который я написал - я решил эту точную проблему, переместив Send-MailMessage в нижнюю часть, причем переменная MessageBody/content была объявлена выше этого, а код поля ввода-выше этого.

Несмотря на воспроизведение одной и той же структуры порядка, проблема остается. Я подозреваю, что это все еще вопрос того, как я упорядочиваю код, но все попытки перестроить потерпели неудачу и вновь породили проблему.

###############################DECLARE VARIABLES#############################

#region
#Declares all variables which do not include variables

$EmailFrom = "Name@email.com"
$SMTPServer = "0.0.0.0"
$SMTPPassword = Get-Content "\\foo\bar\mailpw.txt" | ConvertTo-SecureString
$SMTPCred = New-Object System.Management.Automation.PSCredential "MailUser", $SMTPPassword
$GetDate = get-date -uformat %d/%m/%y
$GetDate_ForEDRMS Product = get-date -uformat %Y%m%d
$CC = "Name@email.com"

#endregion

###############################FORMAT FORM###################################

#region
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "FORM SELECTOR"
$objForm.Size = New-Object System.Drawing.Size(300,1000) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Enter" -or $_.KeyCode -eq "Escape"){
        $objForm.Close()
    }
})
#endregion

###############################DRAW LABELS AND INPUTS########################

#region
#CREATE HEADER LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,5) 
$objLabel.Size = New-Object System.Drawing.Size(280,60) 
    $objLabel.Text = "                ICT On/Off-Boarding Form Selector: 

    1. Enter details relevant to desired form 
    2. Select corresponding button"
$objForm.Controls.Add($objLabel) 

#CREATE FIRSTNAME LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,65) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "First Name:"
$objForm.Controls.Add($objLabel) 

#CREATE FIRSTNAME BUTTON

$Firstname = New-Object System.Windows.Forms.TextBox 
$Firstname.Location = New-Object System.Drawing.Size(10,85) 
$Firstname.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($Firstname) 

#CREATE SURNAME LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,115) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Surname:"
$objForm.Controls.Add($objLabel) 

#CREATE SURNAME BUTTON

$Surname = New-Object System.Windows.Forms.TextBox 
$Surname.Location = New-Object System.Drawing.Size(10,135) 
$Surname.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($Surname) 

#CREATE USERNAME LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,165) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Username:"
$objForm.Controls.Add($objLabel) 

#CREATE USERNAME BUTTON

$Username = New-Object System.Windows.Forms.TextBox 
$Username.Location = New-Object System.Drawing.Size(10,185) 
$Username.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($Username) 

#CREATE PHONE EXT LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,215) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Phone Extension:"
$objForm.Controls.Add($objLabel) 

#CREATE PHONE EXT BUTTON

$PhoneExt = New-Object System.Windows.Forms.TextBox 
$PhoneExt.Location = New-Object System.Drawing.Size(10,235) 
$PhoneExt.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($PhoneExt)

#CREATE PHONE PIN LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,265) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Phone PIN:"
$objForm.Controls.Add($objLabel)  

#CREATE PHONE PIN  BUTTON

$PhonePIN = New-Object System.Windows.Forms.TextBox 
$PhonePIN.Location = New-Object System.Drawing.Size(10,285) 
$PhonePIN.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($PhonePIN) 

#CREATE VM PIN LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,315) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Voicemail PIN:"
$objForm.Controls.Add($objLabel)  

#CREATE VM PIN BUTTON

$VMPIN = New-Object System.Windows.Forms.TextBox 
$VMPIN.Location = New-Object System.Drawing.Size(10,335) 
$VMPIN.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($VMPIN) 

#CREATE EMPLOYEE POSITION LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,365) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Employee Position:"
$objForm.Controls.Add($objLabel)  

#CREATE EMPLOYEE POSITION BUTTON

$EmpPos = New-Object System.Windows.Forms.TextBox 
$EmpPos.Location = New-Object System.Drawing.Size(10,385) 
$EmpPos.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($EmpPos) 

#CREATE DEVICE MAKE LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,415) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Device Make:"
$objForm.Controls.Add($objLabel)  

#CREATE DEVICE MAKE BUTTON

$DeviceMake = New-Object System.Windows.Forms.TextBox 
$DeviceMake.Location = New-Object System.Drawing.Size(10,435) 
$DeviceMake.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($DeviceMake) 

#CREATE DEVICE MODEL LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,465) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Device Model:"
$objForm.Controls.Add($objLabel)  

#CREATE DEVICE MODEL BUTTON

$DeviceModel = New-Object System.Windows.Forms.TextBox 
$DeviceModel.Location = New-Object System.Drawing.Size(10,490) 
$DeviceModel.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($DeviceModel) 

#CREATE SERIAL NUMBER LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,515) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Serial Number:"
$objForm.Controls.Add($objLabel)  

#CREATE SERIAL NUMBER BUTTON

$DeviceSerial = New-Object System.Windows.Forms.TextBox 
$DeviceSerial.Location = New-Object System.Drawing.Size(10,535) 
$DeviceSerial.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($DeviceSerial) 

#CREATE MOBILE NUMBER LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,565) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Mobile Number:"
$objForm.Controls.Add($objLabel)  

#CREATE MOBILE NUMBER BUTTON

$Device_MobileNumber = New-Object System.Windows.Forms.TextBox 
$Device_MobileNumber.Location = New-Object System.Drawing.Size(10,585) 
$Device_MobileNumber.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($Device_MobileNumber) 

#CREATE SIM NUMBER LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,615) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "SIM Number:"
$objForm.Controls.Add($objLabel)  

#CREATE SIM NUMBER BUTTON

$Device_SIM = New-Object System.Windows.Forms.TextBox 
$Device_SIM.Location = New-Object System.Drawing.Size(10,635) 
$Device_SIM.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($Device_SIM) 

#CREATE IMEI NUMBER LABEL

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,665) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "IMEI Number:"
$objForm.Controls.Add($objLabel)  

#CREATE IMEI NUMBER BUTTON

$Device_IMEI = New-Object System.Windows.Forms.TextBox 
$Device_IMEI.Location = New-Object System.Drawing.Size(10,685) 
$Device_IMEI.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($Device_IMEI) 

#endregion

###############################ADD BUTTONS###################################

#region
#Button: Welcome Email 

$WelcomeEmailButton = New-Object System.Windows.Forms.Button
$WelcomeEmailButton.Location = New-Object System.Drawing.Size(10,715)
$WelcomeEmailButton.Size = New-Object System.Drawing.Size(260,23)
$WelcomeEmailButton.Text = "New User ICT On-Boarding Email"
$WelcomeEmailButton.Add_Click($WelcomeEmailButton_OnClick)
$WelcomeEmailButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($WelcomeEmailButton)

#Button: Laptop Agreement 

$LaptopAgreement_Button = New-Object System.Windows.Forms.Button
$LaptopAgreement_Button.Location = New-Object System.Drawing.Size(10,740)
$LaptopAgreement_Button.Size = New-Object System.Drawing.Size(260,23)
$LaptopAgreement_Button.Text = "Employee Laptop Agreement"
$LaptopAgreement_Button.Add_Click($LaptopAgreementButton_OnClick)
$LaptopAgreement_Button.Add_Click({$objForm.Close()})
$objForm.Controls.Add($LaptopAgreement_Button)

#Button: Mobile Agreement

$MobileAgreement_Button = New-Object System.Windows.Forms.Button
$MobileAgreement_Button.Location = New-Object System.Drawing.Size(10,765)
$MobileAgreement_Button.Size = New-Object System.Drawing.Size(260,23)
$MobileAgreement_Button.Text = "Employee Mobile Phone Agreement"
$MobileAgreement_Button.Add_Click($MobileAgreementButton_OnClick)
$MobileAgreement_Button.Add_Click({$objForm.Close()})
$objForm.Controls.Add($MobileAgreement_Button)

#Button: Stage 1 Termination Email to MSP 

$Departing_Stage1toMSP_Button = New-Object System.Windows.Forms.Button
$Departing_Stage1toMSP_Button.Location = New-Object System.Drawing.Size(10,790)
$Departing_Stage1toMSP_Button.Size = New-Object System.Drawing.Size(260,23)
$Departing_Stage1toMSP_Button.Text = "Stage 1 Termination Email to MSP"
$Departing_Stage1toMSP_Button.Add_Click($Departing_Stage1toMSP_Button_OnClick)
$Departing_Stage1toMSP_Button.Add_Click({$objForm.Close()})
$objForm.Controls.Add($Departing_Stage1toMSP_Button)

#Button: Stage 2 Termination Email to MSP 

$Departing_Stage2toMSP_Button = New-Object System.Windows.Forms.Button
$Departing_Stage2toMSP_Button.Location = New-Object System.Drawing.Size(10,815)
$Departing_Stage2toMSP_Button.Size = New-Object System.Drawing.Size(260,23)
$Departing_Stage2toMSP_Button.Text = "Stage 2 Termination Email to MSP"
$Departing_Stage2toMSP_Button.Add_Click($Departing_Stage2toMSP_Button_Onclick)
$Departing_Stage2toMSP_Button.Add_Click({$objForm.Close()})
$objForm.Controls.Add($Departing_Stage2toMSP_Button)

#Button: Off-Boarding Email for Departing Staff

$OffBoarding_EmailTo_DepartingUser_Button = New-Object System.Windows.Forms.Button
$OffBoarding_EmailTo_DepartingUser_Button.Location = New-Object System.Drawing.Size(10,840)
$OffBoarding_EmailTo_DepartingUser_Button.Size = New-Object System.Drawing.Size(260,23)
$OffBoarding_EmailTo_DepartingUser_Button.Text = "Off-Boarding Email for Departing Staff"
$OffBoarding_EmailTo_DepartingUser_Button.Add_Click($OffBoarding_EmailTo_DepartingUser_Button_Onclick)
$OffBoarding_EmailTo_DepartingUser_Button.Add_Click({$objForm.Close()})
$objForm.Controls.Add($OffBoarding_EmailTo_DepartingUser_Button)

#Button: New User Request Email to MSP

$NewUserRequest_toMSP_Button = New-Object System.Windows.Forms.Button
$NewUserRequest_toMSP_Button.Location = New-Object System.Drawing.Size(10,865)
$NewUserRequest_toMSP_Button.Size = New-Object System.Drawing.Size(260,23)
$NewUserRequest_toMSP_Button.Text = "New User Request Email to MSP"
$NewUserRequest_toMSP_Button.Add_Click($NewUserRequest_toMSP_Button_Onclick)
$NewUserRequest_toMSP_Button.Add_Click({$objForm.Close()})
$objForm.Controls.Add($NewUserRequest_toMSP_Button)

#Button: Terminating Staff ICT Asset Return Form

$TerminatingStaff_AssetReturn_Button = New-Object System.Windows.Forms.Button
$TerminatingStaff_AssetReturn_Button.Location = New-Object System.Drawing.Size(10,890)
$TerminatingStaff_AssetReturn_Button.Size = New-Object System.Drawing.Size(260,23)
$TerminatingStaff_AssetReturn_Button.Text = "Terminating Staff ICT Asset Return Form"
$TerminatingStaff_AssetReturn_Button.Add_Click($TerminatingStaff_AssetReturn_Button_OnClick)
$TerminatingStaff_AssetReturn_Button.Add_Click({$objForm.Close()})
$objForm.Controls.Add($TerminatingStaff_AssetReturn_Button)

#endregion

###############################INITIALISE FORM###############################

#region
$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void]$objForm.ShowDialog()
#endregion

###############################DECLARE Email Subject VARIABLES###############

#region


$WelcomeEmail_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Welcome to Foo + ICT On-Boarding Details"
$LaptopAgreement_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Foo Employee Mobile Device Agreement - Laptop"
$MobileAgreement_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Foo Employee Mobile Device Agreement - Mobile Phone"
$Departing_Stage1toMSP_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Foo Employee Mobile Device Agreement - Mobile Phone"
$Departing_Stage2toMSP_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Foo Employee Mobile Device Agreement - Mobile Phone"
$OffBoarding_EmailTo_DepartingUser_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Foo Employee Mobile Device Agreement - Mobile Phone"
$NewUserRequest_toMSP_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Foo Employee Mobile Device Agreement - Mobile Phone"
$TerminatingStaff_AssetReturn_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Foo Employee Mobile Device Agreement - Mobile Phone"

#endregion

###############################START TESTING VARIABLES#######################

#region
Write-host "###################################" -ForegroundColor Green
Write-host "Firstname is $($Firstname.Text)" -ForegroundColor Green
Write-Host "Surname is $($Surname.Text)" -ForegroundColor Green
Write-Host "Username is $($Username.Text)" -ForegroundColor Green
Write-Host "Phone Ext is $($PhoneExt.Text)" -ForegroundColor Green
Write-Host "Phone PIN is $($PhonePIN.Text)" -ForegroundColor Green
Write-Host "Voicemail PIN is $($VMPIN.Text)" -ForegroundColor Green
Write-host "Device Make is $($DeviceMake.Text)" -ForegroundColor Green
Write-Host "Device Model is $($DeviceModel.Text)" -ForegroundColor Green
Write-Host "Device SIM is $($Device_SIM.Text)" -ForegroundColor Green
Write-Host "Device IMEI is $($Device_IMEI.Text)" -ForegroundColor Green
Write-Host "Device Serial is $($DeviceSerial.Text)" -ForegroundColor Green
Write-Host "Employee Position is $($EmpPos.Text)" -ForegroundColor Green
Write-Host "Device Mobile Number is $($Device_MobileNumber.Text)" -ForegroundColor Green
Write-host "###################################" -ForegroundColor Green
#endregion

###############################DEFINE HTML MESSAGES##########################

#region

#New User Welcome Email

#region

$WelcomeEmail_Body = @"

<font face="Calibri">
Hi $($Firstname.text),
<br>
<br>
Welcome to Company! 
<br>
<br>
Please read through the <a href="https://EDRMS Product.Foo.com.au:8443/id:A345125/document/versions/latest ">ICT On-Boarding Guide</a>
<br>
<br>
Some of the information you will find in the guide includes:
<br>
<ul style="List-style-type:circle">
<li>MSP IT Service Desk contact details</li>
<li>Email signature</li>
<li>Adding Printers</li>
<li>VPN Access</li>
<li>Wi-Fi Access</li>
<li>Desk phone login</li>
</ul>
Accessing Webmail:
<Br>
You can access your emails in a web browser on any phone, tablet or computer with an internet connection:
<Br>
<ul style="List-style-type:circle">
<li>Go to <a href="https://mail.Foo.com.au">https://mail.Foo.com.au</a></li>
<li>Log in with Foo\$($Username.Text)</li>
<li>The password is your computer password</li>
</ul>
Your Personalised details:
<Br>
Username: $($Username.Text)
<Br>
Email:  $($Username.Text)@Company.com.au
<Br>
Phone Extension: $($PhoneExt.Text) (+61 02 9255 $($PhoneExt.Text)) Dial 0 for external calls.
<Br>
Phone Username: $($Username.Text)
<Br>
Phone PIN: $($PhonePin.Text)
<Br>
Voicemail PIN: $($VMPIN.Text)
<Br>
<Br>
Additionally, please find attached introductory documentation.
<Br>
<Br>
Please ensure you have read all, as knowledge of these policies is required. 
<Br>
<ul style="List-style-type:circle">
<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A503866/document/versions/latest">Recognising Malicious Email</a></li>
<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A499081/document/versions/latest">Information Security Policy</a></li>
<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A496795/document/versions/latest">Information Classification DLM Guide</a></li>
<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A501188/document/versions/latest">BYOD Policy</a></li>
<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A499079/document/versions/latest">ICT Access Control and Use Policy</a></li>
<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A526460/document/versions/latest">EDRMS Product Navigator Guide</a></li>
<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A465801/document/versions/latest">EDRMS Product Connect Help Guide</a></li>
<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A568499/document/versions/latest">VPN User Guide</a></li>
<li>Meeting Room AV guides:</a></li>
<ul>
	<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A531741/document/versions/latest">Meeting Room 1 Table Input</a></li>
	<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A531740/document/versions/latest">Using "Resident PC" in Meeting Rooms</a></li>
	<li><a href="https://EDRMS Product.Foo.com.au:8443/id:A524751/document/versions/latest">Overall AV User Guide</a></li>
</ul>
</ul>
Kind regards,
<Br>
<br>
<font face="calibri" color="#4682B4"><p style="font-size:1.4em;">Foo Bar
<br>
ICT Coordinator </p></font>
Telephone +02 9255 1767
<Br>
Mobile +0438 224 509
<Br>
<a href="Foo.Bar@Company.com.au">Foo.Bar@Company.com.au</a>
<Br>
AON Tower, Level 27, 201 Kent Street<BR>
Sydney NSW 2000 Australia<br>
<A HREF ="www.Company.com">www.Company.com</a>
<BR>
<br>
<a href="https://www.facebook.com/Companysydney/?utm_source=Company%20Esignature&utm_medium=Banner&utm_campaign=Facebook_Acquisition_Campaign&utm_term=Like%20Us">
  <img src="\\Foo1pwutil01\FooITInstall\PowerShell\Foo_SendWelcomeEmail\DS_OutlookSigPic.png" alt="https://www.facebook.com/Companysydney/?utm_source=Company%20Esignature&utm_medium=Banner&utm_campaign=Facebook_Acquisition_Campaign&utm_term=Like%20Us">
</a>
</font>

"@

#endregion

###############################EXECUTE COMMANDS##############################

#region

#Send Welcome Email

#region
$WelcomeEmailButton_OnClick = 
{
Send-MailMessage `
 -Credential $SMTPCred `
 -To "$Username@Company.com.au" `
 -From $EmailFrom `
 -CC $CC `
 -Subject ` $WelcomeEmail_Subject `
 -SmtpServer $SMTPServer `
 -Body $WelcomeEmail_Body `
 -BodyAsHtml
}
#endregion

#Employee Mobile Device Agreement - Laptop

#region
$LaptopAgreementButton_OnClick = 
{
Send-MailMessage `
 -Credential $SMTPCred `
 -To "$Username@Company.com.au" `
 -From $EmailFrom `
 -CC $CC `
 -Subject $LaptopAgreement_Subject `
 -SmtpServer $SMTPServer `
 -Body $LaptopAgreement_Body `
 -BodyAsHtml `
}
#endregion

#Employee Mobile Device Agreement - Mobile Phone

#region
$MobileAgreementButton_OnClick = 
{
Send-MailMessage `
 -Credential $SMTPCred `
 -To "$Username@Company.com.au" `
 -From $EmailFrom `
 -CC $CC `
 -Subject $MobileAgreement_Subject `
 -SmtpServer $SMTPServer `
 -Body $MobileAgreement_Body `
 -BodyAsHtml `
}
#endregion

#Departing User: Stage 1 Termination Email to MSP

#region
$Departing_Stage1toMSP_Button_Onclick = 
{
Send-MailMessage `
 -Credential $SMTPCred `
 -To "$Username@Company.com.au" `
 -From $EmailFrom `
 -CC $CC `
 -Subject $Departing_Stage1toMSP_Subject `
 -SmtpServer $SMTPServer `
 -Body $DepartingStage1toMSP_Body `
 -BodyAsHtml `
}
#endregion

#Departing User: Stage 2 Termination Email to MSP

#region
$Departing_Stage2toMSP_Button_Onclick = 
{
Send-MailMessage `
 -Credential $SMTPCred `
 -To "$Username@Company.com.au" `
 -From $EmailFrom `
 -Cc $CC `
 -Subject $Departing_Stage2toMSP_Subject `
 -SmtpServer $SMTPServer `
 -Body $DepartingStage2toMSP_Body `
 -BodyAsHtml `
}
#endregion

#Departing User: ICT Off-Boarding Email to Foo User

#region
$OffBoarding_EmailTo_DepartingUser_Button_Onclick = 
{
Send-MailMessage `
 -Credential $SMTPCred `
 -To "$Username@Company.com.au" `
 -From $EmailFrom `
 -CC $CC `
 -Subject $OffBoarding_EmailTo_DepartingUser_Subject `
 -SmtpServer $SMTPServer `
 -Body $OffBoarding_EmailTo_DepartingUser_Body `
 -BodyAsHtml `

}
#endregion

#New User Request Email to MSP

#region
$NewUserRequest_toMSP_Button_Onclick = 
{
Send-MailMessage `
 -Credential $SMTPCred `
 -To "$Username@Company.com.au" `
 -From $EmailFrom `
 -CC $CC `
 -Subject $NewUserRequest_toMSP_Subject `
 -SmtpServer $SMTPServer `
 -Body $NewUserRequest_toMSP_Body `
 -BodyAsHtml `
}
#endregion

#Terminating Staff ICT Asset Return Form

#region
$TerminatingStaff_AssetReturn_Button_OnClick = 
{
Send-MailMessage `
 -Credential $SMTPCred `
 -To "$Username@Company.com.au" `
 -From $EmailFrom `
 -CC $CC `
 -Subject $TerminatingStaff_AssetReturn_Subject `
 -SmtpServer $SMTPServer `
 -Body $TerminatingStaff_AssetReturn_Body `
 -BodyAsHtml `
}
#endregion

#endregion


Что я уже пробовал:

-Перестановке кодовых блоков, чтобы изменить порядок, в каких регионах исполнять
-Активно гуглить и находить мало что помогает в решении такой специфической проблемы
-Исследование и реализация 3 различных методов очистки или удаления переменных, чтобы гарантировать, что переменные данные не переносятся на следующую попытку (хотя это не изменило поведение; и если бы это произошло, я бы опасался, что у меня не будет выходных данных, как во время моего первого запуска после открытия Powershell ISE).

1 Ответов

Рейтинг:
0

Richard Deeming

ShowDialog отображает форму и ожидает ее закрытия.

Вы нажимаете кнопку, которая отправляет электронное письмо с использованием переменных тема и тело, а затем закрывает форму.

После закрытия формы вы используете сведения, введенные в форме, для построения переменных субъекта и тела.

Вам нужно построить переменные субъекта и тела до вы отправляете электронное письмо. Например:

$WelcomeEmailButton_OnClick = 
{
    $WelcomeEmail_Subject = "$GetDate_ForEDRMS Product - $($Firstname.text) $($Surname.Text) - Welcome to Foo + ICT On-Boarding Details"
    
    $WelcomeEmail_Body = @"

<font face="Calibri">
Hi $($Firstname.text),
<br>
<br>
Welcome to Company! 
...
"@
    
    Send-MailMessage `
     -Credential $SMTPCred `
     -To "$Username@Company.com.au" `
     -From $EmailFrom `
     -CC $CC `
     -Subject ` $WelcomeEmail_Subject `
     -SmtpServer $SMTPServer `
     -Body $WelcomeEmail_Body `
     -BodyAsHtml
}