Unable to get button click event to work with PowerShell console - works with IS

Hi all.

 

I hope someone can help me with this. I spent a whole day on this and I could not get my head around this. I wrote a simple tool which will allow end-users to manage the distribution lists. I can get this to work with ISE but when I ran this on console, button click event do anything. If someone can help me with this, would be really appreciated.

 

 

#This assembly is required form to function
Try{


Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Import-Module ActiveDirectory
[System.Windows.Forms.Application]::EnableVisualStyles()

}

Catch {$_ | Out-File $LogErrors -Append}

#Setup logging
#######################################################
$Date = Get-Date
$LogPath = "\\mbsvmedc\DLLogs"
$LogGeneral= Join-Path $LogPath 'Gen-DLModify.log'
$LogErrors = Join-Path $LogPath 'Errors-DLModify.log'

#Log Intial details
$admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")
$Whoami = whoami
"Running script $($MyInvocation.MyCommand.Path) at $Date"
"#########################################" |Out-File $LogGeneral -Append
"LogDate: $date" |Out-File $LogGeneral -Append
"Admin: $Admin" | Out-File $LogGeneral -Append
"User: $Whoami" | Out-File $LogGeneral -Append

"#########################################" |Out-File $LogErrors -Append
"LogDate: $date" |Out-File $LogErrors -Append
"User: $Whoami" | Out-File $LogErrors -Append

# Create GUI
########################################################
# Create GUI
########################################################

$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = '450,200'
$Form.text = "Modify Distribution Lists"
$Form.TopMost = $True
$Form.Text = "Modify Distribution Lists"
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.FormBorderStyle = 'Fixed3D'
#$Form.BackColor = "rgb(201, 76, 76)"
$Icon = New-Object system.drawing.icon ("\\MBSVMEDC\c$\DistributionListManagement\3.Resources\2.UC.ico")
$Form.Icon = $Icon

#C:\DistributionListManagement\3.Resources
#\\mbsvmedc\3.Resources
$image = [System.Drawing.Image]::Fromfile("\\MBSVMEDC\3.Resources\1.logo.jpg")
$PictureBox = new-object Windows.Forms.PictureBox # --instantiates a PictureBox $pictureBox.width=320
$PictureBox.height = 240
$PictureBox.top = 0
$PictureBox.left = 368
$PictureBox.Image = $image

$Label1 = New-Object system.Windows.Forms.Label
$Label1.text = "*DL Name"
$Label1.AutoSize = $True
$Label1.width = 25
$Label1.height = 10
$Label1.location = New-Object System.Drawing.Point(32,32)
$Label1.Font = 'Microsoft Sans Serif,10'

$TextBox1 = New-Object system.Windows.Forms.TextBox
$TextBox1.multiline = $False
$TextBox1.width = 185
$TextBox1.height = 20
$TextBox1.location = New-Object System.Drawing.Point(230,32)
$TextBox1.Font = 'Microsoft Sans Serif,10'
$TextBox1.tabindex = 0
#Check whether user has entered values for mandatory fields
$TextBox1.Add_TextChanged({Validate-TextBox1})

$Label2 = New-Object system.Windows.Forms.Label
$Label2.text = "Email addresses to be added"
$Label2.AutoSize = $true
$Label2.width = 25
$Label2.height = 10
$Label2.location = New-Object System.Drawing.Point(32,64)
$Label2.Font = 'Microsoft Sans Serif,10'

$TextBox2 = New-Object system.Windows.Forms.TextBox
$TextBox2.multiline = $false
$TextBox2.width = 185
$TextBox2.height = 20
$TextBox2.location = New-Object System.Drawing.Point(230,64)
$TextBox2.Font = 'Microsoft Sans Serif,10'
$TextBox2.tabindex = 1
#Check whether user has entered values for mandatory fields
$TextBox2.Add_TextChanged({Validate-TextBox2})

$AddButton = New-Object system.Windows.Forms.Button
$AddButton.text = "Add Memeber"
$AddButton.width = 185
$AddButton.height = 26
$AddButton.location = New-Object System.Drawing.Point(230,96)
$AddButton.Font = 'Microsoft Sans Serif,10'
$AddButton.Enabled = $False
$AddButton.TabIndex = 3

$Label3 = New-Object system.Windows.Forms.Label
$Label3.text = "Email addresses to be removed"
$Label3.AutoSize = $true
$Label3.width = 25
$Label3.height = 10
$Label3.location = New-Object System.Drawing.Point(32,128)
$Label3.Font = 'Microsoft Sans Serif,10'

$TextBox3 = New-Object system.Windows.Forms.TextBox
$TextBox3.multiline = $false
$TextBox3.width = 185
$TextBox3.height = 20
$TextBox3.location = New-Object System.Drawing.Point(230,128)
$TextBox3.Font = 'Microsoft Sans Serif,10'
$TextBox3.tabindex = 1
#Check whether user has entered values for mandatory fields
$TextBox3.Add_TextChanged({Validate-TextBox3})

$RemoveButton = New-Object system.Windows.Forms.Button
$RemoveButton.text = "Remove Memeber"
$RemoveButton.width = 185
$RemoveButton.height = 26
$RemoveButton.location = New-Object System.Drawing.Point(230,160)
$RemoveButton.Font = 'Microsoft Sans Serif,10'
$RemoveButton.Enabled = $false
$RemoveButton.TabIndex = 3

########################################################
#End of GUI

Try {
$MailSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://MBSVEX01/PowerShell/
"Initiate a new session to onprem exchange server" | Out-File $LogGeneral -Append
# [System.Windows.MessageBox]::Show('Hello2')
# [System.Windows.MessageBox]::Show("Please enter a valid Group Memeber", "Invalid Group Memeber")
Import-PsSession $MailSession -AllowClobber
"Import exchange server cmdlts"|Out-File $LogGeneral -Append
}

Catch {$_ | Out-File $LogErrors -Append}
########################################################
#Global Variables

#$global:DL=""
#$global:c=0
#$global:d=0

#Button click event trigger
########################################################
$AddButton.Add_Click($eventHandler1) ;
$RemoveButton.Add_Click($eventHandler2) ;
########################################################

#Verify user has entered values to first name, last name and Ticket number text boxes

function Validate-TextBox1(){
if($TextBox1.Text -and $TextBox2.Text)
{
$AddButton.Enabled = $true
#Set the email subject value to ticket number(value in textbox 12)
#$global:DL = $TextBox1.Text
}
else { $AddButton.Enabled = $False
}

if($TextBox1.Text -and $TextBox3.Text)
{
#Enable remove button
$RemoveButton.Enabled = $True
# $global:DL = $TextBox1.Text
}
else {$RemoveButton.Enabled = $False
}

}

function Validate-TextBox2(){
if($TextBox1.Text -and $TextBox2.Text)
{
$AddButton.Enabled = $true
#Set the email subject value to ticket number(value in textbox 12)
#$global:DL = $TextBox1.Text

}
else{
#Disable "OK" button, if user has not entered values for
$AddButton.Enabled = $false

}
}

function Validate-TextBox3(){
if($TextBox1.Text -and $TextBox3.Text)
{
$RemoveButton.Enabled = $true
#Set the email subject value to ticket number(value in textbox 12)
#$global:DL = $TextBox1.Text

}
else{
#Disable "OK" button, if user has not entered values for
$RemoveButton.Enabled = $false

}
}

Function Add-DLMemeber {

Try{
Add-DistributionGroupMember -Identity "$global:DL" -Member $TextBox2.text -Confirm:$false -ErrorAction stop
"Added" + $TextBox2.text + "to $global:DL" | Out-File $LogGeneral -Append

$myOutput = [System.Windows.Forms.MessageBox]::Show("Added "+ $TextBox2.text + " to $global:DL","Information",0,`
[System.Windows.Forms.MessageBoxIcon]::Information)

}

Catch {$_ | Out-File $LogErrors -Append}

}

Function Remove-DLMemeber {
Try{
Remove-DistributionGroupMember -Identity "$global:DL" -Member $TextBox3.text -Confirm:$false
"Removed" + $TextBox3.text + "from $global:DL" | Out-File $LogGeneral -Append

$myOutput = [System.Windows.Forms.MessageBox]::Show("Removed "+ $TextBox2.text +" from $global:DL","Information",0,`
[System.Windows.Forms.MessageBoxIcon]::Information)
}
Catch {$_ | Out-File $LogErrors -Append}


}

Function Validate-EmailAddress($Email){
Write-host "recieving email is $Email"
Try{
$X =0
$X= ((Get-Recipient $Email -EA silentlycontinue ) | Measure-Object).Count
"Provided E-mail address is valid" | Out-File $LogGeneral -Append

Write-Host "$x"
If ($X -eq 0) { #$Message = $TextBox2.text +": is not a valid email address"
#Write-Host "It comes her 11111"
return $False
# Write-Host "It comes her 2222222"
}
else { #Write-Host "It comes her 33333333"
return $True
}

}
Catch {$_ | Out-File $LogErrors -Append}
}

Function Validate-GroupMembership($EmailAddress){

TRY{
#$GroupEmailAddresses = Get-DistributionGroupMember -Identity "$global:DL"|Select -ExpandProperty PrimarySMTPAddress
$GroupEmailAddresses = Get-DistributionGroupMember -Identity "$global:DL" -ErrorAction stop
$y=0
#$ForwardMailAddress = $TextBox2.text
$UserAccount =Get-Recipient $EmailAddress | select -ExpandProperty samaccountname -ErrorAction Stop
foreach ($MailAddress in $GroupEmailAddresses)
{
If ( $MailAddress.samaccountname -eq $UserAccount)
{
$Val = "True"
$y = $y + 1
#write-host "It came here"
#write-host $ForwardMailAddress
#write-host $MailAddress.PrimarySMTPAddress
break
}
else
{ $Val = "False"
#write-host "$ForwardMailAddress"
#write-host $MailAddress.PrimarySMTPAddress
# return $False
}
}

Write-Host "`$y is $y"
If ($y -gt 0) {
"Provided E-mail address is a memeber of DL" | Out-File $LogGeneral -Append
Return $True} else {Return $False}
}
Catch {$_ | Out-File $LogErrors -Append}

}

Function Validate-DistributionGroup{
if (((Get-DistributionGroup "$global:DL" -ErrorAction SilentlyContinue ).IsValid) -eq $true)
{return $True} else {return $false}

}

#when user press "Create" button below code will excecute
$eventHandler1 = [System.EventHandler]{
# $myOutput = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to perform exit actions for user $global:username ?","Warning",4,[System.Windows.Forms.MessageBoxIcon]::Warning)

#[System.Windows.MessageBox]::Show('Hello3')
$global:DL = $TextBox1.Text

$ResultDG = (Validate-DistributionGroup)

If ( $ResultDG -eq 'True') {Write-Host "valid Dl"}
else {Write-Host "invalid Dl"

[Systems.Windows.Forms.MessageBox]::Show('Invalid Distribution List')
#Z[System.Windows.MessageBox]::Show("Please enter a valid Distribution List", "Invalid Distribution List")
return
}

$ResultEA = (Validate-EmailAddress($textbox2.text))
If ( $ResultEA -eq 'True') {Write-Host "valid Email Address"}
else {Write-Host "invalid Email Address"
[System.Windows.MessageBox]::Show("Please enter a valid E-mail Address", "Invalid E-mail Address")
return }

$ResultGM = (Validate-GroupMembership($textbox2.text))
If ( $ResultGM -eq 'True') {Write-Host " Group Memeber already exists"
[System.Windows.MessageBox]::Show("Please enter a valid Group Memeber", "Invalid Group Memeber")
return
}
else {Write-Host " Group Memeber is ready to be added"
Add-DLMemeber
}

}

$eventHandler2 = [System.EventHandler]{

$global:DL = $TextBox1.Text

$ResultDG = (Validate-DistributionGroup)

If ( $ResultDG -eq 'True') {Write-Host "valid Dl"}
else {Write-Host "invalid Dl"

[System.Windows.MessageBox]::Show("Please enter a valid Distribution List", "Invalid Distribution List")
return
}

$ResultEA = (Validate-EmailAddress($TextBox3.text))
If ( $ResultEA -eq 'True') {Write-Host "valid Email Address"}
else {Write-Host "invalid Email Address"
[System.Windows.MessageBox]::Show("Please enter a valid E-mail Address", "Invalid E-mail Address")
return }

$ResultGM = (Validate-GroupMembership($TextBox3.text))
If ( $ResultGM -eq 'True') {Write-Host " Group Memeber is ready to be removed"
Remove-DLMemeber

}
else {
[System.Windows.MessageBox]::Show("Please enter a valid Group Memeber", "Invalid Group Memeber")
return
Write-Host " Group Memeber is Invalid "
}

}

#Display form objects
$Form.controls.AddRange(@($Label1,$TextBox1,$Label2,$TextBox2,$Label3,$TextBox3,$AddButton ,$RemoveButton,$PictureBox ))

$Form.ShowDialog()

Hi all,

 

I found what I was doing wrong. I had to add button click events after the events.

 

Thanks

Don