I am trying to get my head around PowerShell Class best practices, and running into some confusion with a simple class to handle Balloon Tips.
Add-Type -assemblyName:System.Drawing
Add-Type -assemblyName:System.Windows.Forms
class PxMessage {
static [PxMessage] $instance
static $balloon
static $defaultIcon
static [PxMessage] GetInstance($processIcon) {
if ([PxMessage]::instance -eq $null) {
[PxMessage]::instance = [PxMessage]::new()
#[PxMessage]::balloon = [Windows.Forms.NotifyIcon]::new()
[PxMessage]::balloon = New-Object Windows.Forms.NotifyIcon
[PxMessage]::defaultIcon = $processIcon
}
return [PxMessage]::instance
}
[Void] SendMessage ([String]$title, [String]$message, [String]$messageIcon) {
[PxMessage]::balloon.icon = [PxMessage]::defaultIcon
[PxMessage]::balloon.balloonTipTitle = $title
[PxMessage]::balloon.balloonTipText = $message
[PxMessage]::balloon.balloonTipIcon = $messageIcon
[PxMessage]::balloon.visible = $true
[PxMessage]::balloon.ShowBalloonTip(0)
[PxMessage]::balloon.Dispose
}
}
$processIcon = [System.Drawing.Icon]::ExtractAssociatedIcon($(Get-Process -id:$PID | Select-Object -expandProperty:path))
$message = [PxMessage]::GetInstance($processIcon)
$message.SendMessage('Title', "$(Get-Date)", 'Info')
I have two questions:
1: Why does [PxMessage]::balloon = New-Object Windows.Forms.NotifyIcon work, but [PxMessage]::balloon = [Windows.Forms.NotifyIcon]::new() does not (Unable to find type error)? And does this suggest that using [Type]::new() is not yet fully supported, and for consistency sake I am better off using New-Object everywhere? Or at least everywhere in my own Classes?
2: I would like to type my properties & parameters, but I also get Unable to find type errors when I type the $balloon & $defaultIcon properties, or if I type the $processIcon parameter in the GetInstance method.
Obviously I can type Properties, even with my type being defined. So what is different about the two [System.Drawing] & [System.Windows.Forms], and is this a bug, or a feature? And are there other types that behave similarly?