This is going to be a really short post due to the fact that after a conversation I had on Twitter, I decided that I’d share the Windows Forms template that I always start out with when I’m starting to work on a new tool. Since I’m not blessed with having a license for PowerShell Studios, I’ve developed my own template for creating PowerShell GUI’s based upon Windows Forms. In my opinion it’s quite slick and clean, following best practices and it’s easy to read. If you have any suggestions or question, write a comment or send me an email.

Windows Forms template

If you don’t have any use for the param block in your GUI, simply just remove those lines in the beginning. Although a lot of my GUI’s make use of the Get-WmiObject cmdlet which for ConfigMgr requires a Site Code. And to determine the Site Code, I normally determine that by providing the Primary Site server name as a parameter.

[CmdletBinding(SupportsShouldProcess=$true)]
param(
    [parameter(Mandatory=$true, HelpMessage="Specify the Primary Site server")]
    [ValidateNotNullOrEmpty()]
    [string]$SiteServer
)
Begin {
    # Assemblies
    try {
        Add-Type -AssemblyName "System.Drawing" -ErrorAction Stop
        Add-Type -AssemblyName "System.Windows.Forms" -ErrorAction Stop
    }
    catch [System.UnauthorizedAccessException] {
	    Write-Warning -Message "Access denied when attempting to load required assemblies" ; break
    }
    catch [System.Exception] {
	    Write-Warning -Message "Unable to load required assemblies. Error message: $($_.Exception.Message)" ; break
    }
}
Process {
    function Load-Form {
	    $Form.Add_Shown({$Form.Activate()})
	    $Form.ShowDialog()
    }

    # Forms
    $Form = New-Object System.Windows.Forms.Form    
    $Form.Size = New-Object System.Drawing.Size(350,100)  
    $Form.MinimumSize = New-Object System.Drawing.Size(350,100)
    $Form.MaximumSize = New-Object System.Drawing.Size(350,100)
    $Form.SizeGripStyle = "Hide"
    $Form.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($PSHome + "\powershell.exe")
    $Form.Text = "Header"
    $Form.ControlBox = $true
    $Form.TopMost = $true

    # Load Form
    Load-Form
}
Nickolaj Andersen
Principal Consultant and Enterprise Mobility MVP. Nickolaj has been in the IT industry for the past 10 years specializing in Enterprise Mobility and Security, Windows deployments and Automation. In 2015 Nickolaj was awarded as PowerShell Hero by the community for his script and tools contributions. Author of ConfigMgr Prerequisites Tool, ConfigMgr OSD FrontEnd, ConfigMgr WebService and a frequent speaker at user groups.

(57)

comments

Leave a Reply