我为ps脚本创建了一个winforms gui。
通过单击“开始”按钮,脚本将从地址列表中获取数据,修改正文和对象,并发送显示进度条的电子邮件。
# FORM BUTTON START
function ButtonStart_Click {
$script:CancelLoop = $false
$ProgressBar1.Visible = $true
$progressbar1.Value = 0
$LabelCounter.visible = $true
$ButtonStart.Enabled = $false
$ButtonStop.Enabled = $true
$TextBoxSubject.ReadOnly = $true
$TextBoxTimeout.ReadOnly = $true
# =============================================================
# LOOP DATA OBJECT
# =============================================================
$Counter = 0
$ErrorCounter = 0
$Timeout = 0
foreach ($Row in $ExcelData) {
[System.Windows.Forms.Application]::DoEvents()
# =============================================================
# Customize mail subject
# =============================================================
$Id = Get-Random -Minimum 99999999
$Subject = ReplaceChars $TextBoxSubject.Text $Id
$MailSettings.Subject = $Subject
# Check timeout input
if ($TextBoxTimeout.Text -match '^[0-9]+$'){
$Timeout = [int]$TextBoxTimeout.Text
}
# =============================================================
# Customize body
# =============================================================
$BodyHTML = ReplaceChars $Body $Row
# =============================================================
# PROGRESSBAR
# =============================================================
if ($script:CancelLoop -eq $true){
$progressbar1.Value = 0
break
}
# Calculate The Percentage Completed
$Counter++
[Int]$Percentage = ($Counter/$ExcelData.Count)*100
$ProgressBar1.Value = $Percentage
$LabelCounter.Text = "Invio $Counter di " +$ExcelData.Count
# =============================================================
# SEND EMAIL
# =============================================================
if ($Row.Email) {
try {
Send-MailMessage -to $Row.Email -Body $BodyHTML -BodyAsHtml @MailSettings -ErrorAction STOP
if ($Timeout -gt 0) {
Sleep $Timeout
}
}
catch {
Log-Write $ErrorLogFile $_.Exception.Message
$ErrorCounter++;
}
}
}
if ($Counter -eq $ExcelData.Count) {
[System.Windows.Forms.MessageBox]::Show("OK!","Info","OK","Information")
$ButtonStop.Enabled = $false
# Show Errors Popup
if ($ErrorCounter -gt 0) {
[System.Windows.Forms.MessageBox]::Show("Error !","Error","OK","Error")
}
$Form.close()
}
# FORM BUTTON STOP
function ButtonStop_Click {
$script:CancelLoop = $true
$ProgressBar1.Visible = $false
$ProgressBar1.Value = 0
$LabelCounter.Visible = $false
$TextBoxSubject.ReadOnly = $false
$TextBoxSubject.Text = ""
$TextBoxTimeout.ReadOnly = $false
}
我的问题是在脚本执行过程中,GUI似乎冻结了。
即使启用了停止按钮,有时也似乎没有相互作用。
我想尝试在后台启动用于生成和发送邮件的循环(解决冻结问题?),将进度栏和命令按钮保留在主窗口中,但是不幸的是我做不到(我失去了对后台作业的控制)。
可以帮我吗?
谢谢