Этот полезный пример взят из книги "Windows Powershell in Action".
Сама книга, а также все примеры кода можно взять на офсайте:
http://
www.manning.com/payette/
$global:_ClassTable = @{}
function global:_NewInstance ( [scriptblock]$definition )
{
function ElementSyntax ( $msg )
{
throw "class element syntax: $msg"
}
function Note ( [string]$name, $value )
{
if ( ! $name )
{
elementSyntax "note name <value>"
}
new-object Management.Automation.PSNoteProperty ( $name,
$value )
}
function Method ( [string]$name, [scriptblock]$script )
{
if ( ! $name )
{
elementSyntax "method name <value>"
}
new-object Management.Automation.PSScriptMethod ( $name,
$script )
}
$object= new-object Management.Automation.PSObject
$members= &$definition
foreach ( $member in $members )
{
if ( ! $member )
{
write-error "bad member $member"
}
else
{
$object.psobject.members.Add( $member )
}
}
$object
}
function global:NewClass
{
param( [string]$type, [scriptblock]$definition )
if ( $global:_ClassTable[$type] )
{
throw "type $type is already defined"
}
_NewInstance $definition > $null
$global:_ClassTable[$type] = $definition
}
function global:New ( [string]$type )
{
$definition = $_ClassTable[$type]
if ( ! $definition )
{
throw "$type is undefined"
}
_NewInstance $definition
}
function RemoveClass ( [string]$type )
{
$_ClassTable.Remove( $type )
}
Добавив эту функцию в профайл, можно определять классы в такой форме:
NewClass point {
note x 0
note y 0
method ToString {
"($($this.x), $($this.y))"
}
method Scale {
$this.x *= $args[0]
$this.y *= $args[0]
}
}
А использовать так:
PS C:\> $p = New point
PS C:\> $p.tostring()
(0, 0)
PS C:\> $p.x=2
PS C:\> $p.y=3
PS C:\> $p.tostring()
(2, 3)
PS C:\> $p.scale(3)
PS C:\> $p.tostring()
(6, 9)
PS C:\> "The point p is {0}" -f $p
The point p is (6, 9)