powershell script.exe is disappearing - powershell

I have some ps script which is runs OK via PowerShell ISE env.
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Data Entry Form"
$objForm.Size = New-Object System.Drawing.Size(600,400)
$objForm.StartPosition = "CenterScreen"
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(50,50)
$objTextBox.Size = New-Object System.Drawing.Size(150,20)
$findLabel = New-Object System.Windows.Forms.Label
$findLabel.Location = New-Object System.Drawing.Size(50,100)
$findLabel.Size = New-Object System.Drawing.Size(300,20)
$findLabel.Text = "Nađi:"
$findBox = New-Object System.Windows.Forms.TextBox
$findBox.Location = New-Object System.Drawing.Size(50,120)
$findBox.Size = New-Object System.Drawing.Size(260,20)
$replaceLabel = New-Object System.Windows.Forms.Label
$replaceLabel.Location = New-Object System.Drawing.Size(50,180)
$replaceLabel.Size = New-Object System.Drawing.Size(300,20)
$replaceLabel.Text = "Zameni sa:"
$replaceBox = New-Object System.Windows.Forms.TextBox
$replaceBox.Location = New-Object System.Drawing.Size(50,200)
$replaceBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($startButton)
$objForm.Controls.Add($findBox)
$objForm.Controls.Add($replaceBox)
$objForm.Controls.Add($objTextBox)
$objForm.Controls.Add($beginScriptButton)
$objForm.Controls.Add($findLabel)
$objForm.Controls.Add($replaceLabel)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
$startButton = New-Object System.Windows.Forms.Button
$startButton.Location = New-Object System.Drawing.Size(220,50)
$startButton.Size = New-Object System.Drawing.Size(75,23)
$startButton.Text = "Browse!"
$startButton.Add_Click({
$browser = New-Object System.Windows.Forms.FolderBrowserDialog
$browser.Location = New-Object System.Drawing.Size(60,60)
$null = $browser.ShowDialog()
$path = $browser.SelectedPath
$objTextBox.Text = $path
})
$beginScriptButton = New-Object System.Windows.Forms.Button
$beginScriptButton.Location = New-Object System.Drawing.Size(350,130)
$beginScriptButton.Size = New-Object System.Drawing.Size(350,180)
$beginScriptButton.Text = "Begin"
$beginScriptButton.Add_Click({
$a = $objTextBox.Text
if(($a) -and ($findBox.Text) -and ($replaceBox.Text)){
$objWord = New-Object -comobject Word.Application
$objWord.Visible = $false
$list = Get-ChildItem "c:\users\stefan\test\*.*" -Include *.doc*
foreach($item in $list){
$objDoc = $objWord.Documents.Open($item.FullName,$true)
$objSelection = $objWord.Selection
$wdFindContinue = 1
$FindText = $findBox.Text
$MatchCase = $false
$MatchWholeWord = $true
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdReplaceNone = 0
$ReplaceWith = $replaceBox.Text
$wdFindContinue = 1
$ReplaceAll = 2
$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith,$ReplaceAll)
$objDoc.Save()
$objDoc.Close()
}
$objWord.Quit()
[System.Windows.Forms.MessageBox]::Show("Uspešno ste izvršili izmenu!")
}
else{
[System.Windows.Forms.MessageBox]::Show("Please fill in all fields.")
}
})
Then, I compile it via PowerGUI as .exe
And I run it, first, it opens a cmd and after a second it disappear, I can't even see my powershell form that I've created through the code.
I've tried different options through PowerGui (I want to not be displayed a cmd window, just my form). Do you know some way how to compile it to .exe and to see only form and logic behind it?
Thanks!

Compiling the script as an exe in Powershell runs it in a new instance, where you'll need to load the form components. Try adding this to the start of your script:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

Related

I want to monitor the date and time of a file every 30 seconds

I want to monitor the date and time of a file. I wrote the code that do the job as I want but I can't reposition the gui window. I tried all I could find like "start-job" or create a new runspace but I don't get any results in richtextbox. Any suggestion is welcome.
$targetFile = "full path"
# Function - Add Text to RichTextBox
function Add-RichTextBox{
[CmdletBinding()]
param ($text)
#$richtextbox_output.Text += "`tCOMPUTERNAME: $ComputerName`n"
$richtext.Text += "$text"
$richtext.Text += "`n"
}
# Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Monitor script"
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$Font = New-Object System.Drawing.Font("Tahoma",11)
$Form.Font = $Font
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,40)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = (Get-Date).ToString()
$form.Controls.Add($label)
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Point(150,220)
$StartButton.Size = New-Object System.Drawing.Size(100,33)
$StartButton.Text = 'Start'
#$StartButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $StartButton
$form.Controls.Add($StartButton)
$StartButton.Add_click({
while($true){
$lastdate = Get-ChildItem $targetFile
$Date = $lastdate.LastAccessTime.ToString()
Add-RichTextBox "$date"
$richtext.SelectionStart = $richtext.TextLength
$richText.ScrollToCaret()
#$richtext.refresh()
#$form.refresh()
Start-sleep 30
}
})
## the Rich text box
$richtext = new-object System.Windows.Forms.RichTextBox
$richtext.Location = New-Object System.Drawing.Point(20,60)
$richtext.multiline = $true
$richtext.Name = "Results"
$richtext.text = "Results:`n"
$richtext.scrollbars = "Both"
$richtext.Height = 120
$richtext.width = 350
$richtext.font = new-object system.drawing.font "Lucida Console",10
$Form.controls.add($richtext)
$Form.Add_Shown({$Form.Activate()})
$form.ShowDialog()
Continuing from my comment to use a Timer on your form (if you absolutely do not want a FileSystemWatcher), here's how you can do that:
$targetFile = "D:\Test\blah.txt"
$lastAccessed = (Get-Date) # a variable to keep track of the last LastAccessTime of the file
# Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Monitor script"
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$Font = New-Object System.Drawing.Font("Tahoma",11)
$form.Font = $Font
# Label
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,40)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = (Get-Date).ToString()
$form.Controls.Add($label)
# Button
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Point(150,200)
$StartButton.Size = New-Object System.Drawing.Size(100,33)
$StartButton.Text = 'Start'
$form.Controls.Add($StartButton)
$StartButton.Add_click({
$timer.Enabled = $true
$timer.Start()
})
# RichTextBox
$richtext = New-Object System.Windows.Forms.RichTextBox
$richtext.Location = New-Object System.Drawing.Point(20,60)
$richtext.Multiline = $true
$richtext.Name = "Results"
$richtext.Text = "Results:`r`n"
$richtext.ScrollBars = "Both"
$richtext.Height = 120
$richtext.Width = 350
$richtext.Font = New-Object System.Drawing.Font "Lucida Console",10
$form.Controls.Add($richtext)
# Timer
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 30000 # 30 seconds
$timer.Enabled = $false # disabled at first
$timer.Add_Tick({
$file = Get-Item -Path $targetFile -ErrorAction SilentlyContinue
# if we can find the file and its last AccessedTime is not
# the same as we already stored in variable $lastAccessed
# use script-scoping here, so $script:lastAccessed instead of $lastAccessed
if ($file -and $file.LastAccessTime -gt $script:lastAccessed) {
$richtext.AppendText("$($file.LastAccessTime.ToString())`r`n")
$script:lastAccessed = $file.LastAccessTime # remember this new datetime
}
})
$form.ShowDialog()
# Important: Clean up
$timer.Stop()
$timer.Dispose()
$richtext.Dispose()
$form.Dispose()

PowerShell ISE GUI how to live monitor and changed the jpg based on variable

I would like to ask how to refresh and changed the jpg below GUI from "Offline" to "Online" based on the live monitoring of specific folder and filenames. For example, I am monitoring a folder for any changes, if in the folder a filename exists with specific string, then it will shows in GUI as "Online" and when the folder doesn't contain the file with specific string, then it will shows as "Offline" in the GUI.
Below is the code that I have.
####################################### Form settings ##############################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$Form.Anchor = "Top,Bottom,Left,Right"
$Form.Size = New-Object System.Drawing.Size(1920,1600)
$Form.AutoScale = $True
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.BackgroundImageLayout = "Zoom"
$Form.MinimizeBox = $True
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Auto"
$Form.AutoSizeMode = New-Object System.Windows.Forms.AutoSizeMode
$Form.SizeGripStyle = "Show"
$Form.BackColor = "LightGray"
$Form.Icon = $Icon
$TestStatus16 = Test-Path -Path C:\Desktop\Newfolder\P16*
$Online = [System.Drawing.Image]::FromFile("C:\Online.jpg")
$Offline = [System.Drawing.Image]::FromFile("C:\Offline.jpg")
$Photo16 = New-Object System.Windows.Forms.Button
$Photo16.Location = New-Object System.Drawing.Point(830,250)
$Photo16.Size = New-Object System.Drawing.Size(200,50)
$Photo16.Font = New-Object System.Drawing.Font ("HelveticaNeueLTStd-Roman",11,[System.Drawing.FontStyle]::Bold)
$Photo16.Text = "Photo # 16"
$Photo16.BackColor = "SandyBrown"
$Photo16.ForeColor = "Black"
$Form.Controls.Add($Photo16)
$StatusPhoto16 = New-Object System.Windows.Forms.PictureBox
$StatusPhoto16.Location = New-Object System.Drawing.Size(1050,252)
$StatusPhoto16.Size = New-Object System.Drawing.Size(150,45)
$StatusPhoto16.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::StretchImage
$StatusPhoto16.BackColor = "White"
$Form.Controls.Add($StatusPhoto16)
if($TestStatus16 -eq $True){$StatusPhoto16.Image=$Online}else{$StatusPhoto16.Image=$Offline}
$Timer16 = New-Object System.Windows.Forms.Timer
$Timer16.Interval = 3000
$Timer16.Add_Tick({Status16 $StatusPhoto16})
$Timer16.Enabled = $False
$Timer16.Start()
$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()
Kindly help improving the above code.
You're missing is what I'm assuming it to be the function call for your Test-Path.
What's needed is for it to be defined, the object ($StatusPhoto16) be passed to it, and the update of the actual image based on your Test-Path.
####################################### Form settings ##############################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$Form.Anchor = "Top,Bottom,Left,Right"
$Form.Size = New-Object System.Drawing.Size(1920,1600)
$Form.AutoScale = $True
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.BackgroundImageLayout = "Zoom"
$Form.MinimizeBox = $True
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Auto"
$Form.AutoSizeMode = New-Object System.Windows.Forms.AutoSizeMode
$Form.SizeGripStyle = "Show"
$Form.BackColor = "LightGray"
$Form.Icon = $Icon
$Online = [System.Drawing.Image]::FromFile("C:\Online.jpg")
$Offline = [System.Drawing.Image]::FromFile("C:\Offline.jpg")
$Photo16 = New-Object System.Windows.Forms.Button
$Photo16.Location = New-Object System.Drawing.Point(830,250)
$Photo16.Size = New-Object System.Drawing.Size(200,50)
$Photo16.Font = New-Object System.Drawing.Font ("HelveticaNeueLTStd-Roman",11,[System.Drawing.FontStyle]::Bold)
$Photo16.Text = "Photo # 16"
$Photo16.BackColor = "SandyBrown"
$Photo16.ForeColor = "Black"
$Form.Controls.Add($Photo16)
function status16 ($StatusPhoto16) {
if (Test-Path -Path 'C:\Desktop\Newfolder\P16*')
{
$StatusPhoto16.Image = $Online
}
else
{
$StatusPhoto16.Image = $Offline
}
}
$StatusPhoto16 = New-Object System.Windows.Forms.PictureBox
$StatusPhoto16.Location = New-Object System.Drawing.Size(1050,252)
$StatusPhoto16.Size = New-Object System.Drawing.Size(150,45)
$StatusPhoto16.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::StretchImage
$StatusPhoto16.BackColor = "White"
$Form.Controls.Add($StatusPhoto16)
$Timer16 = New-Object System.Windows.Forms.Timer
$Timer16.Interval = 3000
$Timer16.Add_Tick({status16 $StatusPhoto16})
$Timer16.Enabled = $False
$Timer16.Start()
$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()

Powershell GUI tabbed layout script placement

I wrote six small gui scripts that I'd like to place in a single file, for the sake of converting said file into rxecutable with ps2exe.
I've found a script ,here on stack that is perfect for what I want. Unfortunatelly I cann't find any info on script placement within tabs and MS documentation leads me to ISE tabs, which is not helpfull.
Say I'd like to place this
Add-Type -AssemblyName PresentationFramework
$button_click = {
$folder = $textBox1.Text;
$pytanie = [System.Windows.MessageBox]::Show('Czy chcesz usunac folder?', '', '4');
If($pytanie -eq 'Yes')
{Remove-Item –path $folder –recurse -Force};
$test = Test-Path $folder;
if ($test -eq $false){[System.Windows.MessageBox]::Show('Folder Usuniety', '', '0')}}
$label2 = New-Object System.Windows.Forms.Label
$label2.AutoSize = $True
$label2.Text = ("Scieżka")
$label2.Location = New-Object System.Drawing.Point (10,30)
$label2.Size = New-Object System.Drawing.Size (25,70)
$label2.Font = [System.Drawing.Font]::new("Arial", 10, [System.Drawing.FontStyle]::Bold)
$textBox1 = New-Object System.Windows.Forms.TextBox
$textBox1.Location = New-Object System.Drawing.Point(10,70) ### Location of the text box
$textBox1.Size = New-Object System.Drawing.Size(200,50) ### Size of the text box
$textBox1.Multiline = $false ### Allows multiple lines of data
$textBox1.Font = New-Object System.Drawing.Font("Consolas",10,[System.Drawing.FontStyle]::Regular)
$textBox1.ReadOnly=$false
$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Point(10,120)
$button.Size = New-Object System.Drawing.Size (200,30)
$button.Text = "Usun Folder"
$button.Add_Click($button_click)
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Mapowanie' ### Text to be displayed in the title
$form.Size = New-Object System.Drawing.Size(240,200) ### Size of the window
$form.StartPosition = 'Manual'
$form.Location = '10,10'
$form.Topmost = $true ### Optional - Opens on top of other windows
$form.Controls.AddRange(#($textBox1,$button, $label2))
$form.ShowDialog()
within a tab. How to do it?
I think that it the
$Tab1.Controls.Add($button)
You are looking for.
For example
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$ApplicationForm = New-Object System.Windows.Forms.Form
$ApplicationForm.StartPosition = "CenterScreen"
$ApplicationForm.Topmost = $false
$ApplicationForm.Size = "800,600"
$FormTabControl = New-object System.Windows.Forms.TabControl
$FormTabControl.Size = "755,475"
$FormTabControl.Location = "25,75"
$ApplicationForm.Controls.Add($FormTabControl)
$Tab1 = New-object System.Windows.Forms.Tabpage
$Tab1.DataBindings.DefaultDataSourceUpdateMode = 0
$Tab1.UseVisualStyleBackColor = $True
$Tab1.Name = "Tab1"
$Tab1.Text = "Tab1”
$FormTabControl.Controls.Add($Tab1)
$textBox1 = New-Object System.Windows.Forms.TextBox
$textBox1.Location = New-Object System.Drawing.Point(10,70) ### Location of the text box
$textBox1.Size = New-Object System.Drawing.Size(200,50) ### Size of the text box
$textBox1.Multiline = $false ### Allows multiple lines of data
$textBox1.Font = New-Object System.Drawing.Font("Consolas",10,[System.Drawing.FontStyle]::Regular)
$textBox1.ReadOnly=$false
$Tab1.Controls.Add($textBox1)
$Tab2 = New-object System.Windows.Forms.Tabpage
$Tab2.DataBindings.DefaultDataSourceUpdateMode = 0
$Tab2.UseVisualStyleBackColor = $True
$Tab2.Name = "Tab2"
$Tab2.Text = "Tab2”
$FormTabControl.Controls.Add($Tab2)
$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Point(10,120)
$button.Size = New-Object System.Drawing.Size (200,30)
$button.Text = "Usun Folder"
$button.Add_Click($button_click)
$Tab2.Controls.Add($button)
# Initlize the form
$ApplicationForm.Add_Shown({$ApplicationForm.Activate()})
[void] $ApplicationForm.ShowDialog()

Prevent Powershell GUI from closing

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

Problems with Powershell and imageboxes

Trying to create a simple GUI Script using powershell to ping a TP ip address and display it with a simple Green/Red Image depending whether its on/off.
But for some reason, when hitting the Close button, I cant seem to remove the green/red dots.
The File contains:
Arial,172.0.0.0
Bodoni,172.0.0.0
Caslon,172.0.0.1
Script:
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form
$Form.text = "Hardware Checks"
$Form.Size = New-Object System.Drawing.Size(600,600)
$arrayTPs = Get-Content -path "C:\Activity monitor\TPs.txt"
#Image Locations
$filered = (get-item 'C:\Activity monitor\red1.png')
$filegreen = (get-item 'C:\Activity monitor\green1.png')
$imgred = [System.Drawing.Image]::Fromfile($filered)
$imggreen = [System.Drawing.Image]::Fromfile($filegreen)
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(10,200)
$outputBox.Size = New-Object System.Drawing.Size(565,200)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(450,30)
$Button.Size = New-Object System.Drawing.Size(75,75)
$Button.Text = "Check"
$Button.Add_Click({
$Form.controls.Remove($outputBox)
$Form.controls.refresh()
foreach($room in $arrayTPs){
#Get Name of room from array
$roomAlone = $room -split ","
$roomAlone[0]
$pictureBoxRed = new-object Windows.Forms.PictureBox
$pictureBoxGreen = new-object Windows.Forms.PictureBox
#Add room name to textbox
if($roomAlone[1] -eq "172.0.0.0"){
$pictureBoxGreen.Width = 10
$pictureBoxGreen.Height = 10
$pictureBoxGreen.Image = $imggreen
$pictureBoxGreen.Location = New-Object System.Drawing.Point(90,$counterpic)
$outputBox.controls.add($pictureBoxGreen)
$Form.Controls.Add($outputBox)}
else{
$pictureBoxRed.Width = 10
$pictureBoxRed.Height = 10
$pictureBoxRed.Image = $imgred
$pictureBoxRed.Location = New-Object System.Drawing.Point(90,$counterpic)
$outputBox.controls.add($pictureBoxRed)
$Form.Controls.Add($outputBox)
}
$counterpic = $Counterpic + 20
$counter = $Counter + 20
}})
$Form.Controls.Add($Button)
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Size(450,520)
$cancelButton.Size = New-Object System.Drawing.Size(75,25)
$cancelButton.Text = "Close"
$cancelButton.Add_Click({
$outputBox.controls.Remove($pictureBoxRed)
$outputBox.controls.Remove($pictureBoxGreen)
$outputBox.Controls.Equals($null)
$outputBox.controls.update()
$Form.Refresh()
foreach($room in $arrayTPs){
#Get Name of room from array
$roomAlone = $room -split ","
$roomAlone[0]
$pictureBoxRed = new-object Windows.Forms.PictureBox
$pictureBoxGreen = new-object Windows.Forms.PictureBox
}})
$Form.Controls.Add($cancelButton)
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()