replace text with a textbox input using variable - powershell

In my script I have a textbox- the user inserts text in it and than I want to change the text in a file (which the script creates earlier) to what the user inserted in the textbox.
The problem: it does deletes the part I wanted to be changed in the file- but it doesn`t write the text of the user instead. I also tried to locate the variable in the if loop- and it did changed the text like i wanted, but when I run the script again it wrote the old text in the disabled textbox.
my script is kinda long so I wont post all of it, but here are the importent parts. Thanks for the help!
#This creates a checkbox called dsp.z
$objDspCheckbox = New-Object System.Windows.Forms.Checkbox
$objDspCheckbox.Location = New-Object System.Drawing.Size(20,40)
$objDspCheckbox.Size = New-Object System.Drawing.Size(150,20)
$objDspCheckbox.Text = "dsp.z"
$objDspCheckbox.TabIndex = 0
$objForm.Controls.Add($objDspCheckbox)
#This creates the TextBox1 and put it on disable
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(450,40)
$objTextBox1.Size = New-Object System.Drawing.Size(140,150)
$objTextBox1.TabIndex = 3
$objTextBox1.text = $text1
$objTextBox1.Enabled = $false
$objForm.Controls.Add($objTextBox1)
#This creates a checkbox for textbox1
$objDsp2Checkbox = New-Object System.Windows.Forms.Checkbox
$objDsp2Checkbox.Location = New-Object System.Drawing.Size(430,40)
$objDsp2Checkbox.Size = New-Object System.Drawing.Size(150,20)
$objDsp2Checkbox.TabIndex = 0
$objForm.Controls.Add($objDsp2Checkbox)
#Enables the textbox when user check the box:
#textbox1
$objDsp2Checkbox_OnClick = {
if ($objDsp2Checkbox.Checked -eq $true)
{
$objTextBox1.Enabled = $true
}
elseif ($objDsp2Checkbox.Checked -eq $false)
{
$objTextBox1.Enabled = $false
}
}
$objDsp2Checkbox.Add_Click($objDsp2Checkbox_OnClick)
#variables
$text1=$objTextBox1.Text
#This creates the ok and cancle buttons:
#ok Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(220,155)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click(
{
if (($objDspCheckbox.Checked -eq $true) -and ($objDsp2Checkbox.Checked -eq $true))
{
New-Item $path -itemtype file -name Dsp.json -value "old" ;((Get-Content "c:\users\$env:USERNAME\documents\Json\dsp.json") -replace 'old', $text1 | out-file "c:\users\$env:USERNAME\documents\Json\dsp.json") ;$objForm.close()
}

Try to Change This Line (specifly the $text1) to $objTextBox1.Text :
New-Item $path -itemtype file -name Dsp.json -value "old" ;
((Get-Content "c:\users\$env:USERNAME\documents\Json\dsp.json") -replace 'old', $text1 |
Out-file "c:\users\$env:USERNAME\documents\Json\dsp.json") ;$objForm.close()
To:
New-Item $path -itemtype file -name Dsp.json -value "old" ;
((Get-Content "c:\users\$env:USERNAME\documents\Json\dsp.json") -replace 'old', $objTextBox1.Text |
Out-file "c:\users\$env:USERNAME\documents\Json\dsp.json") ;$objForm.close()
I'm not sure if it's the case but if you just need to save the textbox text to file there's an easier approach :
$objTextBox1.Text | Out-file "c:\users\$env:USERNAME\documents\Json\dsp.json")

Related

copy file in a gui with checkboxes

i'm creating a gui in powershell for copying files. first i add a file with a button, next i choose the folder where to copy and then i want to copy. unfortunately the script says the file path is empty. how can i solve this problem? Furthermore, i want to add 2 functions.
a warning if no checkbox is marked
a text field next to the choose button where i can see the path from the file i want to copy
$PSDefaultParameterValues['*:Encoding'] = 'ascii'
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#create form
$form = New-Object System.Windows.Forms.Form
$form.Width = 500
$form.Height = 300
$form.MaximizeBox = $false
#choose file button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(10,10)
$Button.Size = New-Object System.Drawing.Size(150,50)
$Button.Text = "choose file"
$Button.Add_Click({
Function Get-FileName($initialDirectory) {
[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = “All files (*.*)| *.*”
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
$file = Get-FileName -initialDirectory “c:”
})
$form.Controls.Add($Button)
#create checkbox1
$checkBox = New-Object System.Windows.Forms.CheckBox
$checkBox.Location = New-Object System.Drawing.Point (10, 100)
$checkBox.Size = New-Object System.Drawing.Size(350,30)
$checkBox.Text = "folder 1"
$form.Controls.Add($checkBox)
#create checkbox2
$checkBox2 = New-Object System.Windows.Forms.CheckBox
$checkBox2.Location = New-Object System.Drawing.Point (10, 150)
$checkBox2.Size = New-Object System.Drawing.Size(350,30)
$checkBox2.Text = "folder 2"
$form.Controls.Add($checkBox2)
#copy file button
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Location = New-Object System.Drawing.Size(10,200)
$Button2.Size = New-Object System.Drawing.Size(150,50)
$Button2.Text = "copy file"
$Button2.Add_Click({
#checkbox1 action
if ($checkBox.Checked -eq $true)
{
copy-item -Path $file -Destination "C:\folder 1"
}
#checkbox2 action
if ($checkBox2.Checked -eq $true)
{
copy-item -Path $file -Destination "C:\folder 2"
}
})
$form.Controls.Add($Button2)
#end
[void]$form.ShowDialog()
There are plenty of improvements to be suggested but let's focus on your questions:
The problem is that the scope of your $file variable is local to the function Get-Filename.
So when accessed from outside of the function, it is always null.
As stated in the comments, the minimum modification for your script to work is the change the following line (I would also suggest to declare it initially outside of the function, at global level for sake of clarity):
# From this
$file = Get-FileName -initialDirectory "c:"
# To this
$Global:file = Get-FileName -initialDirectory "c:"
To add a textbox with the choosen filename, proceed as for the other controls:
#Text box with choosen file name
$txtBox = New-Object System.Windows.Forms.TextBox
$txtBox.Location = New-Object System.Drawing.Point (180, 20)
$txtBox.Size = New-Object System.Drawing.Size(280,20)
$form.Controls.Add($txtBox)
And to update the text, add the following line after setting the $Global:file variable:
$Global:file = Get-FileName -initialDirectory "c:"
$txtBox.Text = $Global:file
Finally, a message can be displayed if you add the following code to your $Button2.Add_Click code:
#nothing checked
if(($checkBox.Checked -eq $false) -and ($checkBox.Checked -eq $false)) {
[System.Windows.Forms.Messagebox]::Show("No CheckBox checked")
}

Loop Multiple Values In Variable Output To csv Powershell

I created a script where a dialogue box pops up and the value you enter goes into foreach. I didn't know how to take a single value created in a running script and process it. It worked, although I knew it wasn't the right way to do it.. Now I've created a loop to prompt again and the goal is to append each value into a csv. My problem is now the original variable value is overwritten by the next value put into the prompt before writing out to a csv. How can I build each entry into the looping dialogue box and create the csv?
You can see in the powershell script that I create $x from the value input to the dialogue box, then I cycle the script into a function that repeats the dialogue prompt. When it does that it overwrites the first value of $x. I'm trying to figure out how to build many values before writing the all to the csv.
This script is to have a user enter a group, check it against Active Directory, and then generate a CSV.
...Update## I was able to resolve it. I'm removing the original test code and putting the final product. The following script creates a form which asks for an object in Active Directory. It checks active directory then outputs to a spreadsheet, and asks again until canceled. Building the variable repeatedly.
function ProcessOut ($x , $group) {
$result = #()
Foreach ($Line in $x){
$GroupName = "domain.local\" + $group
$OutList = New-Object System.Object
$OutList | Add-Member -type NoteProperty -Name "DisplayPath_GroupName" -value $GroupName
$OutList | Add-Member -type NoteProperty -Name "RuleName" -value "AutomaticApproval"
$OutList | Add-Member -type NoteProperty -Name "RuleClauses" -value '
$result+= $OutList
}
#Output to csv
$outputfilepath = 'c:\users\technician\desktop\'
$outputfilename = $outputfilepath + 'FinalFile.csv'
$result | export-csv $outputfilename -Append -encoding unicode -NoTypeInformation
}
function PromptInput {
add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Group Auto-Approval Setup'
$form.Size = New-Object System.Drawing.Size(500,230)
$form.StartPosition = 'CenterScreen'
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(170,100)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(260,100)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(200,40)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Enter a group name:"
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(100,65)
$textBox.Size = New-Object System.Drawing.Size(300,120)
$form.Controls.Add($textBox)
$form.Topmost = $true
$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()
if ($result -eq 'Cancel'){
Exit
}
if ($result -eq [System.Windows.Forms.DialogResult]::OK){
$x = $textBox.Text
}
return $x
}
$continue = $true
while($continue){
$input = PromptInput
Add-Type -AssemblyName microsoft.visualbasic
$searcher = [ADSISearcher]"(SAMAccountName=$input)"
$result = $searcher.FindOne()
if($result){
ProcessOut $result $input
$additional = [System.Windows.Forms.MessageBox]::Show("Would you like to enter another group?" , "Status" , 4)
if ($additional -eq "NO"){
Exit
}
} else{
[System.Windows.Forms.MessageBox]::Show("Group name not found - Please enter a valid group name")
}
}
Use an ArrayList or an Array to build things up. Create this at the Global level so that it is accessible within the code. Example:
# Create an empty array outside of the loop
$myArray = #()
# Get all running processes
$processes = Get-Process
# for each process in the list of processes we are going to do something
foreach($process in $processes)
{
# Create a Pipe separated string
$myString = $process.Name + "|" + $process.Id
# Add the process name to my array.
$myArray += $myString
}
# Export the array to a CSV file
$myArray | Export-Csv -Path c:\myfile.csv
Or if you don't like arrays (I don't for many reasons...) Try a List...
Replace the 2nd line with:
$myArray = New-Object System.Collections.ArrayList
Replacing the 14th line with
$myArray.Add($myString) > $null
Notice that I am piping the output to null. This is to stop it echoing back which may / maynot be useful to you.
Hope this helps.

Powershell Codewrap for repeat option and bug with form

I got a script which is handling some things. I know a lot say I should get more short scripts which are working. But there are many people which can't handle many files or scripts and want 1 which can do all, and I can't tell 600 people which script does what. I need a kind of assembling at least of a few.
I wanted to make a workaround for the canceld options. The easiest way is to wrap all the code in a do {} while () for sure. But are there any options where I can repeat a single option? Something like when it asks do you really want to cancel.
And a real annoying bug I can't fix is that after every single action the start form blops up again. I tried out diffrent ways to debug with a counter but it didn't count up and also I tried to put the function assembling at a other place didn't fix it as well. Don't know why it happens.
Code for repro
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Set-PSDebug -Strict #Errorcall if a variable isnt declared
#Function Assembling
function Saveat()
{
#working
$Saveat = New-Object -Typename System.Windows.Forms.SaveFileDialog
$Saveat.filter = "CSV (*.csv)| *.csv"
#IF selection is canceld
$result = $form.ShowDialog()
[void]$Saveat.ShowDialog()
return $Saveat.FileName
}
function Compare($location1, $location2)
{
#work in progress
$CSV1 = Import-Csv -Path $location1 -UseCulture
$CSV2 = Import-Csv -Path $location2 -UseCulture
$Compared = Compare-Object -ReferenceObject $CSV1 -DifferenceObject $CSV2 |
select -ExpandProperty inputObject |
sort
[void] $CSV1
[void] $CSV2
return $Compared
}
function whichcsv()
{
#working
$location = New-Object System.Windows.Forms.OpenFileDialog
$location.Filter = "CSV (*.csv)| *.csv"
$result = $form.ShowDialog()
[void]$location.ShowDialog()
return $location.FileName
}
#Select which option Form
#region Initiate Form **This Form Blops up after every user action**
$form = New-Object System.Windows.Forms.Form
$form.Text = "CSV Liste"
$form.Size = New-Object System.Drawing.Size(300,300)
$form.StartPosition = "CenterScreen"
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,195)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,195)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = "Welche CSV Liste soll geladen werden:"
$form.Controls.Add($label)
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 150
[void] $listBox.Items.Add("List Filter")
[void] $listBox.Items.Add("ADComputer")
[void] $listBox.Items.Add("AS400 Personal Not implemented yet")
[void] $listBox.Items.Add("ADBenutzer Not implemented yet")
#endregion
$form.Controls.Add($listBox)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
#Choosed Option
$x = $listBox.SelectedItem
switch ($x)
{
#Option 1 working
"List Filter"
{
#Select path of the CSV
$csvpath = whichcsv
#IF selection is canceld
if ($csvpath -eq "")
{
Write-Host "Operation Canceld"
}
else
{
#CSV Import and Filter set
$CSV = Import-Csv -Path $csvpath -UseCulture
$Filter = Read-Host "Please enter columname. Leave clear for cancel"
if ($Filter -eq "")
{
Write-Host "Operation canceld"
}
else
{
$y = $CSV | Select $Filter
Write-Host "CSV Successfull Imported and Filter set"
}
$SDestination = Saveat
if ($SDestination -eq "")
{
Write-Host "Operation Canceld"
}
else
{
Write-Host "Process started"
foreach ($y1 in $y)
{
New-Object PSObject -Property #{Inventarnummer=$y1.$Filter} | Export-Csv $SDestination -NoTypeInformation -Append
}
Write-Host "Process finished"
}
}
}
#Option 2 working
"ADComputer"
{
#Select path of the CSV
$csvpath = whichcsv
#IF selection is canceld
if ($csvpath -eq "")
{
Write-Host "Operation Canceld"
}
else
{
#CSV Import with filter
$CSV = Import-Csv -Path $csvpath -Delimiter ','
$Filter = Read-Host "Please enter columname. Leave clear for cancel"
if ($Filter -eq "")
{
Write-Host "Operation canceld"
}
else
{
$y = $CSV | Select $Filter
Write-Host "CSV Successfull Imported and Filter set"
}
#Path selection
$Saveworking = Saveat
$SaveFailed = Saveat
if($Saveworking -eq "")
{
Write-Host "Operation canceld"
}
elseif ($SaveFailed -eq "")
{
Write-Host "Operation canceld"
}
else
{
#Progress
Write-Host "Process Start"
foreach($n in $y)
{
try
{
$Computer = [system.net.dns]::resolve($n.$Filter) | Select HostName,AddressList
$IP = ($Computer.AddressList).IPAddressToString
Write-Host $n.$Filter $IP
New-Object PSObject -Property #{IPAddress=$IP; Name=$n.$Filter} | Export-Csv $Saveworking -NoTypeInformation -Append
}
catch
{
Write-Host "$($n.$Filter) is unreachable."
New-Object PSObject -Property #{Name=$n.$Filter} | Export-Csv $SaveFailed -NoTypeInformation -Append
}
}
Write-Host "Process successfull completed"
}
}
}
#Option 3 Not implemented yet
"AS400 Personal Not implemented yet"
{
Write-Host "Not implemented yet"
}
#Option 4 not implemented yet
"ADBenutzer Not implemented yet"
{
Write-Host "Not implemented yet"
}
}
}
else
{
Write-Host "Operation Canceld"
}
I guess you need to work with form events rather than .DialogResult.
For the Cancel button you would probably do something like: $CancelButton.Add_Click({[Void]$Form.Window.Close()})
For the OK button you would probably want to put the majority of your OK task in a function and invoke it from a similar event:
Function Task {
#Choosed Option
$x = $listBox.SelectedItem
switch ($x)
{
#Option 1 working
"List Filter"
{
#Select path of the CSV
$csvpath = whichcsv
...
$OkButton.Add_Click({Task})
(And close the dialog ([Void]$Form.Window.Close()) when the task is completed)

If is not working in If-elseif statement

Im writing a code which asks the user to mark certain files that he wants and then it creates a file and changes it accordingly, just wrote hello for now.
The problem is that it only works in the if section, and not in the else if. I couldn't find an answer online.
Here is my code:
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName ("System.Windows.Forms")
#This creates the path for the Json
New-Item c:\users\$env:USERNAME\documents -ItemType directory -Name Json
#creating the form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Ofir`s script"
$objForm.Size = New-Object System.Drawing.Size(270,200)
$objForm.StartPosition = "CenterScreen"
#creating the label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please check the relevant boxes:"
$objForm.Controls.Add($objLabel)
#This creates a checkbox called dsp.z
$objDspCheckbox = New-Object System.Windows.Forms.Checkbox
$objDspCheckbox.Location = New-Object System.Drawing.Size(10,40)
$objDspCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objDspCheckbox.Text = "dsp.z"
$objDspCheckbox.TabIndex = 0
$objForm.Controls.Add($objDspCheckbox)
#This creates a checkbox called fpga.bin
$objFpgaCheckbox = New-Object System.Windows.Forms.Checkbox
$objFpgaCheckbox.Location = New-Object System.Drawing.Size(10,60)
$objFpgaCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objFpgaCheckbox.Text = "fpga.bin"
$objFpgaCheckbox.TabIndex = 1
$objForm.Controls.Add($objFpgaCheckbox)
#This creates a checkbox called bootrom_uncmp.bin
$objBootCheckbox = New-Object System.Windows.Forms.Checkbox
$objBootCheckbox.Location = New-Object System.Drawing.Size(10,80)
$objBootCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objBootCheckbox.Text = "bootrom_uncmp.bin"
$objBootCheckbox.TabIndex = 2
$objForm.Controls.Add($objBootCheckbox)
#ok Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(40,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({if ($objDspCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello" ;$objForm.close()}
}
)
elseif ($objFpgaCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello2" ;$objForm.close()
}
elseif ($objBootCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello3" ;$objForm.close()
}
$objForm.Controls.Add($OKButton)
#cancle Button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(140,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
#makes the form appear on top of the screen
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
You have a curly-bracket in this line:
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello" ;$objForm.close()}
So change the click handler to:
$OKButton.Add_Click(
{
if ($objDspCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello" ;$objForm.close()
}
elseif ($objFpgaCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello2" ;$objForm.close()
}
elseif ($objBootCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello3" ;$objForm.close()
}
})
This is working fine now with the elseif . I have made few improvements like if the json folder is already existing then it was throwing error . So I am checking on prior that if the folder is already there then do not create or overwrite. Use that same folder and create the Json file under that. If the folder is not present then only create it.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
#This creates the path for the Json and also check if it is already there.
If(!(Test-Path -Path C:\Users\$env:USERNAME\documents\Json))
{
New-Item c:\users\$env:USERNAME\documents -ItemType directory -Name Json
}
#creating the form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Ofir`s script"
$objForm.Size = New-Object System.Drawing.Size(270,200)
$objForm.StartPosition = "CenterScreen"
#creating the label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please check the relevant boxes:"
$objForm.Controls.Add($objLabel)
#This creates a checkbox called dsp.z
$objDspCheckbox = New-Object System.Windows.Forms.Checkbox
$objDspCheckbox.Location = New-Object System.Drawing.Size(10,40)
$objDspCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objDspCheckbox.Text = "dsp.z"
$objDspCheckbox.TabIndex = 0
$objForm.Controls.Add($objDspCheckbox)
#This creates a checkbox called fpga.bin
$objFpgaCheckbox = New-Object System.Windows.Forms.Checkbox
$objFpgaCheckbox.Location = New-Object System.Drawing.Size(10,60)
$objFpgaCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objFpgaCheckbox.Text = "fpga.bin"
$objFpgaCheckbox.TabIndex = 1
$objForm.Controls.Add($objFpgaCheckbox)
#This creates a checkbox called bootrom_uncmp.bin
$objBootCheckbox = New-Object System.Windows.Forms.Checkbox
$objBootCheckbox.Location = New-Object System.Drawing.Size(10,80)
$objBootCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objBootCheckbox.Text = "bootrom_uncmp.bin"
$objBootCheckbox.TabIndex = 2
$objForm.Controls.Add($objBootCheckbox)
#ok Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(40,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click(
{
if($objDspCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello" ;$objForm.close()
}
elseif($objFpgaCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello2" ;$objForm.close()
}
elseif($objBootCheckbox.Checked -eq $true)
{
New-Item c:\users\$env:USERNAME\documents\Json -itemtype file -name file.json -value "Hello3" ;$objForm.close()
}
}
)
$objForm.Controls.Add($OKButton)
#cancle Button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(140,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
#makes the form appear on top of the screen
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

Powershell script works in ISE but not in Run With Powershell

I had develop a script that basically restart a service in a remove server based on a selection.
This selection is done by a form.
The problem is... when I run this using the ISE... the script work totally fine.
When I run this using the RIGHT CLICK / RUN with Powershell
My form doesn't work. The Button that I had created didn't appear...
What can be wrong?
Here is my code:
Function Write-Centered {
Param( [string] $message,
[string] $color = "black")
$offsetvalue = [Math]::Round(([Console]::WindowWidth / 2) + ($message.Length / 2))
Write-Host ("{0,$offsetvalue}" -f $message) -ForegroundColor $color
}
clear
$timestamp=Get-date -format yyyy_MM_dd_hh_mm_ss
$systems = #(
("System 1","Server1","bmc_ctsa_sm_SAP_Instance_2"),
("System 2","Server2","bmc_ctsa_sm_SAP_Instance_6"),
("System 3","Server3","bmc_ctsa_sm_SAP_Instance_6")
)
Write-Centered "Service Restart Tool" "Green"
Write-Centered "Choose the target system you would like to restart" "Green"
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form1 = New-Object System.Windows.Forms.Form
$Form1.ClientSize = New-Object System.Drawing.Size(300, 100)
$form1.topmost = $true
$Form1.Controls.Add($Button)
$Form1.Text = "SSPR Restart Tool"
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Point(150, 25)
$Button.Size = New-Object System.Drawing.Size(120, 25)
$Button.add_Click({
$label.Text = $comboBox1.SelectedItem.ToString()
$Form1.Close()
})
$Button.Text = "Start Process"
$Label = New-Object System.Windows.Forms.Label
$Label.Location = New-Object System.Drawing.Point(10, 10)
$Label.Size = New-Object System.Drawing.Size(300, 15)
$Label.Text = "Please select the system you would like to restart"
$Form1.Controls.Add($Label)
$comboBox1 = New-Object System.Windows.Forms.ComboBox
$comboBox1.Location = New-Object System.Drawing.Point(10, 25)
$comboBox1.Size = New-Object System.Drawing.Size(120, 25)
foreach($system in $systems)
{
$comboBox1.Items.add($system[0]) | Out-Null
}
$Form1.Controls.Add($comboBox1)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(70, 90)
$label.Size = New-Object System.Drawing.Size(98, 23)
$label.Text = ""
$Form1.Controls.Add($label)
[void]$form1.showdialog()
Write-Centered $comboBox1.Text "Yellow"
$do=0
$i=0
do {
if ($comboBox1.Text -eq $systems[$i][0]){
$result=$i
$i++
}
$do++
}while ($do -le $systems.length-1)
$System=$systems[$result][0]
$Server=$systems[$result][1]
$Instance=$systems[$result][2]
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
"Start the process."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
"Cancel the process."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice("",`
"`nWould you like to progress with the service restart? `n`nSystem: $System`nServer: $Server`nInstance: $Instance", $options, 0)
if ($result -eq 0) {
$services = Get-Service -computername $Server -name $Instance
$target=$services.name
$sharefolder = "\\"+$Server+"\c$"
New-PSDrive –Name “X” –PSProvider FileSystem –Root $sharefolder | out-null
Write-Host ======================================================
Write-Host = Searching for the destination folder. Please wait...
Write-Host ======================================================
$test1=Test-Path "X:\Program Files (x86)\BMC Software"
$test2=Test-Path "X:\Program Files\BMC Software"
if ($test1) {
$file=Get-ChildItem "X:\Program Files (x86)\BMC Software" -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "CONTROL-SA"}
} elseif ($test2){
$file=Get-ChildItem "X:\Program Files\BMC Software" -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "CONTROL-SA"}
}
$fullname=$file.FullName+"\Services Manager\"+$Instance
$fullname
Write-Host ======================================================
Write-Host = Stopping $target
Write-Host ======================================================
Get-Service -Name $target -ComputerName $Server | Set-Service -Status Stopped
$src=$fullname+"\log\*"
$des=$fullname+"\log_bkp_"+$timestamp+"\"
Write-Host ======================================================
Write-Host = Perform LOG folder backup for troubleshooting
Write-Host ======================================================
New-Item $des -type directory | out-null
Move-item -path $src -destination $des -force -verbose
#Remove-item $src -force -recurse -verbose
Get-Service -Name $target -ComputerName $Server | Set-Service -Status Running
Remove-PSDrive -Name "X" | out-null
}
elseif ($result -eq 1) {
BREAK
}
Write-Host ======================================================
Write-Host = Process Completed
Write-Host = You may now close this window
Write-Host ======================================================
Start-Sleep -s 120
Have the screen captures of the results.. but low reputation prevent me to post it... :-(
I typo'd my comment, it should be Controls and not Controles, but that's the issue. After $Form1.Controls.Add($label) add a new line:
$Form1.Controls.Add($Button)
See if it doesn't work as expected at that time. It does for me when I tested it.
A wrong place for the $Form1.Controls.Add($Button) was preventing my code to show up the control button...
Thanks for the hint