Can someone point me in the right direction? I want to create a powershell script that opens up to a module with check boxes and fields.
Say I have individual powershell scripts that I want to run on a server. I want to be able to have them all in the window and be able to toggle them on and off (with a checkbox) as needed. Here is an example of some code and the GUI I want to make.
So each check box would add the respective code to the list to run. I should be able to get the GUI setup. Its the run button, getting the checkbox to call up a script and the variable field I'm not too sure about.
Screenshot
Here is the code I am working with
#This creates the form and sets its size and position
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Server Setup / Install Roles"
$objForm.Size = New-Object System.Drawing.Size(800,800)
#This creates a checkbox called Set Remote Execution to: unrestricted
$objSet_RECheckbox = New-Object System.Windows.Forms.Checkbox
$objSet_RECheckbox.Location = New-Object System.Drawing.Size(10,10)
$objSet_RECheckbox.Size = New-Object System.Drawing.Size(500,20)
$objSet_RECheckbox.Text = "Set Remote Execution to: unrestricted"
$objSet_RECheckbox.TabIndex = 1
$objForm.Controls.Add($objSet_RECheckbox)
#This creates a checkbox called Change time zone
$objTimeCheckbox = New-Object System.Windows.Forms.Checkbox
$objTimeCheckbox.Location = New-Object System.Drawing.Size(10,30)
$objTimeCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objTimeCheckbox.Text = "Change time zone"
$objTimeCheckbox.TabIndex = 2
$objForm.Controls.Add($objTimeCheckbox)
#This creates a checkbox called Install DNS Role
$objDNSCheckbox = New-Object System.Windows.Forms.Checkbox
$objDNSCheckbox.Location = New-Object System.Drawing.Size(10,50)
$objDNSCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objDNSCheckbox.Text = "Install DNS Role"
$objDNSCheckbox.TabIndex = 3
$objForm.Controls.Add($objDNSCheckbox)
#This creates a checkbox called Install DHCP Role
$objDHCPCheckbox = New-Object System.Windows.Forms.Checkbox
$objDHCPCheckbox.Location = New-Object System.Drawing.Size(10,70)
$objDHCPCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objDHCPCheckbox.Text = "Install DHCP Role"
$objDHCPCheckbox.TabIndex = 4
$objForm.Controls.Add($objDHCPCheckbox)
#This creates a checkbox called Install Print Role
$objPrintCheckbox = New-Object System.Windows.Forms.Checkbox
$objPrintCheckbox.Location = New-Object System.Drawing.Size(10,90)
$objPrintCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objPrintCheckbox.Text = "Install Print Role"
$objPrintCheckbox.TabIndex = 5
$objForm.Controls.Add($objPrintCheckbox)
#This creates a checkbox called Install AD and DC promo
$objAD_NewCheckbox = New-Object System.Windows.Forms.Checkbox
$objAD_NewCheckbox.Location = New-Object System.Drawing.Size(10,110)
$objAD_NewCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objAD_NewCheckbox.Text = "Install AD and DC promo"
$objAD_NewCheckbox.TabIndex = 6
$objForm.Controls.Add($objAD_NewCheckbox)
#This creates a label for the DomainMode TextBox1
$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,140)
$objLabel1.Size = New-Object System.Drawing.Size(280,20)
$objLabel1.Text = "Domain Mode"
$objForm.Controls.Add($objLabel1)
#This creates the DomainMode TextBox1
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(10,160)
$objTextBox1.Size = New-Object System.Drawing.Size(100,20)
$objTextBox1.TabIndex = 0
$objForm.Controls.Add($objTextBox1)
#This creates the RUN button and sets the event
$RUNButton = New-Object System.Windows.Forms.Button
$RUNButton.Location = New-Object System.Drawing.Size(10,190)
$RUNButton.Size = New-Object System.Drawing.Size(75,23)
$RUNButton.Text = "RUN"
$RUNButton.Add_Click({$objForm.Close()})
$RUNButton.TabIndex = 9
$objForm.Controls.Add($RUNButton)
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
I think you have answered all your questions there.
In the other code you are referring to, the button has an event handler. Whatever is inside this code block, gets executed when you press the button.
Inside the code block, the code is looking for which checkbox has been checked using the if loop. All you need to do is call the script you want from the correct if loop. Instead of external script files, you could also call scriptblocks which I think is a cleaner way.
$handler_button1_Click=
{
$listBox1.Items.Clear();
if ($checkBox1.Checked) { "C:\MyScript\Script1.ps1" }
if ($checkBox2.Checked) { "C:\MyScript\Script2.ps1" }
if ($checkBox3.Checked) { "C:\MyScript\Script3.ps1" }
}
If you want to do more with the results of the script after execution, you can put that too inside the if block.
I have written one in GUI that uses checkboxes if you want to refer: Windows Patching Assistant
Related
I have a PS script that implements System.Windows.Forms in order to query technicians for some data.
I create the forms and set both .Topmost and .TopLevel to true in an attempt to have them show up over the Powershell window, but they continue to (for some reason inconsistently) appear behind the Powershell window. This slows down the process and is confusing in its inconsistency.
If anyone knows how to ensure these windows stay top without a mountain of code larger than the script itself that would be incredibly useful. I'll include the code I use to build one of the basic forms below.
Any simple solution that will allow these Forms to appear over the Powershell window is appreciated. It could even just minimize the PS window, but I don't want to launch without the window as we need it open. Thanks.
$form.Text = 'Computer Name Entry'
$form.Size = New-Object System.Drawing.Size(550,400)
$form.StartPosition = 'CenterScreen'
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(75,300)
$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)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(400,40)
$label.Text = 'Text is here:'
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,70)
$textBox.Size = New-Object System.Drawing.Size(400,20)
$form.Controls.Add($textBox)
$form.Topmost = $true
$form.TopLevel = $true
$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
Do-Stuff
}
The easiest way I know of forcing the form to be topmost is to open it with a new temporary form that is TopMost as parameter for ShowDialog().
First, from your code remove the lines $form.Topmost = $true and $form.TopLevel = $true
Next, show your form like this:
# force the dialog TopMost by creating a temporary parent window for this form
$result = $form.ShowDialog((New-Object System.Windows.Forms.Form -Property #{TopMost = $true }))
Another way of doing this is to use a piece of C# to return a windowhandle which implements the IWin32Window interface.
Then use this handle as the owner window for this form in the .ShowDialog() method of the form.
For this method, also remove the lines $form.Topmost = $true and $form.TopLevel = $true from your original code.
$iWin32Code = #"
using System;
using System.Windows.Forms;
public class Win32Window : IWin32Window {
public Win32Window(IntPtr handle) {
Handle = handle;
}
public IntPtr Handle { get; private set; }
}
"#
if (-not ([System.Management.Automation.PSTypeName]'Win32Window').Type) {
Add-Type -TypeDefinition $iWin32Code -ReferencedAssemblies System.Windows.Forms.dll
}
Now, using that code, create a handle for the currently running PowerShell process
# get the owner handle from this PowerShell process
$ownerHandle = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
# and use that in the ShowDialog method as argument
$result = $form.ShowDialog($ownerHandle)
P.S. do not forget to clear your form from memory after you are done with it by calling
$form.Dispose()
Im trying to build a gui form using powershell, i want to add a button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(35,35)
$Button.Size = New-Object System.Drawing.Size(120,23)
$Button.Text = "Show Dialog Box"
$Form.Controls.Add($Button)
$Button.Add_Click($Button_Click)
now i want to create a function called button_click with a few commands, lets say: echo "Hello world"
so i write this:
Function Button_Click(){
echo "Hello World"}
But clicking on the button wont give me any result, what am i doing wrong here?
You were using Write-Output which will write to the pipeline and in this case will not be displayed because your PowerShell console is locked while the $form.ShowDialog() is active.
However you can still do this! Write-host is another cmdlet for returning output and it can directly write to the PowerShell host window in real time. This is one of those rare times when you probably do want to use Write-Host.
Then, some small tweaks to make. Your event handler behavior should generally be defined before adding the $button to the $Form.
You made a function named Button_click, but you add the event handler like it is a variable. Here's how to do that instead, by making a variable which contains a {scriptblock}:
$button_click = {write-host "hi Sahar"}
And with that done, your code should look like this, and it will work as expected
$form = New-Object System.Windows.Forms.Form
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(35,35)
$Button.Size = New-Object System.Drawing.Size(120,23)
$Button.Text = "Show Dialog Box"
$Button.Add_Click($Button_Click)
$Form.Controls.Add($Button)
$form.showdialog()
I'm trying to work around a script Under Windows.Form and I'm a little bit stuck.
I'd like to be able a specific list appears depending on the choice made from the first list, which means that at the start of the script, only one list has to appears and many other available depending of the choice made.
Here's the full script for reference
#Open a Window.
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$form = New-Object Windows.Forms.Form
$form.text = "Contrôles"
$form.Size = New-Object System.Drawing.Size(1000,700)
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,150)
$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,150)
$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)
#Create the Data table (DataTable).
$table1 = New-Object system.Data.DataTable
$table2 = New-Object system.Data.DataTable
#Define the 2 column (Name, Type).
$colonne1 = New-Object system.Data.DataColumn Choice,([string])
$colonne2 = New-Object system.Data.DataColumn Choice,([string])
#Create columns in the data table.
$table1.columns.add($colonne1)
$table2.columns.add($colonne2)
#Add the data line by line in the data table.
$ligne = $table1.NewRow() #Creation of the new row.
$ligne.Choice = "Service" #In the column Choice we put the value we want.
$table1.Rows.Add($ligne) #Add a line in the data table.
$ligne = $table1.NewRow()
$ligne.Choice = "Software"
$table1.Rows.Add($ligne)
$ligne = $table1.NewRow()
$ligne.Choice = "Other"
$table1.Rows.Add($ligne)
#Add the data line by line in the data table.
$ligne = $table2.NewRow() #Creation of the new row.
$ligne.Choice = "Service Enable" #In the column Choice we put the value we want.
$table2.Rows.Add($ligne) #Add a line in the data table.
$ligne = $table2.NewRow()
$ligne.Choice = "Service Disable"
$table2.Rows.Add($ligne)
$ligne = $table2.NewRow()
$ligne.Choice = "Other"
$table2.Rows.Add($ligne)
#Create the View.
$vu1 = New-Object System.Data.DataView($table1)
$vu1.Sort="Choice ASC" #Tri la colonne "Extension" par ordre croissant.
$vu2 = New-Object System.Data.DataView($table2)
$vu2.Sort="Choice ASC"
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(650,50)
$label.Size = New-Object System.Drawing.Size(280,35)
$label.Text = 'Please enter the information in the space below:'
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(650,100)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$form.Controls.Add($textBox)
#Create the Drop-down list (ComboBox).
$liste1 = New-Object System.Windows.Forms.Combobox
$liste1.Location = New-Object Drawing.Point 20,50
$liste1.Size = New-Object System.Drawing.Size(150, 50)
$liste1.DropDownStyle = "DropDownList"
$liste2 = New-Object System.Windows.Forms.Combobox
$liste2.Location = New-Object Drawing.Point 350,50
$liste2.Size = New-Object System.Drawing.Size(150, 50)
$liste2.DropDownStyle = "DropDownList"
#Associate the Data to the Drop-down list
#To do so, we create a "Binding Context".
$liste1.BindingContext = New-Object System.Windows.Forms.BindingContext
$liste1.DataSource = $vu1 #Assigne the view that contains the sorted Data.
$liste1.DisplayMember = "Choice" #Column that will be displayed (Choice).
$liste2.BindingContext = New-Object System.Windows.Forms.BindingContext
$liste2.DataSource = $vu2 #Assigne the view that contains the sorted Data.
$liste2.DisplayMember = "Choice" #Column that will be displayed (Choice).
#Attach the control to the window.
$form.controls.add($liste1)
$form.controls.add($liste2)
#Show everything.
$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()
#Work the code arround.
if ($liste1.DisplayMember= "Service Enable")
{set-service -name RemoteRegistry -ComputerName $textBox.Text -StartupType Automatic}
if ($liste1.DisplayMember = "Service Disable")
{set-service -name RemoteRegistry -ComputerName $textBox.Text -StartupType Automatic}
Write-Host "ComboBox = " $liste1.DisplayMember
Write-Host "ComboBox = " $liste2.selectedvalue
#Fin.
If anybody have an idea where I could look, it would be great.
Thanks you
Nad
1. You have no form / trigger events in your code.
2. You don't have the correct GUI objects in your code to hold a list /
record result.
A form is just a container to hold elements until you add the code behind to make it do something. You have to have a proper GUI object to send that result to.
I am not sure if you are doing this all by hand in the ISE or VSCode or Notepad or whatever, but this is a good first effort. However, what you show, seems to indicate you are not really up to speed on GUI development / general app dev work, as what you are doing is not really unique to PowerShell, but something required for any app development client or web.
So, really, spend some time studying / reviewing general WPF/Winforms development and that form event stuff will be covered.
As for your use case, you need:
Define the list GUI object (multiline, ListBox, ListView, datagrid) to hold the results (synch'ing combox boxes mean adding and removing elements on event actions)
Define what that list is (text files, db read etc)
On the click, change or other form event, read from that list and populate
the GUI list object
There are many examples of this on this site and all over the web.
Here a good video on GUI development with PowerShell:
powershell populate combobox basing on the selected item on another combobox
From the above discussion (not something to just add to your code without understanding the what's and the why's):
Use a ComboBox.SelectionChangeCommitted Event:
"Occurs when the user changes the selected item and that change is displayed in the ComboBox"
$combobox2_SelectionChangeCommitted={
$Mailboxes = Get-Mailbox -OrganizationalUnit $ClientSelected
foreach ($mailbox in $Mailboxes)
{
$CurrentMailbox = "{0} ({1})" -f $mailbox.Name, $mailbox.Alias
Load-ComboBox $combobox2 $CurrentMailbox -Append
}
}
Use a button:
$button1_Click={
$Mailboxes = Get-Mailbox -OrganizationalUnit $ClientSelected
foreach ($mailbox in $Mailboxes)
{
$CurrentMailbox = "{0} ({1})" -f $mailbox.Name, $mailbox.Alias
Load-ComboBox $combobox2 $CurrentMailbox -Append
}
}
Lastly, using this …
Write-Host "ComboBox = " $liste1.DisplayMember
Write-Host "ComboBox = " $liste2.selectedvalue
… is not something one would do, because the console is not opened to see these results and Write-Host should be avoided except for when using console only text colorizations of other console only formatting scenarios, it also empties the display buffer, so it cannot be sent to anything else. Also, you don't have a GUI object called 'ComboBox' anywhere on the form, so it's not serving any purpose for your use case.
After some times and research, I managed to find what I needed exactly.
This might help people who stumble upon the post so here a small part of what I found
function Service()
{if ($ListBox1.SelectedItem -eq 'Enable Services')
{
$form.Controls.Add($Label3)
$form.Controls.add($ListBox2)
$form.Controls.Add($Label4)
$form.Controls.Add($textBox)
$form.Controls.Add($Button2)
$form.Controls.Add($Button3)
}
I create firstly a Function with a name, in which will countain the condition of what I'd like to happen when a choice is made in my listbox "ComboBox"
$button1.add_Click({ Service })
Then I call that function from a button I Added, in which other Boxes will appear upon click on that button.
It is not very different from #Postanote's answer but that was the solution I'm more at ease with.
I am trying to run a powershell script remotely that displays a pop-up alert. We are attempting to create a sort of "Emergency Notification System". On the admin machine there is a script to choose which emergency alert to send to everyone, and then it should run/appear on everyone's screen.
I've used the /msg command to achieve this, but the message is so plain that it doesn't catch the user's attention and the text can't be customized (unless it can be, which in that case PLEASE enlighten me).
I am receiving the error below when attempting to do this. I've also attempted to do it via PsExec but receive the same error.
Error:
Exception calling "ShowDialog" with "0" argument(s): "Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application."
Below is the PowerShell script. It's nothing fancy, just wanting something that works for our purpose.
Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Disaster Alert!"
$Form.AutoScroll = $True
$Form.AutoSize = $True
$Form.AutoSizeMode = "GrowAndShrink"
$Form.WindowState = "Normal"
$Form.StartPosition = "CenterScreen"
$Form.Font = New-Object System.Drawing.Font("Calibri",60,[System.Drawing.FontStyle]::Bold)
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(500,200)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "Close"
$OKButton.Font = New-Object System.Drawing.Font("Calibri",11)
$OKButton.UseVisualStyleBackColor = $True
$OKButton.Add_Click({$Form.Close()})
$Form.Controls.Add($OKButton)
$Label = New-Object System.Windows.Forms.Label
$Label.Text = "Please Exit the Building`nBuilding Fire Alarm Sounding!!"
$Label.ForeColor = "Red"
$Label.TextAlign = "MiddleCenter"
$Label.AutoSize = $True
$Form.Controls.Add($Label)
$Form.ShowDialog()
Is it possible to have a pop-up via PowerShell? If not, does anyone have any recommendations?
Thank you very much in advance.
I'm trying to create a message dialogue in Powershell where the user has no option to action on the message as that is the intention. So the message will have the X button grayed along with the buttons (not showing buttons are even better).
The closest I could reach was disabling the X via below code:
$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop
$wshell.Popup("Aborted",0,"ERROR!",48+4)
But cannot figure out disabling button part. Below MS articles were of little help as well:
http://blogs.technet.com/b/heyscriptingguy/archive/2006/07/27/how-can-i-display-a-message-box-that-has-no-buttons-and-that-disappears-after-a-specified-period-of-time.aspx
https://msdn.microsoft.com/en-us/library/x83z1d9f(v=vs.84).aspx
Referred to few other articles over net some even suggesting custom made buttons using HTML, or VB library. But not what I was looking for.
Any help/hint/suggestion would be deeply appreciated.
Regards,
Shakti
Dig into the .NET Windows.Forms namespace, you can make pretty much any kind of window you want with that:
https://msdn.microsoft.com/en-us/library/system.windows.forms.aspx
Here's a quick sample window w/ no buttons that can't be moved/closed by the user, but closes itself after 5 seconds:
Function Generate-Form {
Add-Type -AssemblyName System.Windows.Forms
# Build Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Test"
$objForm.Size = New-Object System.Drawing.Size(220,100)
# Add Label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(80,20)
$objLabel.Size = New-Object System.Drawing.Size(100,20)
$objLabel.Text = "Hi there!"
$objForm.Controls.Add($objLabel)
# Show the form
$objForm.Show()| Out-Null
# wait 5 seconds
Start-Sleep -Seconds 5
# destroy form
$objForm.Close() | Out-Null
}
generate-form
Using the script above as a launching point I'm attempting to make a function that will allow me to popup a please wait message run some more script then close the popup
Function Popup-Message {
param ([switch]$show,[switch]$close)
Add-Type -AssemblyName System.Windows.Forms
# Build Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Test"
$objForm.Size = New-Object System.Drawing.Size(220,100)
# Add Label
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(80,20)
$objLabel.Size = New-Object System.Drawing.Size(100,20)
$objLabel.Text = "Hi there!"
$objForm.Controls.Add($objLabel)
If ($show)
{
$objForm.Show() | Out-Null
$global:test = "Show"
}
If ($close)
{
# destroy form
$objForm.Close() | Out-Null
$global:test = "Close"
}
}
I can then get the popup to display by:
Popup-Message -show
At this point I can see the $test variable as Show
But when I try to close the window with:
Popup-Message -close
But the popup window will not close
If I look at $test again it will show as Close
I'm assuming this has something to do with keeping the function in the Global Scope but I can't figure out how to do this with the form