Home > Enterprise >  Powershell: Output a search from a csv to a small gui
Powershell: Output a search from a csv to a small gui

Time:09-27

maybe one of you experts can help a complete newbie (I don't know if what I want is even feasible). Let's assume I have a CSV file with various data. (see csv_screenshot)enter image description here


As per your comment to empty the textbox when nothing (or just whitespace) has been entered, you could change the function to:

function search_csv {
    $searchThis = $textbox_Search.Text.Trim()
    # use $script: scoping here to reference the $csvData variable
    $data = $script:csvData | Where-Object {$_.Location -like "*$searchThis*"}
    if ([string]::IsNullOrWhiteSpace($searchThis)) {
        $output_TextBox.Clear()
    }
    elseif ($data) {
        $output_TextBox.Text = ($data | Format-List | Out-String).Trim()
    }
    else {
        $output_TextBox.Text = "Not found.."
    }
}

However, as postanote already commented, it would be much better to simply disable the search button and only enable it when something other that whitespace has been entered.

To do that, you need to add an eventhandler to the textbox:

$textbox_Search = New-Object System.Windows.Forms.TextBox
$textbox_Search.Location = New-Object System.Drawing.Size(195,50)
$textbox_Search.Size = New-Object System.Drawing.Size(266,37)
$textbox_Search.Add_TextChanged({
    # enable the button when there is at least one non-whitespace character present
    $button_Search.Enabled = $this.Text -match '\S'
    # or use
    # $button_Search.Enabled = (-not [string]::IsNullOrWhiteSpace($this.Text))
})
$search_csvtool.Controls.Add($textbox_Search)

And initialize the button to be disabled at startup:

$button_Search = New-Object System.Windows.Forms.Button
$button_Search.Location = New-Object System.Drawing.Size(195,80)
$button_Search.Size = New-Object System.Drawing.Size(266,24)
$button_Search.TextAlign = "MiddleCenter"
$button_Search.Text = "Search"
# initialize to Disabled; will be enabled as soon as there is text entered in the $textbox_Search
$button_Search.Enabled = $false  
$button_Search.Add_Click({search_csv})
$search_csvtool.Controls.Add($button_Search)

Inside an event handler, you can refer to the object itself using automatic variable $this

  • Related