Powershell UI - DialogResult - PropertyAssignmentException - powershell

I am creating a powershell UI for some Script.
Now I am running in an error. But first, here is my code of my form:
$form_appBase = New-Object System.Windows.Forms.Form
$form_appBase.Text = 'APP Policy creator'
$form_appBase.Width = 350
$form_appBase.Height = 150
$form_appBase.AutoSize = $true
$label_appFilename = New-Object System.Windows.Forms.Label
$label_appFilename.Location = '10,10'
$label_appFilename.Size = '200,15'
$label_appFilename.Text = 'Program'
$Textbox_appFilename = New-Object System.Windows.Forms.TextBox
$Textbox_appFilename.Location = '10,30'
$Textbox_appFilename.Size = '200,25'
$label_appVersion = New-Object System.Windows.Forms.Label
$label_appVersion.Location = '220,10'
$label_appVersion.Size = '100,15'
$label_appVersion.Text = 'Version:'
$Textbox_appVersion = New-Object System.Windows.Forms.TextBox
$Textbox_appVersion.Location = '220,30'
$Textbox_appVersion.Size = '100,25'
$label_appProgPath = New-Object System.Windows.Forms.Label
$label_appProgPath.Location = '10,60'
$label_appProgPath.Size = '130,15'
$label_appProgPath.Text = 'Path to PROG Policy'
$textbox_appProgPath = New-Object System.Windows.Forms.TextBox
$textbox_appProgPath.Location = '150,60'
$textbox_appProgPath.Size = '170,25'
$Radio_appBaseSW = New-Object System.Windows.Forms.RadioButton
$Radio_appBaseSW.Location = '10,90'
$Radio_appBaseSW.Size = '100,15'
$Radio_appBaseSW.Text = "Software"
$Radio_appBaseSW.DialogResult = [System.Windows.Forms.DialogResult]::SW
$Radio_appBaseHW = New-Object System.Windows.Forms.RadioButton
$Radio_appBaseHW.Location = '10,110'
$Radio_appBaseHW.Size = '100,15'
$Radio_appBaseHW.Text = "Hardware"
$Radio_appBaseHW.DialogResult = [System.Windows.Forms.DialogResult]::HW
$Button_appConfirm = New-Object System.Windows.Forms.Button
$Button_appConfirm.Location = '220,95'
$Button_appConfirm.Size = '100,30'
$Button_appConfirm.Text = "Create"
$form_appBase.Controls.Add($label_appFilename)
$form_appBase.Controls.Add($Textbox_appFilename)
$form_appBase.Controls.Add($label_appVersion)
$form_appBase.Controls.Add($Textbox_appVersion)
$form_appBase.Controls.Add($label_appProgPath)
$form_appBase.Controls.Add($textbox_appProgPath)
$form_appBase.Controls.Add($Radio_appBaseSW)
$form_appBase.Controls.Add($Radio_appBaseHW)
$form_appBase.Controls.Add($Button_appConfirm)
$form_appBase.AcceptButton = $Button_appConfirm
$dialogResultSHW = $form_appBase.ShowDialog()
}
$Button_appConfirm.Add_click(
{
if ($dialogResultSHW -eq "SW"){$appSHW = "SW"}
elseif ($dialogResultSHW -eq "HW"){
$appSHW = "HW"
$appFilename = $Textbox_appFilename.Text
$appVersion = $Textbox_appVersion.Text
$appProgPath = $textbox_appProgPath.Text
$appUNCPath = "\\zen\netlogon\applocker\Output + '\' + $appSHW + '-' + $appFilename + '-' $appVersion + '.' + 'xml' "
Write-Host "$appFilename"
Write-Host "$appVersion"
Write-Host "$appProgPath"
Write-Host "$appSHW"
Write-Host "$appUNCPath"
powershell.exe -file \\zen\netlogon\applocker\applockerwork.ps1 -application -in $appProgPath -out $appUNCPath
}
}
)
After checking everything, I get the following error:
Powershell_Error
Can anyone help me to find out why this error persists? I tried many Ideas I found on the WWW but nothing seemed to work.

First of all, the [System.Windows.Forms.DialogResult] enum does not have values like "SW" or "HW"..
Remove the lines $Radio_appBaseSW.DialogResult = ... and $Radio_appBaseHW.DialogResult = ... because as guiwhatsthat commented, the RadioButtonClass does not have such a property.
Also change $dialogResultSHW = $form_appBase.ShowDialog() into [void]$form_appBase.ShowDialog()
Then, in your $Button_appConfirm.Add_click({..}) event, do
$appSHW = if ($Radio_appBaseSW.Checked) { "SW" } elseif ($Radio_appBaseHW.Checked) {"HW"}
and use the value of $appSHW do perform the different actions, or simply do
if ($Radio_appBaseSW.Checked) {
# perform action for choice Software
}
elseif ($Radio_appBaseHW.Checked) {
perform a different action for choice Software
}
else {
# no radiobutton was touched... Alert the user to select either the Software or the Hardware radio button
}
Finally, do not forget to remove the form from memory when you are done with it with $form_appBase.Dispose()

Related

Powershell TextBox automatically update file contents

Anyone can help me fix my code below. I am displaying a log file in the textbox, but the textbox wont update automatically when the log file is updated. I tried using a timer but it wont work since it will refresh the whole form and the input file name will be reset too, so it will return a null value. Please go to "viewComo" function.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
#2. Instantiate a Form Object
#-----------------------------------------------------------------------------------------
$Form_MAIN = New-Object system.Windows.Forms.Form;
$Form_MAIN.ClientSize = New-Object System.Drawing.Point(1024,1000);
$Form_MAIN.StartPosition = "manual";
$Form_MAIN.Location = New-Object System.Drawing.Size(600,300);
$Form_MAIN.BackColor = [System.Drawing.ColorTranslator]::FromHtml("#6699CC");
$Form_MAIN.text = "DataCenter Operation Applications";
$Form_MAIN.TopMost = $false;
$Form_MAIN.AutoSize = $false;
$Form_MAIN.AutoScale = $false;
$Form_MAIN.MaximizeBox = $false;
#3. Build the Form Components
#-----------------------------------------------------------------------------------------
$MainMenu = New-Object System.Windows.Forms.MenuStrip;
$Menu_File = New-Object System.Windows.Forms.ToolStripMenuItem("File");
$SubMenu_Open = New-Object System.Windows.Forms.ToolStripMenuItem("Open");
$SubMenu_Save = New-Object System.Windows.Forms.ToolStripMenuItem("Save");
$SubMenu_Exit = New-Object System.Windows.Forms.ToolStripMenuItem("Exit");
$Menu_DCApp = New-Object System.Windows.Forms.ToolStripMenuItem("DCApp");
$SubMenu_Reports_Checker = New-Object System.Windows.Forms.ToolStripMenuItem("Reports_Checker");
$SubMenu_Reports_Transfer = New-Object System.Windows.Forms.ToolStripMenuItem("Reports_Transfer");
$SubMenu_COB_Monitoring = New-Object System.Windows.Forms.ToolStripMenuItem("COB_Monitoring");
$SubMenu_AD_AccountLock_Checker = New-Object System.Windows.Forms.ToolStripMenuItem("AD_AccountLock_Checker");
$Menu_Help = New-Object System.Windows.Forms.ToolStripMenuItem("Help");
$Menu_About = New-Object System.Windows.Forms.ToolStripMenuItem("About");
$GB_Top = New-Object system.Windows.Forms.Groupbox;
$GB_Top.height = 330;
$GB_Top.width = 990;
$GB_Top.text = "Como Checker, Please input the Service name below";
$GB_Top.location = New-Object System.Drawing.Point(15,30);
$GB_Top.Font = New-Object System.Drawing.Font('Calibri',12);
$TB_Top_Input = New-Object system.Windows.Forms.TextBox;
$TB_Top_Input.multiline = $true;
$TB_Top_Input.width = 840;
$TB_Top_Input.height = 30;
$TB_Top_Input.location = New-Object System.Drawing.Point(10,25);
$TB_Top_Input.Font = New-Object System.Drawing.Font('Calibri',10);
$TB_Top_Button = New-Object system.Windows.Forms.Button;
$TB_Top_Button.Text = "Search COMO";
$TB_Top_Button.width = 124;
$TB_Top_Button.height = 30;
$TB_Top_Button.location = New-Object System.Drawing.Point(850,25);
$TB_Top_Button.Add_Click({checkComoFiles})
$RB_LabelQuery = New-Object System.Windows.Forms.Label;
$RB_LabelQuery.Text = "Choose the Range to query:";
$RB_LabelQuery.AutoSize = $true;
$RB_LabelQuery.width = 104;
$RB_LabelQuery.height = 10;
$RB_LabelQuery.location = New-Object System.Drawing.Point(10,55);
$RB_LabelQuery.Font = New-Object System.Drawing.Font('Callibri',9);
$RB_Option1 = New-Object system.Windows.Forms.RadioButton;
$RB_Option1.Text = "Last 1 Hour";
$RB_Option1.AutoSize = $true;
$RB_Option1.width = 104;
$RB_Option1.height = 10;
$RB_Option1.location = New-Object System.Drawing.Point(170,55);
$RB_Option1.Font = New-Object System.Drawing.Font('Callibri',9);
$RB_Option2 = New-Object system.Windows.Forms.RadioButton;
$RB_Option2.Text = "Last 3 Hours";
$RB_Option2.AutoSize = $true;
$RB_Option2.width = 104;
$RB_Option2.height = 10;
$RB_Option2.location = New-Object System.Drawing.Point(270,55);
$RB_Option2.Font = New-Object System.Drawing.Font('Callibri',9);
$RB_Option3 = New-Object system.Windows.Forms.RadioButton;
$RB_Option3.Text = "Last 24 Hours";
$RB_Option3.AutoSize = $true;
$RB_Option3.width = 104;
$RB_Option3.height = 10;
$RB_Option3.location = New-Object System.Drawing.Point(360,55);
$RB_Option3.Font = New-Object System.Drawing.Font('Callibri',9);
$RB_LabelOutput = New-Object System.Windows.Forms.Label;
$RB_LabelOutput.Text = "Result:";
$RB_LabelOutput.AutoSize = $true;
$RB_LabelOutput.width = 104;
$RB_LabelOutput.height = 10;
$RB_LabelOutput.location = New-Object System.Drawing.Point(10,85);
$RB_LabelOutput.Font = New-Object System.Drawing.Font('Calibri',12);
#$TB_Top_Output = New-Object system.Windows.Forms.TextBox;
#$TB_Top_Output.multiline = $true;
#$TB_Top_Output.width = 970;
#$TB_Top_Output.height = 200;
#$TB_Top_Output.location = New-Object System.Drawing.Point(10,110);
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(970,200)
$dataGridView.Location = New-Object System.Drawing.Point(10,110);
$dataGridView.BackgroundColor = "White";
#$form.Controls.Add($dataGridView)
$dataGridView.ColumnCount = 1
$dataGridView.ColumnHeadersVisible = $true
$dataGridView.Columns[0].Name = "Como Name"
$datagridview.Columns[0].Width = 300;
$datagridview.Font = New-Object System.Drawing.Font('Courier New',9);
$datagridview.Add_CellMouseDoubleClick({viewComoGrid})
$GB_Bottom = New-Object system.Windows.Forms.Groupbox;
$GB_Bottom.height = 600;
$GB_Bottom.width = 990;
$GB_Bottom.text = "View COMO";
$GB_Bottom.location = New-Object System.Drawing.Point(15,380);
$GB_Bottom.Font = New-Object System.Drawing.Font('Calibri',12);
$TB_Bottom_Input = New-Object system.Windows.Forms.TextBox;
$TB_Bottom_Input.multiline = $true;
$TB_Bottom_Input.width = 840;
$TB_Bottom_Input.height = 30;
$TB_Bottom_Input.location = New-Object System.Drawing.Point(10,20);
$TB_Bottom_Input.Font = New-Object System.Drawing.Font('Calibri',10);
$TB_Bottom_Button = New-Object system.Windows.Forms.Button;
$TB_Bottom_Button.Text = "View COMO";
$TB_Bottom_Button.width = 124;
$TB_Bottom_Button.height = 30;
$TB_Bottom_Button.location = New-Object System.Drawing.Point(850,20);
$TB_Bottom_Button.Font = New-Object System.Drawing.Font('Calibri',10);
$TB_Bottom_Button.Add_Click({viewComo})
$RB_LabelOutput_Bottom = New-Object System.Windows.Forms.Label;
$RB_LabelOutput_Bottom.Text = "Result:";
$RB_LabelOutput_Bottom.AutoSize = $true;
$RB_LabelOutput_Bottom.width = 104;
$RB_LabelOutput_Bottom.height = 10;
$RB_LabelOutput_Bottom.location = New-Object System.Drawing.Point(10,55);
$RB_LabelOutput_Bottom.Font = New-Object System.Drawing.Font('Calibri',12);
$TB_Top_Output_Bottom = New-Object system.Windows.Forms.TextBox;
$TB_Top_Output_Bottom.multiline = $true;
$TB_Top_Output_Bottom.size = New-Object System.Drawing.Size(970,510)
$TB_Top_Output_Bottom.ReadOnly = $True
#$TB_Top_Output_Bottom.width = 970;
#$TB_Top_Output_Bottom.height = 510;
$TB_Top_Output_Bottom.location = New-Object System.Drawing.Size(10,80);
$TB_Top_Output_Bottom.ScrollBars = 'Both'
$TB_Top_Output_Bottom.Font = New-Object System.Drawing.Font('Courier New',9);
#4. Add the Components to the Group Boxes
#-----------------------------------------------------------------------------------------
$GB_Top.controls.AddRange(#($RB_LabelQuery, $RB_Option1,$RB_Option2,$RB_Option3,$TB_Top_Input, $TB_Top_Button, $RB_LabelOutput, $dataGridView));
$GB_Bottom.controls.AddRange(#($L_Bottom_Output,$B_Enter, $TB_Bottom_Input, $TB_Bottom_Button, $RB_LabelOutput_Bottom, $TB_Top_Output_Bottom ));
#4. Add the Components to the Form
#-----------------------------------------------------------------------------------------
$Menu_File.DropDownItems.Add($SubMenu_Open);
$Menu_File.DropDownItems.Add($SubMenu_Save);
$Menu_File.DropDownItems.Add($SubMenu_Exit);
$Menu_DCApp.DropDownItems.Add($SubMenu_Reports_Checker);
$Menu_DCApp.DropDownItems.Add($SubMenu_Reports_Transfer);
$Menu_DCApp.DropDownItems.Add($SubMenu_COB_Monitoring);
$Menu_DCApp.DropDownItems.Add($SubMenu_AD_AccountLock_Checker);
$MainMenu.Items.Add($Menu_File);
$MainMenu.Items.Add($Menu_DCApp);
$MainMenu.Items.Add($Menu_Help);
$MainMenu.Items.Add($Menu_About);
$Form_MAIN.controls.AddRange(#($MainMenu,$TB_Output));
#4.1 Add the Group Boxes to the Form
#-----------------------------------------------------------------------------------------
$Form_MAIN.controls.AddRange(#($GB_Top,$GB_Bottom));
#5. Code the Event Handlers
#-----------------------------------------------------------------------------------------
$SubMenu_Open.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n Open File."; })
$SubMenu_Save.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n Save File."; })
$SubMenu_Exit.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n Exit Program."; })
$SubMenu_Reports_Checker.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n Reports_Checker"; })
$SubMenu_Reports_Transfer.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n Reports_Transfer"; })
$SubMenu_COB_Monitoring.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n COB_Monitoring"; })
$SubMenu_AD_AccountLock_Checker.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n AD_AccountLock_Checker"; })
$Menu_DCApp.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n Options!"; })
$Menu_Help.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n Help me!"; })
$Menu_About.Add_Click({ $TB_Top_Output_Bottom.Text = "`r`n All about ME."; })
function checkComoFiles {
$servicename= $TB_Top_Input.Text
$dataGridView.Rows.Clear()
$TB_Top_Input.Clear()
if ($RB_Option1.Checked) {
$hours = 1
$ResultQuery = Get-ChildItem -Path C:\Users\user\Downloads\ -File | Where-Object {($_.LastWriteTime - gt (Get-Date (Get-Date).AddHours(-$hours))) } |
ForEach-Object { $_ | Select-String -List -Pattern $servicename -SimpleMatch |
Select-Object -first 1 -ExpandProperty FileName}
}
if ($RB_Option2.Checked) {
$hours = 3
$ResultQuery = Get-ChildItem -Path C:\Users\user\Downloads\ -File | Where-Object {($_.LastWriteTime -gt (Get-Date (Get-Date).AddHours(-$hours))) } |
ForEach-Object { $_ | Select-String -List -Pattern $servicename -SimpleMatch |
Select-Object -first 1 -ExpandProperty FileName}
}
if ($RB_Option3.Checked) {
$hours = 24
$ResultQuery = Get-ChildItem -Path C:\Users\user\Downloads\ -File | Where-Object {($_.LastWriteTime -gt (Get-Date (Get-Date).AddHours(-$hours))) } |
ForEach-Object { $_ | Select-String -List -Pattern $servicename -SimpleMatch |
Select-Object -first 1 -ExpandProperty FileName}
}
$dataGridView.Columns[0].Name = $servicename
$rows = #($ResultQuery)
foreach ($row in $rows)
{
$dataGridView.Rows.Add($row)
}
}
Function viewComo {
$comoName = $TB_Bottom_Input.Text
$openComolive = Get-Content C:\Users\user\Downloads\$comoName
$TB_Top_Output_Bottom.Lines = $openComolive
$TB_Bottom_Input.Clear()
}
Function viewComoGrid {
$rowIndex = $datagridview.CurrentRow.Index
$columnIndex = $datagridview.CurrentCell.ColumnIndex
#Write-Host $rowIndex
#Write-Host $columnIndex
#Write-Host $datagridview.Rows[$rowIndex].Cells[0].value
#Write-Host $datagridview.Rows[$rowIndex].Cells[$columnIndex].value
$comoNameGrid = $datagridview.Rows[$rowIndex].Cells[0].value
$openComoliveGrid = Get-Content C:\Users\user\Downloads\$comoNameGrid
$TB_Top_Output_Bottom.Lines = $openComoliveGrid
$TB_Bottom_Input.Clear()
}
#6. Display Form
#-----------------------------------------------------------------------------------------
$Form_Main.ShowDialog();
Im trying to use below timer in my above code but it wont work since the whole form will be refresh
$timer = new-object Windows.Forms.Timer
$timer.Interval=10000
$timer.add_Tick({$TB_Top_Output_Bottom.Lines = Get-Content C:\Users\user\Downloads\$logname | Out-String; $TB_Top_Output_Bottom.Refresh()})
$timer.Start()
Original Version:
This isn't exactly intended to be an answer!
I think mklement0's answer is probably a safer way of getting the job done. But I remember reading about FileSystemWatcher some years ago, and having never used it before, wanted to give it a try.
Found this C# FileSystemWatcher answer, and figured out how to recreate the work in PowerShell.
Found this interesting use of SynchronizingObject for System.Timers.Timer that appears to allow Timer's Elapsed event to to run in the same thread as a control or form, and discovered that FileSystemWatcher also has a SynchronizingObject Property.
This seems to work flawlessly when editing and saving MyLogFile.TXT with NotePad.exe, but when I load MyLogFile.TXT in VSCode, the script either crashes or stops working. I think VSCode is locking the file and preventing the script from reading it, but I'm not really sure.
I would like to stress that this is an experiment, and this is outside my experience, use with with caution.
Basic code for setting up a Form for testing FileSystemWatcher:
using namespace System.Windows.Forms
Add-Type -AssemblyName System.Windows.Forms
[Application]::EnableVisualStyles()
$FilePathToWatch = $PSScriptRoot
$FileNameToWatch = "MyLogFile.TXT"
$FilePathNameToWatch = Join-Path -Path $FilePathToWatch -ChildPath $FileNameToWatch
$Form_MAIN = [Form]#{
AutoSize = $false
AutoScale = $false
BackColor = '0x6699CC'
ClientSize = "1024,1000"
Location = "600,300"
MaximizeBox = $false
StartPosition = "manual"
Text = "DataCenter Operation Applications"
Topmost = $true
}
$TextBox_Output = [TextBox]#{
Anchor = 'Top, Left, Bottom, Right'
Location = '12, 12'
Multiline = $true
Name = 'TextBox_Output'
Size = "$($Form_MAIN.ClientSize.Width - 24), $($Form_MAIN.ClientSize.Height - 24)"
Text = Get-Content -Raw $FilePathNameToWatch
}
$Form_Main.Controls.Add($TextBox_Output)
Code for setting up FileSystemWatcher, ending with ShowDialog() to open the form, $watcher.Dispose() to, as mklement0 pointed out, to stop $watcher from continuing to fire after form closes.:
[IO.FileSystemWatcher]$watcher = [IO.FileSystemWatcher]#{
Path = $FilePathToWatch
NotifyFilter = [IO.NotifyFilters]::LastWrite
Filter = $FileNameToWatch
SynchronizingObject = $TextBox_Output
}
$watcher.Add_Changed({
$TextBox_Output.Text = Get-Content -Raw $FilePathNameToWatch
})
$watcher.EnableRaisingEvents = $true
$null = $Form_Main.ShowDialog()
$watcher.Dispose()
UPDATED Version:
Walk through of changes from above code, full code listed in order in following sections:
Add function GetLogFileContent for safely reading the file, or returning an empty string when the file doesn't exist.
using namespace System.Windows.Forms
Add-Type -AssemblyName System.Windows.Forms
[Application]::EnableVisualStyles()
$FilePathToWatch = $PSScriptRoot
$FileNameToWatch = "MyLogFile.TXT"
$FilePathNameToWatch = Join-Path -Path $FilePathToWatch -ChildPath $FileNameToWatch
function GetLogFileContent {
param ( [Parameter(Mandatory = $true, Position = 0)][string]$FilePathName )
if(Test-Path -PathType Leaf -LiteralPath $FilePathName) { Get-Content -Raw $FilePathName } else { '' }
}
Added code for Form's FormClosing event to shutdown $watcher so it no longer is firing events and properly disposed.
$Form_MAIN = [Form]#{
AutoSize = $false
AutoScale = $false
BackColor = '0x6699CC'
ClientSize = "1024,1000"
Location = "600,300"
MaximizeBox = $false
StartPosition = "manual"
Text = "DataCenter Operation Applications"
Topmost = $true
}
$Form_MAIN.Add_FormClosing({
$watcher.Dispose()
})
The TextBox Text property is assigned results of call to GetLogFileContent function.
$TextBox_Output = [TextBox]#{
Anchor = 'Top, Left, Bottom, Right'
Location = '12, 12'
Multiline = $true
Name = 'TextBox_Output'
Size = "$($Form_MAIN.ClientSize.Width - 24), $($Form_MAIN.ClientSize.Height - 24)"
Text = GetLogFileContent $FilePathNameToWatch
}
$Form_Main.Controls.Add($TextBox_Output)
$watcher's NotifyFilter property now set for checking for both FileName and LastWrite. Just a reminder, SynchronizingObject set to the TextBox so it can be updated on the same thread.
[IO.FileSystemWatcher]$watcher = [IO.FileSystemWatcher]#{
Path = $FilePathToWatch
NotifyFilter = [IO.NotifyFilters]::FileName -bor [IO.NotifyFilters]::LastWrite
Filter = $FileNameToWatch
SynchronizingObject = $TextBox_Output
}
Added Deleted and Renamed events to $watcher to catch deletions and renames, and using GetLogFileContent function to populate the textbox Text property.
$watcher.Add_Changed({
$TextBox_Output.Text = GetLogFileContent $FilePathNameToWatch
})
$watcher.Add_Deleted({
$TextBox_Output.Text = ''
})
$watcher.Add_Renamed({
$TextBox_Output.Text = if($_.Name -eq $FileNameToWatch) { GetLogFileContent $FilePathNameToWatch } else { '' }
})
Watcher.Dispose() removed from end of code (taken care of in FormClosing event).
$watcher.EnableRaisingEvents = $true
$null = $Form_Main.ShowDialog()
Note:
This answer addresses the question as asked.
Darin's helpful answer shows an alternative approach that doesn't unconditionally, periodically re-read the log file (based on a timer), but uses an event-based file-system watcher to only update re-read the file if and when it changes.
This is more elegant and generally preferable, except if the log file is updated very frequently, in which case you'd need a throttling mechanism (which the timer-based approach implicitly provides, though one could be implemented with the file-watcher approach too).
There is no obvious problem with your approach:
The System.Windows.Forms.Timer type fires its events on the GUI thread and therefore allows modifying the form state.
While script blocks ({ ... }) that are passed as event delegates in .add_<eventName>() calls run in a child scope of the script, thanks to PowerShell's dynamic scoping you can still read the variables from the script scope.
Since WinForms is in control of the event loop when you show a form modally with .ShowDialog(), it is sufficient to assign new content to the .Lines property of your text-box control: the control should refresh automatically (and even an explicit .Refresh() call should not make the whole form refresh).
The following is a self-contained proof of concept:
A background job is started that writes the current timestamp to a given file every second.
The WinForms code uses a timer event to read that file and update its multi-line text box control with it.
using namespace System.Windows.Forms
using namespace System.Drawing
Add-Type -AssemblyName System.Windows.Forms
# Create the form.
$form = [Form] #{
Text = "Textbox Timer-Based Refresh Demo"
Size = [Size]::new(380,200)
StartPosition = "CenterScreen"
}
# Create the textbox and add it to the form.
$form.Controls.AddRange(#(
($textBox = [TextBox] #{
Location = [Point]::new(10, 10)
Size = [Size]::new(320, 90)
MultiLine = $true
})
))
# Create a timer that fires every second, and
# reads the then-current file content.
$timer = [Timer]::new()
$timer.InterVal = 1000
$timer.add_Tick({
$textBox.Lines = Get-Content -Raw $logName
})
$timer.Start()
# The log file to read.
$logName = 't.txt'
# Create a background job that updates the log file every second.
$jb = Start-Job {
while ($true) {
Get-Date > "$using:PWD/$using:logName"
Start-Sleep 1
}
}
# Show the form modally.
$null = $form.ShowDialog()
# Clean up
$timer.Dispose()
$jb | Remove-Job -Force

Powershell InputBox (selfmade) only returns "Cancel"

`In a Powershell project - small GUI with Winforms - I need a passwordbox. I wrote a test-function but cannot manage to get the correct output ... I only get "Cancel"
I get the same result if I do not use
$inpBox.PasswordChar = "*"
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[System.Windows.Forms.Application]::EnableVisualStyles()
function InputForm {
param($loggedInUser="Spock")
$inpForm = New-Object System.Windows.Forms.Form
$inpForm.Height = 120
$inpForm.Width = 350
# $inpForm.Icon = "$PSScriptRoot\Heidelberg-H.ico"
$inpForm.Text = "Authentication Window"
$inpForm.MaximizeBox = $false
$inpForm.MinimizeBox = $false
$inpForm.FormBorderStyle = "FixedDialog"
$inpForm.StartPosition = "CenterScreen" # moves to center of screen
$inpForm.Topmost = $true # Make it Topmost
# create a Label
$inpLbl = New-Object System.Windows.Forms.Label
$inpLbl.Width = 300
$inpLbl.Location = New-Object System.Drawing.Point(10,10)
$inpLbl.Text = "Please type in the password for user: " + $loggedInUser
# create a InputBox for the password
$inpBox = New-Object System.Windows.Forms.TextBox
$inpBox.Width = 200
$inpBox.Height = 25
$inpBox.PasswordChar = "*"
$inpBox.Text = "********"
$inpBox.Location = New-Object System.Drawing.Point(10, 35)
# create an OK Button
$inpBtn = New-Object System.Windows.Forms.Button
$inpBtn.Width = 60
$inpBtn.Height = 25
$inpBtn.Text = "OK"
$inpBtn.Location = New-Object System.Drawing.Point(250,33)
$form.AcceptButton = $inpBtn
$inpForm.Controls.AddRange(#($inpLbl, $inpBox, $inpBtn))
# OK-Button - Click event
$inpBtn.Add_Click({
$inpForm.Close()
return $inpBox.Text
})
$inpForm.ShowDialog()
}
# MAIN
$PW = InputForm (Get-WMIObject -ClassName Win32_ComputerSystem).Username
write-host $PW
The problem is with this last part of your function:
$inpBtn.Add_Click({
$inpForm.Close()
return $inpBox.Text
})
$inpForm.ShowDialog()
Instead of registering a custom handler for the Click event, you'll want to assign a value to the DialogResult property on the button - then inspect that result and return the value of the textbox from the function:
$inpBtn.DialogResult = 'OK'
if($inpForm.ShowDialog() -eq 'OK'){
return $inpBox.Text
}
else {
throw "User canceled password prompt!"
}

Create AD user in a different domain

I created a series of scripts for creating domain users. Since every domain where we create users requires different parameters and conditions, I have one script for each domain. But in case of one domain I have a problem. For this domain the manual procedure is like this:
1) open dsa.msc
2) connect to the "xyz" domain (the user is being created from a server in "abc" domain)
3) Create the user (operation for 10 to 15 minutes, that's why I created the scripts)
Unfortunately, when I run my script, I get the error message, that "The server is unwilling to process the request" (That's the precise complete error message) during execution of New-ADUser cmdlet. I suppose the reason is the need to perform the step 2 in the procedure I described above. So I somehow need to simulate it in the script, but I have no idea how to do that.
This is how the command is defined:
$params = #{
'GivenName' = $First_name_val.Text
'Surname' = $Second_name_val.Text
'DisplayName' = $Display_name
'AccountPassword' = $password
'Path' = $Location_val.Text
'Name' = $User_name_val.Text
'CannotChangePassword' = $Cannot_chg_pass.Checked
'PasswordNeverExpires' = $Pass_not_expires.Checked
'ChangePasswordAtLogon' = $Must_chg_pass.Checked
'Enabled' = !($Account_disabled_val.Checked)
'Description' = $GECOS_val.Text
'Office' = "NA"
'OfficePhone' = "NA"
'Title' = $Job_Title_val.Text
'Department' = $Department_val.Text
'Company' = $Company_val.Text
'SamAccountName' = $User_name_val.Text
'UserPrincipalName' = $User_name_val.Text + "#woodplc.com"
'EmailAddress' = $Email_Address_val.Text
'PassThru' = $true
}
$New_user = New-ADUser #params
Definition of $User_name_val.Text is here:
#region Real name of the user
[void]$AD_user_creation.SuspendLayout()
$Display_name_lbl = New-Object system.Windows.Forms.Label
$Display_name_lbl.text = "User`'s real name"
$Display_name_lbl.AutoSize = $true
$Display_name_lbl.width = 25
$Display_name_lbl.height = 10
$Display_name_lbl.location = New-Object System.Drawing.Point(10,10)
$First_name_val = New-Object system.Windows.Forms.TextBox
$First_name_val.Text = "a."
$First_name_val.multiline = $false
$First_name_val.width = 120
$First_name_val.height = 20
$First_name_val.location = New-Object System.Drawing.Point(200,10)
$Second_name_val = New-Object system.Windows.Forms.TextBox
$Second_name_val.multiline = $false
$Second_name_val.width = 120
$Second_name_val.height = 20
$Second_name_val.location = New-Object System.Drawing.Point(330,10)
$Display_name_val = New-Object system.Windows.Forms.Label
$Display_name_val.Text = ""
$Display_name_val.width = 250
$Display_name_val.height = 20
$Display_name_val.location = New-Object System.Drawing.Point(200,40)
$showFullName = { $Display_name_val.Text = ($First_name_val.Text + "." + $Second_name_val.Text) }
[void]$Second_name_val.Add_Leave( { & $showFullName } )
[void]$First_name_val.Add_Leave( { & $showFullName } )
#endregion
#region User name of the user
$User_name_lbl = New-Object system.Windows.Forms.Label
$User_name_lbl.text = "User logon name"
$User_name_lbl.AutoSize = $true
$User_name_lbl.width = 25
$User_name_lbl.height = 10
$User_name_lbl.location = New-Object System.Drawing.Point(10,70)
$User_name_val = New-Object system.Windows.Forms.TextBox
$User_name_val.multiline = $false
$User_name_val.width = 250
$User_name_val.height = 20
$User_name_val.location = New-Object System.Drawing.Point(200,70)
$LogonName = {$User_name_val.Text = ($First_name_val.Text + "." + $Second_name_val.Text)}
[void]$Second_name_val.Add_Leave({& $LogonName})
[void]$First_name_val.Add_Leave({& $LogonName})
[void]$AD_user_creation.ResumeLayout()
#endregion
The error "The server is unwilling to process the request" means that some of your input values are invalid. For example, the OU you are providing could be invalid (maybe a space that shouldn't be there), or the SamAccountName might be too long or contain an invalid character, etc.
If you show the full command you are using I might be able to spot something.
If there was an issue connecting to the server or authenticating, then the error message would be different.

Checkboxes in powershell GUI not working as supposed to

I have a GUI created in powershell, which contains some checkboxes. Later in the script I use the values from the checkboxes to set parameters of a user account, but it seems the script doesn't take the values as intended. I mean, sometimes the account is created with correct values, sometimes not. I wasn't able to discover any pattern when it works and when not.
$Orig_exec_policy = Get-ExecutionPolicy
Set-ExecutionPolicy Bypass -Force
<# This form was created using POSHGUI.com a free online gui designer for PowerShell
.NAME
Untitled
#>
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
#region Window properties
$AD_user_creation = New-Object system.Windows.Forms.Form
$AD_user_creation.ClientSize = '480,740'
$AD_user_creation.text = "AD user creation - WG Mustang"
$AD_user_creation.TopMost = $false
#endregion
[void]$AD_user_creation.SuspendLayout()
#region Real name of the user
$Display_name_lbl = New-Object system.Windows.Forms.Label
$Display_name_lbl.text = "User`'s real name"
$Display_name_lbl.AutoSize = $true
$Display_name_lbl.width = 25
$Display_name_lbl.height = 10
$Display_name_lbl.location = New-Object System.Drawing.Point(10,10)
$First_name_val = New-Object system.Windows.Forms.TextBox
$First_name_val.multiline = $false
$First_name_val.width = 120
$First_name_val.height = 20
$First_name_val.location = New-Object System.Drawing.Point(200,10)
$Second_name_val = New-Object system.Windows.Forms.TextBox
$Second_name_val.multiline = $false
$Second_name_val.width = 120
$Second_name_val.height = 20
$Second_name_val.location = New-Object System.Drawing.Point(330,10)
$Display_name_val = New-Object system.Windows.Forms.Label
$Display_name_val.Text = ""
$Display_name_val.width = 250
$Display_name_val.height = 20
$Display_name_val.location = New-Object System.Drawing.Point(200,40)
#endregion
#region User name of the user
$User_name_lbl = New-Object system.Windows.Forms.Label
$User_name_lbl.text = "User logon name"
$User_name_lbl.AutoSize = $true
$User_name_lbl.width = 25
$User_name_lbl.height = 10
$User_name_lbl.location = New-Object System.Drawing.Point(10,70)
$User_name_val = New-Object system.Windows.Forms.TextBox
$User_name_val.multiline = $false
$User_name_val.width = 250
$User_name_val.height = 20
$User_name_val.location = New-Object System.Drawing.Point(200,70)
#endregion
#region Account password
$Password_lbl = New-Object system.Windows.Forms.Label
$Password_lbl.text = "Password"
$Password_lbl.AutoSize = $true
$Password_lbl.width = 25
$Password_lbl.height = 10
$Password_lbl.location = New-Object System.Drawing.Point(10,100)
$Password_ini_val = New-Object system.Windows.Forms.MaskedTextBox
$Password_ini_val.multiline = $false
$Password_ini_val.width = 250
$Password_ini_val.height = 20
$Password_ini_val.UseSystemPasswordChar = $true
$Password_ini_val.location = New-Object System.Drawing.Point(200,100)
$Password_conf_val = New-Object system.Windows.Forms.MaskedTextBox
$Password_conf_val.multiline = $false
$Password_conf_val.width = 250
$Password_conf_val.height = 20
$Password_conf_val.UseSystemPasswordChar = $true
$Password_conf_val.location = New-Object System.Drawing.Point(200,130)
#endregion
#region Location of the user
$Location_lbl = New-Object system.Windows.Forms.Label
$Location_lbl.text = "Location"
$Location_lbl.AutoSize = $true
$Location_lbl.width = 25
$Location_lbl.height = 10
$Location_lbl.location = New-Object System.Drawing.Point(10,160)
$Location_val = New-Object system.Windows.Forms.TextBox
$Location_val.multiline = $false
$Location_val.text = "OU=Users,OU=ADM,DC=Mustangeng,DC=com"
$Location_val.width = 250
$Location_val.height = 20
$Location_val.location = New-Object System.Drawing.Point(200,160)
#endregion
#region Checkboxes
$Must_chg_pass = New-Object system.Windows.Forms.CheckBox
$Must_chg_pass.text = "User must change password at next logon"
$Must_chg_pass.AutoSize = $false
$Must_chg_pass.width = 290
$Must_chg_pass.height = 20
$Must_chg_pass.location = New-Object System.Drawing.Point(200,190)
$Cannot_chg_pass = New-Object system.Windows.Forms.CheckBox
$Cannot_chg_pass.text = "User cannot change password"
$Cannot_chg_pass.AutoSize = $false
$Cannot_chg_pass.width = 250
$Cannot_chg_pass.height = 20
$Cannot_chg_pass.location = New-Object System.Drawing.Point(200,220)
$Cannot_chg_pass.Checked = $true
$Pass_not_expires = New-Object system.Windows.Forms.CheckBox
$Pass_not_expires.text = "Password never expires"
$Pass_not_expires.AutoSize = $false
$Pass_not_expires.width = 250
$Pass_not_expires.height = 20
$Pass_not_expires.location = New-Object System.Drawing.Point(200,250)
$Pass_not_expires.Checked = $true
$Account_disabled_val = New-Object system.Windows.Forms.CheckBox
$Account_disabled_val.text = "Account is active"
$Account_disabled_val.AutoSize = $false
$Account_disabled_val.width = 250
$Account_disabled_val.height = 20
$Account_disabled_val.location = New-Object System.Drawing.Point(200,280)
$Account_disabled_val.Checked = $false
#endregion
#region Description
$GECOS_lbl = New-Object system.Windows.Forms.Label
$GECOS_lbl.text = "Description"
$GECOS_lbl.AutoSize = $true
$GECOS_lbl.width = 25
$GECOS_lbl.height = 10
$GECOS_lbl.location = New-Object System.Drawing.Point(10,310)
$GECOS_val = New-Object system.Windows.Forms.TextBox
$GECOS_val.multiline = $false
$GECOS_val.width = 250
$GECOS_val.height = 20
$GECOS_val.location = New-Object System.Drawing.Point(200,310)
#endregion
#region Group membership
$ADGroups_lbl = New-Object system.Windows.Forms.Label
$ADGroups_lbl.text = "AD Groups"
$ADGroups_lbl.AutoSize = $true
$ADGroups_lbl.width = 25
$ADGroups_lbl.height = 10
$ADGroups_lbl.location = New-Object System.Drawing.Point(10,340)
$ADGroups_val = New-Object system.Windows.Forms.TextBox
$ADGroups_val.multiline = $true
$ADGroups_val.width = 250
$ADGroups_val.height = 160
$ADGroups_val.location = New-Object System.Drawing.Point(200,340)
#endregion
#region Additional attributes
$Ext_Attribute5_lbl = New-Object System.Windows.Forms.Label
$Ext_Attribute5_lbl.Text = "Extension Attribute5"
$Ext_Attribute5_lbl.AutoSize = $true
$Ext_Attribute5_lbl.Width = 25
$Ext_Attribute5_lbl.Height = 10
$Ext_Attribute5_lbl.Location = New-Object System.Drawing.Point(10,510)
$Ext_Attribute5_val = New-Object System.Windows.Forms.TextBox
$Ext_Attribute5_val.Text = "Company name"
$Ext_Attribute5_val.Multiline = $false
$Ext_Attribute5_val.Width = 250
$Ext_Attribute5_val.Height = 20
$Ext_Attribute5_val.Location = New-Object System.Drawing.Point(200,510)
$Ext_Attribute10_lbl = New-Object System.Windows.Forms.Label
$Ext_Attribute10_lbl.Text = "Extension Attribute10"
$Ext_Attribute10_lbl.AutoSize = $true
$Ext_Attribute10_lbl.Width = 25
$Ext_Attribute10_lbl.Height = 10
$Ext_Attribute10_lbl.Location = New-Object System.Drawing.Point(10,540)
$Ext_Attribute10_val = New-Object System.Windows.Forms.TextBox
$Ext_Attribute10_val.Text = "Region"
$Ext_Attribute10_val.Multiline = $false
$Ext_Attribute10_val.Width = 250
$Ext_Attribute10_val.Height = 20
$Ext_Attribute10_val.Location = New-Object System.Drawing.Point(200,540)
$Ext_Attribute15_lbl = New-Object System.Windows.Forms.Label
$Ext_Attribute15_lbl.Text = "Extension Attribute15"
$Ext_Attribute15_lbl.AutoSize = $true
$Ext_Attribute15_lbl.Width = 25
$Ext_Attribute15_lbl.Height = 10
$Ext_Attribute15_lbl.Location = New-Object System.Drawing.Point(10,570)
$Ext_Attribute15_val = New-Object System.Windows.Forms.TextBox
$Ext_Attribute15_val.Text = "EH/WH"
$Ext_Attribute15_val.Multiline = $false
$Ext_Attribute15_val.Width = 250
$Ext_Attribute15_val.Height = 20
$Ext_Attribute15_val.Location = New-Object System.Drawing.Point(200,570)
$Job_Title_lbl = New-Object System.Windows.Forms.Label
$Job_Title_lbl.Text = "Job title"
$Job_Title_lbl.AutoSize = $true
$Job_Title_lbl.Width = 25
$Job_Title_lbl.Height = 10
$Job_Title_lbl.Location = New-Object System.Drawing.Point(10,600)
$Job_Title_val = New-Object System.Windows.Forms.TextBox
$Job_Title_val.Text = "NA"
$Job_Title_val.Multiline = $false
$Job_Title_val.Width = 250
$Job_Title_val.Height = 20
$Job_Title_val.Location = New-Object System.Drawing.Point(200,600)
$Department_lbl = New-Object System.Windows.Forms.Label
$Department_lbl.Text = "Department"
$Department_lbl.AutoSize = $true
$Department_lbl.Width = 25
$Department_lbl.Height = 10
$Department_lbl.Location = New-Object System.Drawing.Point(10,630)
$Department_val = New-Object System.Windows.Forms.TextBox
$Department_val.Text = "NA"
$Department_val.Multiline = $false
$Department_val.Width = 250
$Department_val.Height = 20
$Department_val.Location = New-Object System.Drawing.Point(200,630)
$Company_lbl = New-Object System.Windows.Forms.Label
$Company_lbl.Text = "Company"
$Company_lbl.AutoSize = $true
$Company_lbl.Width = 25
$Company_lbl.Height = 10
$Company_lbl.Location = New-Object System.Drawing.Point(10,660)
$Company_val = New-Object System.Windows.Forms.TextBox
$Company_val.Text = "IBM"
$Company_val.Multiline = $false
$Company_val.Width = 250
$Company_val.Height = 20
$Company_val.Location = New-Object System.Drawing.Point(200,660)
#endregion
#region Buttons
$Confirm_Button = New-Object system.Windows.Forms.Button
$Confirm_Button.BackColor = "#00ff00"
$Confirm_Button.text = "OK"
$Confirm_Button.width = 100
$Confirm_Button.height = 30
$Confirm_Button.location = New-Object System.Drawing.Point(200,690)
$Confirm_Button.Font = 'Microsoft Sans Serif,10,style=Bold'
$Create_ADuser = {
if ($Password_ini_val.Text -cne $Password_conf_val.Text)
{
[System.Windows.MessageBox]::Show("Passwords don't match")
} elseif ($Password_ini_val.Text.Length -lt 8)
{
[System.Windows.MessageBox]::Show("Password is too short")
} else {
$password = $Password_ini_val.Text | ConvertTo-SecureString -AsPlainText -Force
$Display_name = $Display_name_val.Text + " [ADM]"
New-ADUser -GivenName $First_name_val.Text -Surname $Second_name_val.Text -DisplayName $Display_name -AccountPassword $password -Path $Location_val.Text -Name $User_name_val.Text`
-CannotChangePassword $Cannot_chg_pass.Checked -PasswordNeverExpires $Pass_not_expires.Checked -ChangePasswordAtLogon $Must_chg_pass.Checked -Enabled $Account_disabled_val.Checked`
-Description $GECOS_val.Text -OtherAttributes #{'ExtensionAttribute5' = $Ext_Attribute5_val.Text;'ExtensionAttribute9' = "People";'ExtensionAttribute10' = $Ext_Attribute10_val.Text;`
'ExtensionAttribute11' = "Other";'ExtensionAttribute12' = "No";'ExtensionAttribute14' = "NA";'ExtensionAttribute15' = $Ext_Attribute15_val.Text;'Division' = "WG Mustang"}`
-Office "NA" -OfficePhone "NA" -Title $Job_Title_val.Text -Department $Department_val.Text -Company $Company_val.Text -SamAccountName $User_name_val.Text -PassThru | `
Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
$AD_user_creation.Close()
}
}
$Confirm_Button.add_Click($Create_ADuser)
$Cancel_button = New-Object system.Windows.Forms.Button
$Cancel_button.BackColor = "#ff0000"
$Cancel_button.text = "Cancel"
$Cancel_button.width = 100
$Cancel_button.height = 30
$Cancel_button.location = New-Object System.Drawing.Point(350,690)
$Cancel_button.Font = 'Microsoft Sans Serif,10,style=Bold'
<#$Cancel = {
$AD_user_creation.Close()
exit
}#>
$Cancel_button.add_Click({
$AD_user_creation.Close()
exit
})
$AD_user_creation.AcceptButton = $Confirm_Button
$AD_user_creation.CancelButton = $Cancel_button
#endregion
$AD_user_creation.controls.AddRange(#($Display_name_lbl,$First_name_val,$Second_name_val,$User_name_lbl,$Display_name_val,$User_name_val,$Password_lbl,$Password_ini_val,$Password_conf_val,$Location_lbl,`
$Location_val,$Must_chg_pass,$Cannot_chg_pass,$Pass_not_expires,$Account_disabled_val,$GECOS_lbl,$GECOS_val,$ADGroups_lbl,$ADGroups_val,$Ext_Attribute5_lbl,$Ext_Attribute5_val,$Ext_Attribute10_lbl,`
$Ext_Attribute10_val,$Ext_Attribute15_lbl,$Ext_Attribute15_val,$Job_Title_lbl,$Job_Title_val,$Department_lbl,$Department_val,$Company_lbl,$Company_val,$Confirm_Button,$Cancel_button))
$showFullName = { $Display_name_val.Text = ($First_name_val.Text + " " + $Second_name_val.Text) }
[void]$Second_name_val.Add_Leave( { & $showFullName } )
[void]$First_name_val.Add_Leave( { & $showFullName } )
[void]$AD_user_creation.ResumeLayout()
$result = $AD_user_creation.ShowDialog()
[void]$AD_user_creation.Dispose()
Set-ExecutionPolicy $Orig_exec_policy -Force
Definitions of checkboxes start at the row 101 and user gets created at the rows 268-272.
The user sometimes gets created as active, sometimes as disabled. And once I notice that even the "user cannot change password" doesn't get checked in the account, even though the value in the form is set to True. I didn't notice any problems with the other checkboxes. Any idea what's happening?
I believe the error stems from the way you use the New-User cmdlet. That piece of code looks complicated enough to not see that there is at least one backtick in the wrong place.
Better use Splatting for this:
$params = #{
'GivenName' = $First_name_val.Text
'Surname' = $Second_name_val.Text
'DisplayName' = $Display_name
'AccountPassword' = $password
'Path' = $Location_val.Text
'Name' = $User_name_val.Text
'CannotChangePassword' = $Cannot_chg_pass.Checked
'PasswordNeverExpires' = $Pass_not_expires.Checked
'ChangePasswordAtLogon' = $Must_chg_pass.Checked
'Enabled' = $Account_disabled_val.Checked
'Description' = $GECOS_val.Text
'Office' = "NA"
'OfficePhone' = "NA"
'Title' = $Job_Title_val.Text
'Department' = $Department_val.Text
'Company' = $Company_val.Text
'SamAccountName' = $User_name_val.Text
'OtherAttributes' = #{'ExtensionAttribute5' = $Ext_Attribute5_val.Text
'ExtensionAttribute9' = "People"
'ExtensionAttribute10' = $Ext_Attribute10_val.Text
'ExtensionAttribute11' = "Other"
'ExtensionAttribute12' = "No"
'ExtensionAttribute14' = "NA"
'ExtensionAttribute15' = $Ext_Attribute15_val.Text
'Division' = "WG Mustang"}
'PassThru' = $true
}
$newUser = New-ADUser #params
if ($newUser) {
$newUser | Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
}
else {
[System.Windows.MessageBox]::Show("Error creating new user")
}

Can't get ComboBox text to appear correctly [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a script that will do the following:
Create a Form with 2 ComboBoxes and a Text Box for user entry
I populate ComboBox 1 and populate ComboBox 2 based on the selection from ComboBox 1. Another thing that partially works is I can get Text to appear on the form based on the selection of ComboBox 1.
My Challenges are challenges I have, by priority are:
Challenge 1:
How can I change the the text on the form doesn't update if I change the selection in ComboBox 1. selection in ComboBox 1?
Challenge 2: (linked to Challenge 1)
I am looking for a way to combing ComboBox 1 with ComboBox 2 with the Text Box
Example: Comp1-Tst-MyTst?
Challenge 3:
I'm looking to import a CSV file / OR using a Get-AD.... for the variables instead of hard coding in the script.
Challenge 4:
I'm struggling with adding an Icon to the form
Challenge 5:
I'd like to prevent the Ok Button from appearing until a Checkbox is checked
Here's the code I have:
# Below is one of the Array's I'm adding
$ADSites=#("S01","S02","S03")
$ADSiteS01=#("AAA","BBB","CCC")
$ADSiteS02=#("DDD","EEE","FFF")
$ADSiteS03=#("GGG","HHH","JJJ")
####################################################################################################
##### Create Combo Boxes
####################################################################################################
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(625,625)
$Form.FormBorderStyle = "FixedToolWindow"
$Combobox1 = New-Object System.Windows.Forms.Combobox
$Combobox1.Location = New-Object System.Drawing.Size(26,25)
$Combobox1.Size = New-Object System.Drawing.Size(105,20)
$Combobox1.items.AddRange($ADSites)
$combobox2 = New-Object System.Windows.Forms.Combobox
$combobox2.Location = New-Object System.Drawing.Size(143,25)
$combobox2.Size = New-Object System.Drawing.Size(105,20)
$textBoxFPS = New-Object System.Windows.Forms.TextBox
$textBoxFPS.Location = New-Object System.Drawing.Point(26,75)
$textBoxFPS.Size = New-Object System.Drawing.Size(165,20)
$form.Controls.Add($textBoxFPS)
$Form.Controls.Add($combobox1)
$Form.Controls.Add($combobox2)
################################################################################################
##### Create Text Box
################################################################################################
$textBoxFPS = New-Object System.Windows.Forms.TextBox
$textBoxFPS.Location = New-Object System.Drawing.Point(26,75)
$textBoxFPS.Size = New-Object System.Drawing.Size(165,20)
$form.Controls.Add($textBoxFPS)
################################################################################################
##### Add Labels for the Combo Boxes
###################################################################################################
$lbADSub = New-Object System.Windows.Forms.Label
$lbADSub.Text = "Select AD Site"; $lbADSub.Top = 5; $lbADSub.Left = 26; $lbADSub.Autosize = $true
$form.Controls.Add($lbADSub)
$lbDeptSub = New-Object System.Windows.Forms.Label
$lbDeptSub.Text = "Select Department"; $lbDeptSub.Top = 5; $lbDeptSub.Left = 143;
$lbDeptSub.Autosize = $true
$form.Controls.Add($lbDeptSub)
$lbFPSSub = New-Object System.Windows.Forms.Label
$lbFPSSub.Text = "Type in the Asset Tag"; $lbFPSSub.Top = 55; $lbFPSSub.Left = 26;
$lbFPSSub.Autosize = $true
$form.Controls.Add($lbFPSSub)
## CheckBox
$chkThis = New-Object Windows.Forms.checkbox
$chkThis.Text = "Verify New Computer Name" ; $chkThis.Left = 26; $chkThis.Top = 105;
$chkThis.AutoSize = $true
$chkThis.Checked = $false # set a default value
$form.Controls.Add($chkThis)
<#
$lbCompSub = New-Object System.Windows.Forms.Label
$lbCompSub.Text = "Verify Computer Name"; $lbCompSub.Top = 105; $lbCompSub.Left = 26;
$lbCompSub.Autosize = $true
$form.Controls.Add($lbCompSub)
#>
############################################################################################
##### Create Ok and Cancel Buttons
############################################################################################
$buttonPanel = New-Object Windows.Forms.Panel
$buttonPanel.Size = New-Object Drawing.Size #(400,40)
$buttonPanel.Dock = "Bottom"
## Creating the Ok Button
$okButton = New-Object Windows.Forms.Button
$okButton.Top = $cancelButton.Top ; $okButton.Left = $cancelButton.Left - $okButton.Width - 5
$okButton.Text = "Ok"
$okButton.DialogResult = "Ok"
$okButton.Anchor = "Left"
## Creating the Cancel Button
$cancelButton = New-Object Windows.Forms.Button
$cancelButton.Left = $buttonPanel.Height - $cancelButton.Height - 10; $cancelButton.Left = $buttonPanel.Width - $cancelButton.Width - 10
$cancelButton.Text = "Cancel"
$cancelButton.DialogResult = "Cancel"
$cancelButton.Anchor = "Right"
## Add the buttons to the button panel
$buttonPanel.Controls.Add($okButton)
$buttonPanel.Controls.Add($cancelButton)
## Add the button panel to the form
$form.Controls.Add($buttonPanel)
## Set Default actions for the buttons
$form.AcceptButton = $okButton # ENTER = Ok
$form.CancelButton = $cancelButton # ESCAPE = Cancel
##################################################################################################
##### Now we do stuff
##################################################################################################
# Populate Combobox 2 When Combobox 1 changes
$ComboBox1_SelectedIndexChanged= {
$combobox2.Items.Clear() # Clear the list
$combobox2.Text = $null # Clear the current entry
Switch ($ComboBox1.Text) {
"S01"{
$ADSiteS01 | ForEach {
$labelClub = New-Object System.Windows.Forms.Label
$labelClub.Location = New-Object System.Drawing.Point(20,200)
$labelClub.Size = New-Object System.Drawing.Size(280,20)
$labelClub.Text = "$($combobox1.SelectedItem)-"
$form.Controls.Add($labelClub)
$combobox2.Items.Add($_)
#$labelClub.Text = "$($combobox2.SelectedItem)-"
}
}
"S02"{
$ADSiteS02 | ForEach {
$labelClub = New-Object System.Windows.Forms.Label
$labelClub.Location = New-Object System.Drawing.Point(20,200)
$labelClub.Size = New-Object System.Drawing.Size(280,20)
$labelClub.Text = "$($combobox1.SelectedItem)-"
$form.Controls.Add($labelClub)
$combobox2.Items.Add($_)
}
}
"S03"{
$ADSiteS03 | ForEach {
$labelClub = New-Object System.Windows.Forms.Label
$labelClub.Location = New-Object System.Drawing.Point(20,200)
$labelClub.Size = New-Object System.Drawing.Size(280,20)
$labelClub.Text = "$($combobox1.SelectedItem)-"
$form.Controls.Add($labelClub)
$combobox2.Items.Add($_)
}
}
}
}
$ComboBox1.add_SelectedIndexChanged($ComboBox1_SelectedIndexChanged)
$Form.ShowDialog()
This should help you out on the combo box issue and the OK button:
# Below is one of the Array's I'm adding
$ADSites=#("S01","S02","S03")
$ADSiteS01=#("AAA","BBB","CCC")
$ADSiteS02=#("DDD","EEE","FFF")
$ADSiteS03=#("GGG","HHH","JJJ")
Add-Type -AssemblyName System.Windows.Forms
#
####################################################################################################
##### Create Combo Boxes
####################################################################################################
$Form = New-Object System.Windows.Forms.Form
$Form.Size = '625,625'
$Form.FormBorderStyle = "FixedToolWindow"
#
$Combobox1 = New-Object System.Windows.Forms.Combobox
$Combobox1.Location = '26,25'
$Combobox1.Size = '105,20'
$Combobox1.items.AddRange($ADSites)
#
$combobox2 = New-Object System.Windows.Forms.Combobox
$combobox2.Location = '143,25'
$combobox2.Size = '105,20'
#
#
$Form.Controls.Add($combobox1)
$Form.Controls.Add($combobox2)
################################################################################################
##### Create Text Box
################################################################################################
$textBoxFPS = New-Object System.Windows.Forms.TextBox
$textBoxFPS.Location = '26,75'
$textBoxFPS.Size = '165,20'
$textBoxFPS.Text = 'xx'
$form.Controls.Add($textBoxFPS)
################################################################################################
##### Add Labels for the Combo Boxes
###################################################################################################
$lbADSub = New-Object System.Windows.Forms.Label
$lbADSub.Text = "Select AD Site"; $lbADSub.Top = 5; $lbADSub.Left = 26; $lbADSub.Autosize = $true
$form.Controls.Add($lbADSub)
$lbDeptSub = New-Object System.Windows.Forms.Label
$lbDeptSub.Text = "Select Department"; $lbDeptSub.Top = 5; $lbDeptSub.Left = 143;
$lbDeptSub.Autosize = $true
$form.Controls.Add($lbDeptSub)
$lbFPSSub = New-Object System.Windows.Forms.Label
$lbFPSSub.Text = "Type in the Asset Tag"; $lbFPSSub.Top = 55; $lbFPSSub.Left = 26;
$lbFPSSub.Autosize = $true
$form.Controls.Add($lbFPSSub)
## CheckBox
$chkThis = New-Object Windows.Forms.checkbox
$chkThis.Text = "Verify New Computer Name" ; $chkThis.Left = 26; $chkThis.Top = 105;
$chkThis.AutoSize = $true
$chkThis.Checked = $false # set a default value
$form.Controls.Add($chkThis)
############################
# Label for choice selection
############################
$labelClub = New-Object System.Windows.Forms.Label
$labelClub.Location = '20,200'
$labelClub.Size = '280,20'
$labelClub.Text = "-"
$form.Controls.Add($labelClub)
<#
$lbCompSub = New-Object System.Windows.Forms.Label
$lbCompSub.Text = "Verify Computer Name"; $lbCompSub.Top = 105; $lbCompSub.Left = 26;
$lbCompSub.Autosize = $true
$form.Controls.Add($lbCompSub)
#>
############################################################################################
##### Create Ok and Cancel Buttons
############################################################################################
$buttonPanel = New-Object Windows.Forms.Panel
$buttonPanel.Size = New-Object Drawing.Size #(400,40)
$buttonPanel.Dock = "Bottom"
## Creating the Ok Button
$okButton = New-Object Windows.Forms.Button
$okButton.Top = $cancelButton.Top ; $okButton.Left = $cancelButton.Left - $okButton.Width - 5
$okButton.Text = "Ok"
$okButton.DialogResult = "Ok"
$okButton.Anchor = "Left"
$okButton.Enabled = $false
## Creating the Cancel Button
$cancelButton = New-Object Windows.Forms.Button
$cancelButton.Left = $buttonPanel.Height - $cancelButton.Height - 10; $cancelButton.Left = $buttonPanel.Width - $cancelButton.Width - 10
$cancelButton.Text = "Cancel"
$cancelButton.DialogResult = "Cancel"
$cancelButton.Anchor = "Right"
## Add the buttons to the button panel
$buttonPanel.Controls.Add($okButton)
$buttonPanel.Controls.Add($cancelButton)
## Add the button panel to the form
$form.Controls.Add($buttonPanel)
## Set Default actions for the buttons
$form.AcceptButton = $okButton # ENTER = Ok
$form.CancelButton = $cancelButton # ESCAPE = Cancel
##################################################################################################
##### Now we do stuff
##################################################################################################
# Populate Combobox 2 When Combobox 1 changes
$ComboBox1.add_SelectedIndexChanged({
$combobox2.Items.Clear() # Clear the list
$combobox2.Text = $null # Clear the current entry
Switch ($ComboBox1.Text) {
"S01"{
$ADSiteS01 | ForEach {
$combobox2.Items.Add($_)
}
}
"S02"{
$ADSiteS02 | ForEach {
$combobox2.Items.Add($_)
}
}
"S03"{
$ADSiteS03 | ForEach {
$combobox2.Items.Add($_)
}
}
}
$labelClub.Text = $combobox1.Text + "-" + $combobox2.Text + "-" + $textBoxFPS.Text
})
$ComboBox2.add_SelectedIndexChanged({
$labelClub.Text = $combobox1.Text + "-" + $combobox2.Text + "-" + $textBoxFPS.Text
})
$textBoxFPS.add_TextChanged({
$labelClub.Text = $combobox1.Text + "-" + $combobox2.Text + "-" + $textBoxFPS.Text
})
$chkThis.Add_CheckStateChanged({
If ($chkThis.Checked) {
$okButton.enabled = $true
}
Else {
$okButton.enabled = $false
}
})
$Form.ShowDialog()
If you use an AD cmdlet to retrieve site details into an object you should easily be able to populate lists from that object using the same method you have now.