After selecting an option from the drop down list ($RCVROption), when choosing an option from the list provided ($listBox), the $listBox.SelectedItems values are always Null. How do I get those values to assign to variable $x
This is the script I tried, my goal is to have the text from $listBox.SelectedItems to be used as a value that represents a file name, so that when you select an option from the list, and click OK, it runs that file.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
$form = New-Object System.Windows.Forms.Form
$form.Text = 'DMP Receiver Tail'
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(115,220)
$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(190,220)
$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(60,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Which Receiver Would You Like To Tail?:'
$form.Controls.Add($label)
$RCVROption = new-object System.Windows.Forms.combobox
$RCVROption.Location = new-object System.Drawing.Size(20,40)
$RCVROption.Size = new-object System.Drawing.Size(335,30)
[void] $RCVROption.Items.Add('Receiver 560')
[void] $RCVROption.Items.Add('Receiver 2560')
$RCVROption.tabIndex = '0'
$RCVROption.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList;
$RCVROption.add_SelectedValueChanged(
{
if($RCVROption.SelectedItem -eq 'Receiver 560')
{
$listBox = New-Object System.Windows.Forms.Listbox
$listBox.Location = New-Object System.Drawing.Point(40,100)
$listBox.Size = New-Object System.Drawing.Size(260,80)
$listBox.SelectionMode = 'MultiExtended'
[void] $listBox.Items.Add('DMP-560-Line1')
[void] $listBox.Items.Add('DMP-560-Line2')
[void] $listBox.Items.Add('DMP-560-Line3')
[void] $listBox.Items.Add('DMP-560-Line4')
[void] $listBox.Items.Add('DMP-560-Line5')
$form.Controls.Add($listBox)
}
ELSEIF($RCVROption.SelectedItem -eq 'Receiver 2560')
{
$listBox = New-Object System.Windows.Forms.Listbox
$listBox.Location = New-Object System.Drawing.Point(40,100)
$listBox.Size = New-Object System.Drawing.Size(260,80)
$listBox.SelectionMode = 'MultiExtended'
[void] $listBox.Items.Add('DMP-2560-Line1')
[void] $listBox.Items.Add('DMP-2560-Line2')
[void] $listBox.Items.Add('DMP-2560-Line3')
[void] $listBox.Items.Add('DMP-2560-Line4')
[void] $listBox.Items.Add('DMP-2560-Line5')
$form.Controls.Add($listBox)
}
}
)
$form.Controls.Add($RCVROption)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x = $listBox.SelectedItems
$Fpath = 'D:\Toolbar\On Call\DMP-Tail\' + $x + '.exe'
Start-process -filepath $FPath
$Fpath
}
Based on your code, I'm guessing you come from a C# background. PowerShell does something weird where it can normally reach outside of script block's scope {code in scriptblock} and use variables that already exist at the time the scriptblock is executed. But it can't easily create or add new variables in the parent/outer scope.
Your code is creating $listBox inside the $RCVROption.add_SelectedValueChanged({code in scriptblock}) event scriptblock, and adding it to the controls for the form, so it continues to exist in the form, but not at the global/script scope of the your code.
I've reworked your code in a format that I've been learning over the last year. Everything you had should still be there, only in a more condensed form. You don't have to use this format, but I personally really like it. How PowerShell converts things like "Cancel" into [System.Windows.Forms.DialogResult]::Cancel is a bit of a mistery to me, but this type of conversion seems very reliable.
This version of the code creates the $listBox prior to firing of the $RCVROption.add_SelectedValueChanged event, clears the items in $listBox, and then populates the ListBox with the new values. The values are in an array, and piped into the [void] $listBox.Items.Add($_) command, executing it once per item in the array.
using namespace System.Windows.Forms
using namespace System.Drawing
Set-StrictMode -Version 3.0
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[Application]::EnableVisualStyles()
$form = [Form]#{
Text = 'DMP Receiver Tail'
Size = "400,300"
StartPosition = 'CenterScreen'
Topmost = $true
}
$OKButton = [Button]#{
DialogResult = "OK"
Location = "115,220"
Size = "75,23"
Text = 'OK'
}
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = [Button]#{
DialogResult = "Cancel"
Location = "190,220"
Size = "75,23"
Text = 'Cancel'
}
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = [Label]#{
Location = "60,20"
Size = "280,20"
Text = 'Which Receiver Would You Like To Tail?:'
}
$form.Controls.Add($label)
$RCVROption = [ComboBox]#{
DropDownStyle = "DropDownList"
Location = "20,40"
Size = "335,30"
tabIndex = '0'
}
[void] $RCVROption.Items.Add('Receiver 560')
[void] $RCVROption.Items.Add('Receiver 2560')
$listBox = [Listbox]#{
Location = "40,100"
SelectionMode = 'MultiExtended'
Size = "260,80"
}
$form.Controls.Add($listBox)
$RCVROption.add_SelectedValueChanged({
if($RCVROption.SelectedItem -eq 'Receiver 560') {
$listBox.Items.Clear()
'DMP-560-Line1', 'DMP-560-Line2', 'DMP-560-Line3', 'DMP-560-Line4', 'DMP-560-Line5' | ForEach-Object {
[void] $listBox.Items.Add($_)
}
}
elseif($RCVROption.SelectedItem -eq 'Receiver 2560') {
$listBox.Items.Clear()
'DMP-2560-Line1', 'DMP-2560-Line2', 'DMP-2560-Line3', 'DMP-2560-Line4', 'DMP-2560-Line5' | ForEach-Object {
[void] $listBox.Items.Add($_)
}
}
})
$form.Controls.Add($RCVROption)
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
$x = $listBox.SelectedItems
$Fpath = 'D:\Toolbar\On Call\DMP-Tail\' + $x + '.exe'
Start-process -filepath $FPath
$Fpath
}
I want to monitor the date and time of a file. I wrote the code that do the job as I want but I can't reposition the gui window. I tried all I could find like "start-job" or create a new runspace but I don't get any results in richtextbox. Any suggestion is welcome.
$targetFile = "full path"
# Function - Add Text to RichTextBox
function Add-RichTextBox{
[CmdletBinding()]
param ($text)
#$richtextbox_output.Text += "`tCOMPUTERNAME: $ComputerName`n"
$richtext.Text += "$text"
$richtext.Text += "`n"
}
# Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Monitor script"
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$Font = New-Object System.Drawing.Font("Tahoma",11)
$Form.Font = $Font
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,40)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = (Get-Date).ToString()
$form.Controls.Add($label)
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Point(150,220)
$StartButton.Size = New-Object System.Drawing.Size(100,33)
$StartButton.Text = 'Start'
#$StartButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $StartButton
$form.Controls.Add($StartButton)
$StartButton.Add_click({
while($true){
$lastdate = Get-ChildItem $targetFile
$Date = $lastdate.LastAccessTime.ToString()
Add-RichTextBox "$date"
$richtext.SelectionStart = $richtext.TextLength
$richText.ScrollToCaret()
#$richtext.refresh()
#$form.refresh()
Start-sleep 30
}
})
## the Rich text box
$richtext = new-object System.Windows.Forms.RichTextBox
$richtext.Location = New-Object System.Drawing.Point(20,60)
$richtext.multiline = $true
$richtext.Name = "Results"
$richtext.text = "Results:`n"
$richtext.scrollbars = "Both"
$richtext.Height = 120
$richtext.width = 350
$richtext.font = new-object system.drawing.font "Lucida Console",10
$Form.controls.add($richtext)
$Form.Add_Shown({$Form.Activate()})
$form.ShowDialog()
Continuing from my comment to use a Timer on your form (if you absolutely do not want a FileSystemWatcher), here's how you can do that:
$targetFile = "D:\Test\blah.txt"
$lastAccessed = (Get-Date) # a variable to keep track of the last LastAccessTime of the file
# Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Monitor script"
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$Font = New-Object System.Drawing.Font("Tahoma",11)
$form.Font = $Font
# Label
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,40)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = (Get-Date).ToString()
$form.Controls.Add($label)
# Button
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Point(150,200)
$StartButton.Size = New-Object System.Drawing.Size(100,33)
$StartButton.Text = 'Start'
$form.Controls.Add($StartButton)
$StartButton.Add_click({
$timer.Enabled = $true
$timer.Start()
})
# RichTextBox
$richtext = New-Object System.Windows.Forms.RichTextBox
$richtext.Location = New-Object System.Drawing.Point(20,60)
$richtext.Multiline = $true
$richtext.Name = "Results"
$richtext.Text = "Results:`r`n"
$richtext.ScrollBars = "Both"
$richtext.Height = 120
$richtext.Width = 350
$richtext.Font = New-Object System.Drawing.Font "Lucida Console",10
$form.Controls.Add($richtext)
# Timer
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 30000 # 30 seconds
$timer.Enabled = $false # disabled at first
$timer.Add_Tick({
$file = Get-Item -Path $targetFile -ErrorAction SilentlyContinue
# if we can find the file and its last AccessedTime is not
# the same as we already stored in variable $lastAccessed
# use script-scoping here, so $script:lastAccessed instead of $lastAccessed
if ($file -and $file.LastAccessTime -gt $script:lastAccessed) {
$richtext.AppendText("$($file.LastAccessTime.ToString())`r`n")
$script:lastAccessed = $file.LastAccessTime # remember this new datetime
}
})
$form.ShowDialog()
# Important: Clean up
$timer.Stop()
$timer.Dispose()
$richtext.Dispose()
$form.Dispose()
I am working on a script and am stuck at an error I am getting. I wanted to see if anyone could point me in the right direction. Basically I want a user to search AD and generate a report in.CSV file of the users in a particular group. I will show the script and the error below. Any advice would be most welcome. I know it can be done better and cleaned up but for now, it works.
<#
.NOTES
===========================================================================
Created with: PowerShell
Created on: 6/8/2020 3:51 PM
Created by: William Christner
Organization: BCBSA
Filename: AD Group Report
===========================================================================
.DESCRIPTION
Search AD groups, create a .CSV report of users in the group.
#>
####################################################################
import-module ActiveDirectory
####################################################################
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Select AD Group'
$form.Size = New-Object System.Drawing.Size(350, 140)
$form.StartPosition = 'CenterScreen'
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(125, 50)
$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)
$okButton.add_Click({
######################################################################################################
$GroupName = "$textBox"
$Date = Get-Date -UFormat "%m.%d.%y_%H.%M"
$Members = Get-ADGroupMember -Identity $GroupName -Recursive | Select -ExpandProperty SAMAccountName
Foreach ($Name in $Members) {
Get-ADUser $Name -properties * | Select EmailAddress,SAMAccountName,DisplayName,OfficePhone,CanonicalName,Enabled |
Export-Csv -append C:\Reports\$($GroupName)_Membership_Detailed_$($Date).csv -NoTypeInformation -Encoding UTF8 }
})
#####################################################################################################################
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(225, 50)
$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(130, 20)
$label.Text = 'Please select AD Group:'
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(150, 15)
$textBox.Size = New-Object System.Drawing.Size(150, 40)
$form.Controls.Add($textBox)
$textbox.AutoCompleteSource = 'CustomSource'
$textbox.AutoCompleteMode = 'SuggestAppend'
$textbox.AutoCompleteCustomSource = $autocomplete
"awsarchitect",
"BHI",
"cc_support",
"Citrix",
"CyberArk",
"CyberArk_Admins",
"Datastage",
"DB2DBA",
"Distribution Groups",
"DS_Core_Security",
"DS_FEPSIU",
"ems-test",
"FAS_COLDFUSION_DEV",
"FEPBlue",
"FEPOC_MousePointer",
"FogOperations",
"GG_AcceletestAdmins",
"GG_AcceletestUsers",
"GG_Allow LinkedIn",
"GG_Allow_AWS",
"GG_Allow_Firewall_ERwin",
"GG_Allow_Firewall_Hyper-V",
"GG_Allow_Firewall_IBM_Websphere",
"GG_Allow_Firewall_Loadrunner",
"GG_Allow_Firewall_Mainframe",
"GG_Allow_Firewall_NEBA_FTP",
"GG_Allow_Firewall_nodejs",
"GG_Allow_Firewall_Observer_Platform",
"GG_Allow_Firewall_R_Selenium",
"GG_Allow_Firewall_Safeend_DPA",
"GG_Allow_Firewall_SoapUI",
"GG_Allow_Lockdown",
"GG_Allow_MS_Collab_Sites",
"GG_Allow_Skype",
"GG_Allow_Website_Menshealth",
"GG_Allow_Windows_GINA",
"GG_Allow_Wireless",
"GG_Ansible_Development",
"GG_ApplicationSupport_Users",
"gg_bcbsa_sp_audit",
"GG_BindAccounts",
"GG_Blackberry_SSP",
"GG_Chrome_NoPolicies",
"GG_Clearwell_Admin",
"GG_Container_Admins_Nonprod",
"GG_ContentDistributor",
"GG_Contingent",
"GG_Core_GPO",
"GG_Core_GPO_POC",
"GG_Core_Mid",
"GG_CredSSP_Vuln",
"GG_CTX_Allow_Shadow",
"GG_DEP_Disabled",
"GG_DevFep",
"GG_DriveMappings_Test_Group",
"GG_Dropbox ",
"GG_DUOAlerts",
"GG_eDiscovery_Collections",
"GG_EMS_Files",
"GG_EV_Client11_Pilot",
"GG_EV_Phase2_Pilot",
"GG_Exchange_CalendarAdmins",
"GG_Exchange_ISAdmin",
"GG_Exchange_JrAdmin",
"GG_Exchange_MidAdmin",
"GG_Exchange_PowerShell",
"GG_Exchange_SrAdmin",
"GG_Exchange_Training",
"GG_Extend_ScreenSaver",
"gg_fep_contingents",
"GG_FEP_PS_Admins",
"GG_FEP_SIU",
"GG_FEP_SIU_Legal",
"gg_fep_sr_staff",
"gg_fep_staff",
"GG_Firewall_Testing",
"GG_Firewall_Triage",
"GG_Foglight_Read",
"GG_Git-Admins",
"GG_Git-Users",
"GG_Google_Man",
"GG_Google_SU",
"GG_GPO-Arch",
"GG_IBC_SandBox",
"GG_IDN_Pilot",
"GG_Infosys",
"GG_iSight-SRM",
"GG_JumpServers",
"GG_L4CERT_Administrators",
"GG_Legal_Hold",
"GG_Legal_Hold_Pilot",
"GG_LocalProfileRedirect_CHG",
"GG_LocalProfileRedirect_MDC",
"GG_Lost_Devices",
"GG_LTDMailbox",
"GG_Microsoft_Patch_Alerts",
"GG_Mobile_Users_CHG",
"GG_Mobile_Users_Execs",
"GG_Mobile_Users_MDC",
"GG_MSP_Infosys",
"GG_MSP_TechMahindra",
"GG_MSP_UST",
"GG_No_WPAD",
"GG_NRS_Extracts_Access",
"GG_O365_Migration",
"GG_OneDrive_Pilot",
"GG_PeopleSoft_Testers",
"GG_Proxy_WPAD2",
"GG_RDM_ADMIN_NP",
"GG_RDM_Admin_p",
"GG_RDM_ALL",
"GG_RDM_APP_NP",
"GG_RDM_BDC",
"GG_RDM_BLUE2",
"GG_RDM_IPDS",
"GG_RDM_ITS",
"GG_RDM_LDLA",
"GG_RDM_PDSU",
"GG_RDM_TREATMENT_CATEGORY",
"GG_RDM_USER_NP",
"GG_RDM_User_p",
"GG_RDM_WEB_SERVICES",
"GG_RDP_Users ",
"GG_RecordPoint365_Admins",
"GG_Remove_ScreenSaver",
"GG_RMS_SuperUsers",
"GG_Screensaver_Blank",
"GG_Screensaver_Presentations",
"GG_Screensaver_Windows10_Lockscreen",
"GG_SIEM_Log_Captures",
"GG_SIEM_Log_Captures_CHG",
"GG_SIEM_Log_Captures_MDC",
"GG_SIEM_Log_Captures_NGS",
"GG_SIEM_Log_Captures_Rollback",
"GG_StaffNow",
"GG_StateAffairs",
"GG_Tableau_Admin ",
"GG_UC_VMware_Admin",
"GG_VDI_Application_Permissions",
"GG_VDI_PEOPLESOFT_REPORTING-FEPprd",
"GG_VDIDesktopSupport",
"GG_Web_Servers",
"GG_WebEx_Users",
"GG_Windows10_GPO_Testing",
"GG_Windows10_Users",
"GG_Wireless_Profile_Testers",
"GG_Wireless_Testers",
"HPE_IRS",
"Hyperion-Users",
"HyperV_Servers",
"Informatica",
"JohnsAwesomeGPOTestingGroup",
"mongo_nw_pe",
"mongo_rw_dev",
"mongo_rw_pv",
"NetApp",
"NoOutlookNoIE",
"NOW_Upgrade_Temp12",
"O365",
"OKTA",
"Projects",
"QualityStage",
"sco",
"SCOM",
"SCVMM",
"SNOW_Upgrade_Temp_test",
"SNOW_Upgrade_Temp11",
"SNOW_Upgrade_Temp12",
"SNOW_Upgrade_Temp123",
"SNOW_Upgrade_Temp1256",
"SNOW_Upgrade_Temp132",
"SNOW_Upgrade_Temp145",
"SNOW_Upgrade_Temp2",
"SNOW_Upgrade_Temp3",
"SNOW_Upgrade_Temp33",
"SNOW_Upgrade_Temp444",
"SNOW_Upgrade_Temp555",
"SNOW_Upgrade_Temp888",
"Specopshe",
"SUG_FlashPlayerPilot",
"SystemCenter",
"Tower",
"UCSD",
"VCO-Admin",
"VMware"| % { $textbox.AutoCompleteCustomSource.AddRange($_) }
#[void]$listBox.Items.Add('atl-dc-001')
$form.Controls.Add($listBox)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x = $listBox.SelectedItem
$x
}
The error I am getting is as follows:
Looks like it is not seeing the Group in the Domain however when I run the same script it dose work by itself and created the report. I am thinking there is something missing from the textbox input and the rest of the script.
Thanks again for taking a look.
Cheers
You'll want to grab the textbox value from it's Text property:
$GroupName = $textBox.Text
I am a very new to powershell. I was tasked with creating a GUI that takes in several strings from multiple drop-downs and renames the computer according to those choices. I am testing it with two options, $FacilityInitials and $BuildingNumber. Powershell is returning only the $BuildingNumber choice.
I may be doing something wrong with returning? How should I do multiple return fuctions properly? Thank you! :)
I tried checking for typos.
#Edit This item to change the DropDown Values
[array]$DropDownArray1 = "LI", "BE", "HA"
# This Function Returns the Selected Value and Closes the Form
function Return-DropDown {
$script:Choice = $DropDown1.SelectedItem.ToString()
$Form.Close()
}
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.width = 350
$Form.height = 200
$Form.Text = ”Computer Renamer”
$DropDown1 = new-object System.Windows.Forms.ComboBox
$DropDown1.Location = new-object System.Drawing.Size(100,30)
$DropDown1.Size = new-object System.Drawing.Size(130,30)
ForEach ($Item in $DropDownArray1) {
[void] $DropDown1.Items.Add($Item)
}
$Form.Controls.Add($DropDown1)
$DropDown1Label = new-object System.Windows.Forms.Label
$DropDown1Label.Location = new-object System.Drawing.Size(10,30)
$DropDown1Label.size = new-object System.Drawing.Size(100,20)
$DropDown1Label.Text = "Facility Initials:"
$Form.Controls.Add($DropDown1Label)
################################################################################
#Edit This item to change the DropDown Values
[array]$DropDownArray2 = "01", "02", "03"
# This Function Returns the Selected Value and Closes the Form
function Return-DropDown {
$script:Choice2 = $DropDown2.SelectedItem.ToString()
$Form.Close()
}
$DropDown2 = new-object System.Windows.Forms.ComboBox
$DropDown2.Location = new-object System.Drawing.Size(100,60)
$DropDown2.Size = new-object System.Drawing.Size(130,30)
ForEach ($Item in $DropDownArray2) {
[void] $DropDown2.Items.Add($Item)
}
$Form.Controls.Add($DropDown2)
$DropDown2Label = new-object System.Windows.Forms.Label
$DropDown2Label.Location = new-object System.Drawing.Size(10,60)
$DropDown2Label.size = new-object System.Drawing.Size(100,20)
$DropDown2Label.Text = "Building Number:"
$Form.Controls.Add($DropDown2Label)
################################################################################
#Button
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(100,130)
$Button.Size = new-object System.Drawing.Size(150,20)
$Button.Text = "Rename Computer"
$Button.Add_Click({Return-DropDown})
$form.Controls.Add($Button)
################################################################################
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
$FacilityInitials = $Choice
$BuildingNumber = $Choice2
$newCompName = $FacilityInitials + "-" + $BuildingNumber
$AdminAcc = ""
#Add Restart and Force later
Rename-Computer -NewName $newCompName -DomainCredential $AdminAcc
I have created a function that creates a specific UI element with text input forms. This form also has three buttons:
One is supposed to display the text inputs again to do the same function again.
Another is supposed to finish and close the UI, passing the text input into the variables.
The last is supposed to cancel the UI element, doing nothing with anything in the text input forms.
Now I know the loop in the code isn't really complete, but I am having issues with it even performing the loop as well as passing the text forms into the variables. I know its something I am doing but it seems correct to me when I look at it.
Changed from an if loop, a while loop, and now a do/while loop.
Changed the position of the variables between the do section into the while section. Same for the if and while loops.
do {
ChangeDesc
}
while ($result -eq [System.Windows.Forms.DialogResult]::Retry)
{
$PC = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $HNInputBox.Text
$PC.Description = $DescInputBox.Text
$PC.Put()
}
ChangeDesc is the name of the function and works just as intended.
Expected to work is to loop the function 'ChangeDesc', and then when the 'Retry' or 'Ok' button is pressed, pass those forms to the variables as shown.
Currently, it will display the form, and when the 'Retry' button is pressed, the forms are passed properly and then the UI is closed out, the 'Ok' button does not pass any input and the 'Cancel' does the same thing.
Below is the rest of my lines of code for clarification.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
function ChangeDesc {
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Data Entry Form'
$form.Size = New-Object System.Drawing.Size(300,210)
$form.StartPosition = 'CenterScreen'
$AnotherButton = New-Object System.Windows.Forms.Button
$AnotherButton.Location = New-Object System.Drawing.Point(15,130)
$AnotherButton.Size = New-Object System.Drawing.Size(75,23)
$AnotherButton.Text = 'Another?'
$AnotherButton.DialogResult = [System.Windows.Forms.DialogResult]::Retry
$form.AcceptButton = $AnotherButton
$form.Controls.Add($AnotherButton)
$FinishedButton = New-Object System.Windows.Forms.Button
$FinishedButton.Location = New-Object System.Drawing.Point(100,130)
$FinishedButton.Size = New-Object System.Drawing.Size(75,23)
$FinishedButton.Text = 'Finished'
$FinishedButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.CancelButton = $FinishedButton
$form.Controls.Add($FinishedButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(185,130)
$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)
$HNLabel = New-Object System.Windows.Forms.Label
$HNLabel.Location = New-Object System.Drawing.Point(10,20)
$HNLabel.Size = New-Object System.Drawing.Size(280,20)
$HNLabel.Text = 'Enter Host Name:'
$form.Controls.Add($HNLabel)
$HNInputBox = New-Object System.Windows.Forms.TextBox
$HNInputBox.Location = New-Object System.Drawing.Point(10,40)
$HNInputBox.Size = New-Object System.Drawing.Size(260,20)
$form.Controls.Add($HNInputBox)
$DescLabel = New-Object System.Windows.Forms.Label
$DescLabel.Location = New-Object System.Drawing.Point(10,70)
$DescLabel.Size = New-Object System.Drawing.Size(280,20)
$DescLabel.Text = 'Enter Description:'
$form.Controls.Add($DescLabel)
$DescInputBox = New-Object System.Windows.Forms.TextBox
$DescInputBox.Location = New-Object System.Drawing.Point(10,90)
$DescInputBox.Size = New-Object System.Drawing.Size(260,20)
$form.Controls.Add($DescInputBox)
$form.Topmost = $true
$form.Add_Shown({$HNInputBox.Select()})
$result = $form.ShowDialog()
}
Your form is already closed when the loop terminates, and the variables you're trying to use are local to your function. Assign the values you're trying to use to script- or global-scope variables at the end of the function, and the code should do what you expect:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
function ChangeDesc {
$form = New-Object Windows.Forms.Form
...
$script:result = $form.ShowDialog()
$script:hostname = $HNInputBox.Text
$script:description = $DescInputBox.Text
}
do {
ChangeDesc
} while ($script:result -eq [Windows.Forms.DialogResult]::Retry)
$PC = Get-WmiObject Win32_OperatingSystem -Computer $script:hostname
$PC.Description = $script:description
$PC.Put()