I have observed a difference in behavior between PowerShell 2.0 code and 3.0 code but can't seem to fix it. I am hoping I can get some help. Please see code below.
If you run this in V2 (please change ServerA and ServerB to a server on your network) you will see after selecting and clicking the button, write-host shows them as seperate names. In version 3 the listbox populates it as 1.
$Servers = #()
[array]$ServerstoPing = ("ServerA","ServerB")
# Generate the form
Add-Type -AssemblyName System.Windows.Forms
$Form1 = New-Object system.Windows.Forms.Form
$Form1.Text = "Ping Some Servers"
$Font = New-Object System.Drawing.Font("Calibri",18,[System.Drawing.FontStyle]::regular)
$Fontboxes = New-Object System.Drawing.Font("Lucida Sans",8,[System.Drawing.FontStyle]::regular)
$Fontdate = New-Object System.Drawing.Font("Lucida Sans",11,[System.Drawing.FontStyle]::bold)
$FontProgress = New-Object System.Drawing.Font("Lucida Sans",11,[System.Drawing.FontStyle]::bold)
$Form1.Font = $Font
$Serverlistbox = New-Object System.Windows.Forms.Listbox
$Serverlistbox.Location = New-Object System.Drawing.Size(11,137)
$Serverlistbox.Size = New-Object System.Drawing.Size(200,170)
$Serverlistbox.SelectionMode = "MultiExtended"
$Serverlistbox.font = $Fontboxes
foreach($item in $ServerstoPing){
[void] $Serverlistbox.Items.Add("$item")
}
$Form1.Controls.Add($Serverlistbox)
$SubmitButton = New-Object System.Windows.Forms.button
$SubmitButton.text = "Ping Servers"
$SubmitButton.Location = New-Object System.Drawing.Size(171,305)
$SubmitButton.AutoSize = $True
$Form1.Controls.Add($SubmitButton)
$Form1.StartPosition = "CenterScreen"
$OutputPing = New-Object System.Windows.Forms.TextBox
$OutputPing.MultiLine = $True
$OutputPing.ScrollBars = "Vertical"
$OutputPing.text = "Server ping status will be displayed here once done'."
$OutputPing.font = $Fontboxes
$OutputPing.Location = New-Object System.Drawing.Size(226,40)
$OutputPing.Size = New-Object System.Drawing.Size(200,255)
$Form1.Controls.Add($OutputPing)
$SubmitButton.add_click({
#foreach ($objItem in $ServerstoPing)
foreach ($objItem in $Serverlistbox.SelectedItems)
{
$Servers += $objItem
}
write-host $ServerstoPing
Foreach($server in $servers)
{
ping -n 1 -w 1000 $server | out-null
if($? -eq $true){
write-host ("$server ping success")
}
else
{
write-host ("$server did not respond to ping, not extracting events")
}
}
})
$Form1.ShowDialog()
Related
With the below code, my goal is to ping a hostname and have it return if successful or unsuccessful, and project that on the GUI screen itself. At the moment I am getting errors on the "-TargetName".
Add-Type -assembly System.Windows.Forms
# Create window form
$main_form = New-Object System.Windows.Forms.Form
$main_form.Text = 'Device Info'
$main_form.Width = 600
$main_form.Height = 400
$main_form.AutoSize = $true
# Start of code
$Label = New-Object System.Windows.Forms.Label
$Label.Text = "Hostname"
$Label.Location = New-Object System.Drawing.Point(10, 30)
$Label.AutoSize = $true
$main_form.Controls.Add($Label)
# Adding textbox
$TextBox = New-Object System.Windows.Forms.TextBox
$TextBox.Location = New-Object System.Drawing.Point(90, 30)
$TextBox.Width = 300
$main_form.Controls.Add($TextBox)
# Adding check button
$CheckButton = New-Object System.Windows.Forms.Button
$CheckButton.Location = New-Object System.Drawing.Size(400, 30)
$CheckButton.Size = New-Object System.Drawing.Size(120, 23)
$CheckButton.Text = "Check"
$main_form.Controls.Add($CheckButton)
# Perform event when check button is clicked
$ComputerName = $TextBox.Text
$CheckButton.Add_Click(
{
Test-Connection -TargetName $ComputerName -IPv4
}
)
# Show Window
$main_form.ShowDialog()
You need to grab the value from $TextBox.Text when the button is clicked, and then use the correct parameter name (-ComputerName rather than -TargetName)!
Change this:
$ComputerName = $TextBox.Text
$CheckButton.Add_Click(
{
Test-Connection -TargetName $ComputerName -IPv4
}
)
To:
$CheckButton.Add_Click(
{
$ComputerName = $TextBox.Text
Test-Connection -ComputerName $ComputerName -IPv4
}
)
I am currently working on an auto installer for newly configured computers where I work. It has a GUI which allows you to choose which programs will be installed. When the file paths are correct the GUI is blank but when I purposefully mess up the file paths the checkboxes will pop back up.
Sorry if this seems like a very dumb question. I am extremely new to this and have gotten a lot of help from various different websites. This is basically me working off of another auto installer script that I found on this website.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(600,700)
$Form.text ="Software Installer"
############################################## Start group boxes
$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size (10,20)
$groupBox.text = "Available Software to Install:"
$Form.Controls.Add($groupBox)
$Checkboxes += New-Object System.Windows.Forms.CheckBox
$Checkboxes = New-Object System.Drawing.Size (10,20)
$Button1 = New-Object System.Windows.Forms.Button
$Button1.text = "Install"
$Button1.width = 100
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(245,585)
$Button1.Font = 'Microsoft Sans Serif,10'
$apps = [PSCustomObject]#{
Name = ''
Path = ''
PreTransfer = ''
}
$apps = Import-Csv -Path C:\Users\Zach\Desktop\Installers\appslist.csv
$groupBox.Controls.Add($Button1)
$Checkboxes = #()
$y = 20
foreach ($a in $apps)
{
$Checkbox = New-Object System.Windows.Forms.CheckBox
$Checkbox.name = $a.Name
$Checkbox.Text = $a.Name
$Checkbox.Location = New-Object System.Drawing.Size(10,$y)
$y += 30
$groupBox.Controls.Add($Checkbox)
$Checkboxes += $Checkbox
}
$groupbox.size = New-Object System.Drawing.Size(564,(624*$checkboxes.Count))
#to look at each box
$Button1.Add_Click({
foreach ($i in $Checkboxes){
if ($i.checked -eq $true) {
Start-Process $i.AccessibleDescription
}
}
})
$form.ShowDialog()| Out-Null
I'm working on a script but for some reason my ProgressBar won't appear in my groupbox.
I tried a lot of different things (like making the groupbox trensparent) but nothing really work.
Here is my code 'simplified' with just the problematic parts.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object System.Windows.Forms.Form
$Form.ClientSize = ‘345,160’
$Form.Text = " bug progressbar "
$Form.StartPosition = "CenterScreen"
#Functions
Function BDDchoice(){
$BDD = $args[0]
$Label2.Text = "it takes a few seconds"
$ProgressBarcheck = New-Object System.Windows.Forms.ProgressBar
$ProgressBarcheck.Location = New-Object System.Drawing.Point(230,49)
$ProgressBarcheck.Size = New-Object System.Drawing.Size(98, 23)
$ProgressBarcheck.Style = "Marquee"
$ProgressBarcheck.MarqueeAnimationSpeed = 20
$ButtonNEXT1.Hide()
$Form.Controls.Add($ProgressBarcheck);
$job1 ={
sleep 10
$bdd_min = $args[0]
echo $bdd_min
}
Start-Job -ScriptBlock $job1 -ArgumentList $BDD -Name bdd
do { [System.Windows.Forms.Application]::DoEvents() } until ((Get-Job -Name bdd).State -eq "Completed")
Wait-Job -Name bdd
$resultat = Receive-Job -Name bdd -Keep
Get-Job | Remove-Job -Force
$TextBoxBDD.text = $resultat
$ProgressBarcheck.Hide()
$ButtonNEXT1.Visible = $true
$Label2.Text = "BDD:"
}
#variables
$BDDXS = #('SCHEM1','SCHEM2','SCHEM3','SCHEM4')
$BDD1 = 'BDD1'
$BDD2 = 'BDD2'
$BDD3 = 'BDD3'
$BDD4 = 'BDD4'
$BDD = $null
#groupbox
$GroupBoxCREATE = New-Object System.Windows.Forms.GroupBox
$GroupBoxCREATE.Location = New-Object System.Drawing.Point(10,5)
$GroupBoxCREATE.Width = 325
$GroupBoxCREATE.Height = 150
$GroupBoxCREATE.Text = " Create "
#combobox ZONE
$comboBoxTRIG = New-Object System.Windows.Forms.ComboBox
$comboBoxTRIG.Location = New-Object System.Drawing.Point(25, 50)
$comboBoxTRIG.Size = New-Object System.Drawing.Size(200, 200)
foreach($BDDX in $BDDXS)
{
$comboBoxTRIG.Items.add($BDDX)
}
$comboBoxTRIG.Text = "REGION"
$comboBoxTRIG.AutoCompleteMode = "SuggestAppend"
$comboBoxTRIG.AutoCompleteSource = "ListItems"
$comboBoxTRIG.SelectedIndex ="0"
#butons
$ButtonNEXT1 = New-Object System.Windows.Forms.Button
$ButtonNEXT1.Location = New-Object System.Drawing.Point(230,49)
$ButtonNEXT1.Size = New-Object System.Drawing.Size(98, 23)
$ButtonNEXT1.Text = "OK"
$ButtonNEXT1.add_Click({
$zone = $comboBoxTRIG.SelectedItem.ToString()
if ($zone -like "SCHEM1"){
$BDD = $BDD1
}
if ($zone -like "SCHEM2") {
$BDD = $BDD2
}
if ($zone -like "SCHEM3") {
$BDD = $BDD3
}
if ($zone -like "SCHEM4") {
$BDD = $BDD4
}
BDDchoice($BDD)
})
#labels
$Label1 = New-Object System.Windows.Forms.Label
$Label1.Location = New-Object System.Drawing.Point(25,25)
$Label1.Text = "REGION :"
$Label2 = New-Object System.Windows.Forms.Label
$Label2.Location = New-Object System.Drawing.Point(25,80)
$label2.Width = 200
$Label2.Text = "BDD :"
#textbox
$TextBoxBDD = New-Object System.Windows.Forms.TextBox
$TextBoxBDD.Location = New-Object System.Drawing.Point(25,100)
$TextBoxBDD.Width = 200
$TextBoxBDD.ReadOnly = $true
$TextBoxBDD.Text = ""
$TextboxBDD.BackColor = "white"
#list form's butons/lists/combobox
$Form.Controls.AddRange(#($TextBoxBDD))
$Form.controls.AddRange(#($Label1,$Label2))
$Form.controls.AddRange(#($ButtonNEXT1))
$Form.controls.AddRange(#($comboBoxTRIG))
$Form.controls.AddRange(#($GroupBoxCREATE))
$Form.ShowDialog()
i'm interested in any idea.
My coworkers could not find anything but I must admit we are far from expert (i'm still learning and so are they).
$Form.Controls.Add($ProgressBarcheck);
It looks like you're adding Progress Bar to your form, NOT the groupbox. Add progress bar to groupbox then add groupbox to form.
$GroupBoxCREATE.Controls.Add($ProgressBarcheck);
$Form.Controls.Add($GroupBoxCREATE);
I want to prevent my Powershell Form from closing after a submit button is pressed. After the function "search_PC" there is no more code and the form closes. I want to still be able to write stuff in there after the function is finished. I have already tried the pause function and while($true) loops. I would be very happy about an answer.
Import-Module ActiveDirectory
# Assembly for GUI
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Create Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Size = New-Object System.Drawing.Size(400,500)
$objForm.Backcolor="white"
$objForm.StartPosition = "CenterScreen"
$objForm.Text = "Example Software"
$objForm.Icon="C:\Users\...\icon.ico"
# Label
$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(80,30)
$objLabel1.Size = New-Object System.Drawing.Size(60,20)
$objLabel1.Text = "UserID:"
$objForm.Controls.Add($objLabel1)
# Textbox
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(160,28)
$objTextBox1.Size = New-Object System.Drawing.Size(100,20)
$objForm.Controls.Add($objTextBox1)
# Label
$objLabel2 = New-Object System.Windows.Forms.Label
$objLabel2.Location = New-Object System.Drawing.Size(80,72)
$objLabel2.Size = New-Object System.Drawing.Size(80,20)
$objLabel2.Text = "PC-Name:"
$objForm.Controls.Add($objLabel2)
# Textbox
$objTextBox2 = New-Object System.Windows.Forms.TextBox
$objTextBox2.Location = New-Object System.Drawing.Size(160,70)
$objTextBox2.Size = New-Object System.Drawing.Size(100,20)
$objForm.Controls.Add($objTextBox2)
# Button for closing
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(100,220)
$CancelButton.Size = New-Object System.Drawing.Size(163,25)
$CancelButton.Text = "Exit"
$CancelButton.Name = "Exit"
$CancelButton.DialogResult = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
# Checkbox
$objTypeCheckbox1 = New-Object System.Windows.Forms.Checkbox
$objTypeCheckbox1.Location = New-Object System.Drawing.Size(80,120)
$objTypeCheckbox1.Size = New-Object System.Drawing.Size(500,20)
$objTypeCheckbox1.Text = "Internal Session Support"
$objTypeCheckbox1.TabIndex = 1
$objTypeCheckbox1.Add_Click({$objTypeCheckbox2.Checked = $false})
$objForm.Controls.Add($objTypeCheckbox1)
# Checkbox
$objTypeCheckbox2 = New-Object System.Windows.Forms.Checkbox
$objTypeCheckbox2.Location = New-Object System.Drawing.Size(80,140)
$objTypeCheckbox2.Size = New-Object System.Drawing.Size(500,20)
$objTypeCheckbox2.Text = "Session Support Internal & external"
$objTypeCheckbox2.TabIndex = 2
$objTypeCheckbox2.Add_Click({$objTypeCheckbox1.Checked = $false})
$objForm.Controls.Add($objTypeCheckbox2)
# Button fo checking the User Input
$SubmitButton = New-Object System.Windows.Forms.Button
$SubmitButton.Location = New-Object System.Drawing.Size(100,190)
$SubmitButton.Size = New-Object System.Drawing.Size(163,25)
$SubmitButton.Text = "Submit"
$SubmitButton.Name = "Submit"
$SubmitButton.DialogResult = "OK"
$objForm.AcceptButton = $SubmitButton
$SubmitButton.Add_Click({
$User = $objTextBox1.Text
$PC = $objTextBox2.Text
# Check if all User Inputs are filled out
if ( !($User.trim()) -or !($PC.trim()) ) {
[void] [Windows.Forms.MessageBox]::Show("Please fill out every value!", "Error", [Windows.Forms.MessageBoxButtons]::ok, [Windows.Forms.MessageBoxIcon]::Warning)}
if($objTypeCheckbox1.checked -eq $true) {$Software = "Internal"}
elseif($objTypeCheckbox2.checked -eq $true) {$Software = "Internal&External"}
else {[void] [Windows.Forms.MessageBox]::Show("Please fill out every value!", "Error", [Windows.Forms.MessageBoxButtons]::ok, [Windows.Forms.MessageBoxIcon]::Warning)}
search_user
})
$objForm.Controls.Add($SubmitButton)
$statusBar1 = New-Object System.Windows.Forms.StatusBar
$objForm.controls.add($statusBar1)
function createFile
{
$Date = Get-Date -Format d.M.yyyy
$Time = (Get-Date).ToString(„HH:mm:ss“)
$Time2 = (Get-Date).ToString(„HH-mm-ss“)
$Date2 = Get-Date -Format yyyy-M-d;
$FileName = $Time2 + " " + $Date2
$wrapper = New-Object PSObject -Property #{ 1 = $Date; 2 = $Time; 3 = $User; 4 = $PC; 5 = $Software }
Export-Csv -InputObject $wrapper -Path C:\Users\...\$FileName.csv -NoTypeInformation
[void] [Windows.Forms.MessageBox]::Show("Successful!")
}
function search_user
{
if (#(Get-ADUser -Filter {SamAccountName -eq $User}).Count -eq 0) {
$objTextBox1.BackColor = "Red";
$statusBar1.Text = "Couldn't find user!"
$objForm.Dispose()
}
else{$objTextBox1.BackColor = "Green"
search_PC}
}
function search_PC
{
$Client = $PC
if (#(Get-ADComputer -Filter {DNSHostName -eq $Client}).Count -eq 0) {
$objTextBox2.BackColor = "Red";
$statusBar1.Text = "Couldn't find PC!"
$objForm.Dispose()
}
else{$objTextBox2.BackColor = "Green"
createFile}
}
$objForm.ShowDialog() #Showing Form and elements
Screenshot of the form:
This line is your problem:
$SubmitButton.DialogResult = "OK"
It should be:
$SubmitButton.DialogResult = [System.Windows.Forms.DialogResult]::None
Or just be removed.
DialogResult
There is a script on powershell, that creates and removes vpn connection from the user.
The script is a simple form with two buttons "Create" and "Delete", and the output textbox.
If i run a script and click create, the connection is created. But if not closing the form, press delete, the connection is not removed. If i reopen the form, then everything works and connection delete
What could be the problem?
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Windows.Forms.Application]::EnableVisualStyles()
#################Main Form#################
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(552,654)
$form.MaximizeBox = $false
$Form.StartPosition = "CenterScreen"
$Form.FormBorderStyle = 'Fixed3D'
$Form.Text = "VPN create"
##########Constants and Variables##########
$IpAddress = #("172.17.0.0/16", "192.168.197.0/24", "192.168.196.0/24")
$vpnConnection = Get-VpnConnection -AllUserConnection
#########Start functions############
function CreateVPN {
if ($vpnConnection.Name -eq "ConWork") {
$outputBox.Text = "connection is already there"
} else {
Add-VpnConnection -Name "ConWork" -ServerAddress "xxx.xxx.xxx.xxx" -TunnelType IKEv2 -EncryptionLevel Required -AuthenticationMethod Eap -SplitTunneling -RememberCredential -AllUserConnection | Out-String
$outputBox.Text += ("Connection created")
$outputBox.Text += "`r`n"
$outputBox.Text += "Routes added"
foreach ($ip in $IpAddress) {
$outputBox.Text += Add-VpnConnectionRoute -ConnectionName "ConWork" -DestinationPrefix $ip -PassThru | Out-String
}
}
}
function RemoveVPN {
if ($vpnConnection.Name -eq "ConWork") {
$outputBox.Text += ("Routes delete")
foreach ($ip in $IpAddress) {
$outputBox.Text += Remove-VpnConnectionRoute -ConnectionName "ConWork" -DestinationPrefix $ip -PassThru | Out-String
}
$outputBox.Text += ("Connection delete")
$outputBox.Text += Remove-VpnConnection -Name "ConWork" -Force -PassThru -AllUserConnection | Out-String
} else {
$outputBox.text = "No such connection"
}
}
###########end functions################
############Start text fields###########
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(206,23)
$outputBox.Size = New-Object System.Drawing.Size(318,578)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$outputBox.font = "lucida console"
$Form.Controls.Add($outputBox)
###############end text fields################
##############Start buttons################
$CreateTun = New-Object System.Windows.Forms.Button
$CreateTun.Location = New-Object System.Drawing.Size(42,23)
$CreateTun.Size = New-Object System.Drawing.Size(89,43)
$CreateTun.Text = "Create"
$CreateTun.Add_Click({CreateVPN})
$Form.Controls.Add($CreateTun)
$Removetun = New-Object System.Windows.Forms.Button
$Removetun.Location = New-Object System.Drawing.Size(42,90)
$Removetun.Size = New-Object System.Drawing.Size(89,43)
$Removetun.Text = "Delete"
$Removetun.Add_Click({RemoveVPN})
$Form.Controls.Add($Removetun)
############################################## end buttons
#$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()
Your problem is that you are checking for VPN connection only once, when the script is started:
$vpnConnection = Get-VpnConnection -AllUserConnection
After that you are reusing this variable to in your RemoveVPN function. It will never find any new connections. To make it work, just move the line from above inside your RemoveVPN function