2009-11-13

WPF Button with click event using PowerShell

A WPF Button with a click event can basically be defined either programmatic or with XAML. The two examples below gives the same look and feel in both ways.

First the programmatic way:
function Show-pgmButton {
    $Window = New-Object System.Windows.Window
    $Window.Title="SQLAdmin"
    $Window.Height="250"
    $Window.Width="400"
   
    $Button = New-Object System.Windows.Controls.Button
    $Button.Height = 23
    $Button.Width = 100
    $Button.Margin = '12,12,0,0'
    $Button.VerticalAlignment = 'Top'
    $Button.HorizontalAlignment = 'Left'
    $Button.Content = "Don't click me!"
    $Button.add_Click({
        $Button.Content = 'Arrrgh!!!'
        Start-Process '\\Titanium\Musik'
    })
    $Grid = New-Object System.Windows.Controls.Grid
    $Grid.Children.Add( $Button )
   
    $Window.Content = $Grid
    [void]$Window.ShowDialog()
}

Then the XAML way:
function Show-xamlButton {
[xml]$XAML = @'
<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="SQLAdmin" Height="250" Width="400">
   <Grid>
      <Button Height="22" Width="100" Name="myButton" Content="Don't click me!" VerticalAlignment="Top" HorizontalAlignment="Left" />
   </Grid>
</Window>
'@

   $Reader = New-Object System.Xml.XmlNodeReader $XAML
   $Window = [System.Windows.Markup.XamlReader]::Load( $Reader )

   $myButton = $Window.FindName('myButton')
   $myButton.Add_Click({
      $myButton.Content = 'Arrrgh!!!'
      Start-Process '\\Titanium\musik'
   })

   [void]$Window.ShowDialog()
}

Autogenerated scriptheader

In my daily tasks I often use scripts generated by other scripts. Often T-SQL scripts generated by PowerShell scripts.
The descriptive header of such autogenerated scripts I like to contain some general informations like which scripts generated it, who did it, when was it done and on which computer was it done.

In short these line give some of the wanted data.
"Filename  : $($MyInvocation.InvocationName)"
"Date      : $($(Get-Date).ToUniversalTime().ToString('s')) UTC"
"User      : $([Security.Principal.WindowsIdentity]::GetCurrent().Name)"
"Computer  : $($env:COMPUTERNAME)`(.$($env:USERDNSDOMAIN)`)"