[SOLVED]listbox send value different from shown value?

Tagged: 

This topic contains 6 replies, has 2 voices, and was last updated by Profile photo of cm it cm it 1 year, 8 months ago.

  • Author
    Posts
  • #32209
    Profile photo of cm it
    cm it
    Participant

    Hi,

    In HTML you can create a option-list and set the value to X and the text that is shown to the user to Y.

    http://www.w3schools.com/tags/tag_option.asp

    People select Volvo but value 1 is send to the database (or whatever).
    How do you do this in powershell?

    this is my whole script:

    cls
    [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Drawing”)
    [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
    
    #show organisationid's
    function Show-KayakoOrganizations(){    
    	[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
        $connection = New-Object MySql.Data.MySqlClient.MySqlConnection
        $connection.ConnectionString = ""
        $connection.Open()
    	$query = "Select userorganizationid,organizationname from users"
    
        $command = New-Object MySql.Data.MySqlClient.MySqlCommand($query, $connection)
        $dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($command)
        $dataSet = New-Object System.Data.DataSet
        $recordCount = $dataAdapter.Fill($dataSet, "data")
    	$id=@()
        $org=@()    
    
        foreach ($Row in $DataSet.Tables[0].Rows){
            $id += $Row.userorganizationid 
            $org += $Row.organizationname
        }  
        return $id,$org
    }
    
    $a,$b = Show-KayakoOrganizations
    
    $a #example = 1
    $b #example = Finance dep.
    
    $objForm = New-Object System.Windows.Forms.Form 
    $objForm.Text = "Select a department"
    $objForm.Size = New-Object System.Drawing.Size(300,600) 
    $objForm.StartPosition = "CenterScreen"
    
    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Size(75,12)
    $OKButton.Size = New-Object System.Drawing.Size(75,23)
    $OKButton.Text = "OK"
    
    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Size(150,12)
    $CancelButton.Size = New-Object System.Drawing.Size(75,23)
    $CancelButton.Text = "Cancel"
    
    $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $objForm.Controls.Add($OKButton)
    $objForm.AcceptButton = $OKButton
    
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $objForm.Controls.Add($CancelButton)
    $objForm.CancelButton = $CancelButton
    
    $objListBox = New-Object System.Windows.Forms.ListBox 
    $objListBox.Location = New-Object System.Drawing.Size(10,40) 
    $objListBox.Size = New-Object System.Drawing.Size(260,20) 
    $objListBox.Height = 550
    
    foreach($y in $a){
            $objListBox.Items.Add($y)   #Shows the ID (in the example : 1) 
    }
    
    $objForm.Controls.Add($objListBox) 
    $objForm.Topmost = $True
    
    $result = $objForm.ShowDialog()
    if ($result -eq [System.Windows.Forms.DialogResult]::OK -and $objListBox.SelectedIndex -ge 0){
        cls
        $selection = $objListBox.Text
        $selection
    }
    

    Can anyone help me?

  • #32215
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    You should use a hash table. Here is an example. Of course I had to put some fake data for your function to return, but it should show you how to handle what you need.

    cls
    [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Drawing”)
    [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
    
    #show organisationid's
    function Show-KayakoOrganizations(){    
        $Rows = @()
        $Rows += [PSCustomObject]@{'UserOrganizationId' = 1; 'OrganizationName' = 'Finance Dept.'}
        $Rows += [PSCustomObject]@{'UserOrganizationId' = 5; 'OrganizationName' = 'IT Dept.'}
        $Rows += [PSCustomObject]@{'UserOrganizationId' = 3; 'OrganizationName' = 'Maintenance Dept.'}
        $Rows += [PSCustomObject]@{'UserOrganizationId' = 6; 'OrganizationName' = 'Marketing Dept.'}
        foreach ($Row in $Rows){
            @{$Row.organizationname = $Row.userorganizationid}
        }
    }
    
    $a = Show-KayakoOrganizations
    
    $objForm = New-Object System.Windows.Forms.Form 
    $objForm.Text = "Select a department"
    $objForm.Size = New-Object System.Drawing.Size(300,600) 
    $objForm.StartPosition = "CenterScreen"
    
    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Size(75,12)
    $OKButton.Size = New-Object System.Drawing.Size(75,23)
    $OKButton.Text = "OK"
    
    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Size(150,12)
    $CancelButton.Size = New-Object System.Drawing.Size(75,23)
    $CancelButton.Text = "Cancel"
    
    $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $objForm.Controls.Add($OKButton)
    $objForm.AcceptButton = $OKButton
    
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $objForm.Controls.Add($CancelButton)
    $objForm.CancelButton = $CancelButton
    
    $objListBox = New-Object System.Windows.Forms.ListBox 
    $objListBox.Location = New-Object System.Drawing.Size(10,40) 
    $objListBox.Size = New-Object System.Drawing.Size(260,20) 
    $objListBox.Height = 550
    
    foreach($y in $a.keys){
            $objListBox.Items.Add($y)   #Shows the ID (in the example : 1)
    }
    
    $objForm.Controls.Add($objListBox)
    $objForm.Topmost = $True
    
    $result = $objForm.ShowDialog()
    if ($result -eq [System.Windows.Forms.DialogResult]::OK -and $objListBox.SelectedIndex -ge 0){
        cls
        $selection = $objListBox.Text
        $a.$selection
    }
    
  • #32220
    Profile photo of cm it
    cm it
    Participant

    @ Curtis Smith
    Thanks, the term "hash tables" in combination with your example made it easy to adjust my script to my needs.
    Here is my code, i hope it helps someone in the future.
    Please note that i'm note really a programmer, i'm a Windows Sysadmin that started with scripting in Powershell. Because my colleagues are not familiar with Powershell, i was asked to create a GUI. This is my first try and this list is just a part of my GUI.
    So please bare in mind that some parts might not be as performant as could be.

    Thanks again for the help!

    [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Drawing”)
    [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
    
    #show organisationid's
    function Show-KayakoOrganizations(){    
    	[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
        $connection = New-Object MySql.Data.MySqlClient.MySqlConnection
        $connection.ConnectionString = ""
        $connection.Open()
    	$query = "Select userorganizationid,organizationname from swuserorganizations order by organizationname asc"
    
        $command = New-Object MySql.Data.MySqlClient.MySqlCommand($query, $connection)
        $dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($command)
        $dataSet = New-Object System.Data.DataSet
        $recordCount = $dataAdapter.Fill($dataSet, "data")
    	
        $Rows = @()
        # loop trough dataset and create our Hash-table rows with each their key and value
        foreach ($line in $DataSet.Tables[0].Rows){
            $Rows += [PSCustomObject]@{'UserOrganizationId' = $line.userorganizationid; 'OrganizationName' = $line.organizationname}
            # bv : $Rows += [PSCustomObject]@{'UserOrganizationId' = "11"; 'OrganizationName' = "Dienst ICT"}
            #                                  ---   VALUES ---                     ---    KEY ----
        } 
           # loop trough the created hash-table values and actualy create its array $hash
          foreach ($Row in $Rows){
            $hash = @{$Row.organizationname = $Row.userorganizationid}
            $hash 
        } 
         
    }
    
    # $a is an object that holds the hash-table $hash from above. it has the properties (keys and values) which we can now select
    $a = Show-KayakoOrganizations
    
    
    $objForm = New-Object System.Windows.Forms.Form 
    $objForm.Text = "Select a department"
    $objForm.Size = New-Object System.Drawing.Size(300,600) 
    $objForm.StartPosition = "CenterScreen"
    
    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Size(75,12)
    $OKButton.Size = New-Object System.Drawing.Size(75,23)
    $OKButton.Text = "OK"
    
    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Size(150,12)
    $CancelButton.Size = New-Object System.Drawing.Size(75,23)
    $CancelButton.Text = "Cancel"
    
    $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $objForm.Controls.Add($OKButton)
    $objForm.AcceptButton = $OKButton
    
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $objForm.Controls.Add($CancelButton)
    $objForm.CancelButton = $CancelButton
    
    $objListBox = New-Object System.Windows.Forms.ListBox 
    $objListBox.Location = New-Object System.Drawing.Size(10,40) 
    $objListBox.Size = New-Object System.Drawing.Size(260,20) 
    $objListBox.Height = 550
    
    foreach($key in $a.Keys){
            # loop trough the array with both key and values in, and select the key so that we can add it to the selectionlist
            # the key "DIENST ICT" is shown in the list, but actually holds value "11"
            $objListBox.Items.Add($key)
    }
    
    $objForm.Controls.Add($objListBox) #add the list to the screen
    
    $result = $objForm.ShowDialog()
    # if OK is pressed and a selection was made
    if ($result -eq [System.Windows.Forms.DialogResult]::OK -and $objListBox.SelectedIndex -ge 0){
        
        clear-host    
        Write-host "key" $objListBox.Text #Outputs the Key (we made the key the text of the listboxItems)
        
        write-host "value" $a.$selection #Outputs the value linked to the selected key its the same as write-output $a."HR" or $a."Dienst ICT"
        
        $a."HR"
        $selection
    }
    
  • #32225
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    @cm-it, glad to help. I too am an admin by profession. Being able to use PowerShell will make you a much more valuable employee. I started my scripting journey with BATCH files, and over the years have used many different languages: Unix shell scripts, VBScript, JavaScript, etc, etc and now PowerShell. Being able to automate tasks is invaluable to your company. Good luck on developing this skill set and becoming a rock star in your Organization.

  • #32242
    Profile photo of cm it
    cm it
    Participant

    @Curtis Smith

    Well i studied webdev back in '05. So i was pretty good at PHP/Javascript/CSS/... .
    I know some VBscript and have written some scripts in the past. But a few months back we had a very calm month at work, so i decided that each free time i had, i would use to learn Powershell.
    I got me the book "Powershell in a month of lunches" and got started. I have read 2/3th of the book and decided to write some scripts.

    My colleagues were enthusiastic about how much time i saved with the scripts, but the older ones are not at all familiar with Poweshell. So they asked if i could create a GUI.

    I must say that i don't really like making GUI. It reminds me of my HTML training days, having to write each and every item of the GUI by hand.
    I had drawn it in Visual Studio and parsed he XAML, but for some reason i can't find a solution to the following problem:

    Creating this GUI has very little to do with actual scripting (at least in my view).
    I have the feeling i'm writing more C#/VB in the code than i do PS.
    Maybe if i could use the "modern" way (Visual Studio and XAML) i might like it more :).

    Thanks again

  • #32254
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    Ya, GUIs are much easier to write using another GUI. A Development environment. If you have not already looked at it, check out https://www.sapien.com. PowerShell Studio has excellent tools for developing PowerShell GUIs. If your company really likes what you are doing with PowerShell, then they should be willing to get you a proper development environment.

  • #32294
    Profile photo of cm it
    cm it
    Participant

    Yeah, i came across sapien GUi multiple times.
    Unfortunately my employer won't be financing this in the immediate future.
    I've searched for the community version (which is now cancelled, but i looked for the old version). But i had no luck in finding this 🙁

    I'm not expected to create GUI's or to know Powershell at all. Its just that if i have some spare time @ the job, i hate wasting it on reading the newspaper, so i look for things to learn. Powershell for me is the ideal solution. It's not programming like developping a website, which takes a lot of time before you actually have something great. With Powershell i can automate my work with relatively little effort.

    Now i'm only a "noob" in PS but i've done some fun stuff:

    Script that gets the username from a txt and than queried AD for the fullname (used for mailmerge in word)
    wrote a script to auto delete schedueled task from computers in txt when they come online. Script would be running during working hours. If one computer is done, it would not be tried again. if all were done, the script would stop automatic.
    wrote a function that would open an access DB and input certain values that are asked for when a new employee starts (no longer do i need the gui from the intranet)
    wrote a script that will copy all security groups in AD from a user onto the new user along with deparment,PObox, ...
    wrote a script that will create a personal drive on the fileserver when a new employee starts. Also the NTFS ACL is adjusted accordingly.
    wrote several send-key functions so that i don't have to manually type my passwords all the time. But afterwards i found that AutoHotkey is better way to do it.
    fooled around with encryption strings and decrypting them. Found a good article about is http://www.mssqlnotes.es/powershell-two-methods-to-encrypt-and-decrypt-passwords/
    wrote a little function that would allow you to remotly adjust enegery-scheme's from other computers.
    wrote a script that would enable or disable proxy settings (for vpn users) afterwards expanded on that to disconnect from certain wifi and connect to another automatically (i know the SSID's).
    made a little script that queries SCCM collections
    made a script that runs trough all folders and subfolders and than copy's all files (not folders) into one main folder (it uses robocopy for the actual copying as it has a great logging function along with other great features).
    And last but not least, a wrote a function that would monitor a pdfcreator process on a certain server as it tends to get stuck every once in a while. It will warn me when it does.
    Created a GUI for creating a new user into our Kayako Helpdesk. It will retrieve all needed data from AD, you just have to choose the department to which the user will be added.

    And i'm sure i've done some other stuff i can't remember 🙂

You must be logged in to reply to this topic.