Chapters/graphical-controllers-wpf/samples/Get-ServiceWPF.ps1

#requires -version 5.0

$form = New-Object System.Windows.Window
#define what it looks like
$form.Title = "Service Status"
$form.Height = 375
$form.Width = 750

$stack = New-object System.Windows.Controls.StackPanel

#create a label
$label = New-Object System.Windows.Controls.Label
$label.HorizontalAlignment = "Left"
$label.Content = "Enter a Computer name:"
#add to the stack
$stack.AddChild($label)

#create a text box
$TextBox = New-Object System.Windows.Controls.TextBox
$TextBox.Width = 130
$TextBox.HorizontalAlignment = "Left"
$TextBox.Text = "chi-p50"
#add to the stack
$stack.AddChild($TextBox)

$datagrid = New-Object System.Windows.Controls.DataGrid
$datagrid.HorizontalAlignment = "Center"
$datagrid.Height = 250
$datagrid.Width = 650
$datagrid.CanUserReorderColumns = $True
$datagrid.CanUserSortColumns = $True
$datagrid.CanUserResizeColumns = $True
$stack.AddChild($datagrid)

#create a grid control
$grid = New-Object System.Windows.Controls.Grid

#create a button
$btnOK = New-Object System.Windows.Controls.Button
$btnOK.Content = "_OK"
$btnOK.Width = 75
$btnOK.HorizontalAlignment = "Left"

#this will now work
$OK = {
    #verify computername was entered
    if ($textbox.text -notmatch "^\S+$") {
        Write-Warning "You must enter a computername"
    }
    else {
        Write-Host "Getting services from $($textbox.Text)" -ForegroundColor Green;
        $data = Get-CimInstance -ClassName Win32_Service -ComputerName $textbox.Text | 
        Select Name,Displayname,StartName,StartMode,State
        $datagrid.ItemsSource = $data
    }
}
#add an event handler
$btnOK.Add_click($OK)

#add to the stack
$grid.AddChild($btnOK)

#add a quit button
$btnQuit = New-object System.Windows.Controls.Button
$btnQuit.Content = "_Quit"
$btnQuit.Width = 75
$btnQuit.HorizontalAlignment = "right"

$btnQuit.Add_Click({$form.Close()})

$grid.AddChild($btnQuit)

$stack.AddChild($grid)
#add the stack to the form
$form.AddChild($stack)

#show the form
$form.ShowDialog() | Out-Null