簡単な説明
クラスを使用して独自のカスタム型を作成する方法について説明します。
長い説明
PowerShell 5.0 では、クラスやその他のユーザー定義型を定義するための正式な構文が追加されています。 クラスを追加することで、開発者や IT プロフェッショナルは、より広範なユース ケースに PowerShell を採用できます。 これにより、PowerShell アーティファクトの開発が簡素化され、管理サーフェスのカバレッジが加速されます。
クラス宣言は、実行時にオブジェクトのインスタンスを作成するために使用されるブループリントです。 クラスを定義する場合、クラス名は型の名前です。 たとえば、Device という名前のクラスを宣言し、$dev
の新しいインスタンスに 変数を初期化する場合、$dev
は Device 型オブジェクトまたはインスタンスです。
Device の各インスタンスのプロパティには、異なる値を指定できます。
サポートされているシナリオ
- PowerShellでカスタム型を定義するには、クラス、プロパティ、メソッド、継承など、使い慣れたオブジェクト指向プログラミングのセマンティクスを使用します。
- PowerShell 言語を使用して型をデバッグします。
- 正式なメカニズムを使用して例外を生成して処理します。
- DSC リソースとそれに関連付けられている型は、PowerShell 言語を使用して定義します。
構文
クラスは、次の構文を使用して宣言されます。
class <class-name> [: [<base-class>][,<interface-list]] {
[[<attribute>] [hidden] [static] <property-definition> ...]
[<class-name>([<constructor-argument-list>])
{<constructor-statement-list>} ...]
[[<attribute>] [hidden] [static] <method-definition> ...]
}
クラスは、次のいずれかの構文を使用してインスタンス化されます。
[$<variable-name> =] New-Object -TypeName <class-name> [
[-ArgumentList] <constructor-argument-list>]
[$<variable-name> =] [<class-name>]::new([<constructor-argument-list>])
注
[<class-name>]::new(
構文を使用する場合は、クラス名を角かっこで囲む必要があります。 角かっこは、PowerShell の型定義を示します。
構文と使用例
この例では、使用可能なクラスを作成するために必要な最小限の構文を示します。
class Device {
[string]$Brand
}
$dev = [Device]::new()
$dev.Brand = "Microsoft"
$dev
Brand
-----
Microsoft
クラスのプロパティ
プロパティは、クラス スコープで宣言された変数です。 プロパティは、任意の組み込み型または別のクラスのインスタンスにすることができます。 クラスには、プロパティの数に制限はありません。
単純なプロパティを持つサンプルクラス
class Device {
[string]$Brand
[string]$Model
[string]$VendorSku
}
$device = [Device]::new()
$device.Brand = "Microsoft"
$device.Model = "Surface Pro 4"
$device.VendorSku = "5072641000"
$device
Brand Model VendorSku
----- ----- ---------
Microsoft Surface Pro 4 5072641000
クラスプロパティの複合型の例
この例では、Device クラスを使用して空の Rack クラスを定義します。 この例に続く例では、ラックにデバイスを追加する方法と、事前にロードされたラックから開始する方法を示します。
class Device {
[string]$Brand
[string]$Model
[string]$VendorSku
}
class Rack {
[string]$Brand
[string]$Model
[string]$VendorSku
[string]$AssetId
[Device[]]$Devices = [Device[]]::new(8)
}
$rack = [Rack]::new()
$rack
Brand :
Model :
VendorSku :
AssetId :
Devices : {$null, $null, $null, $null...}
クラス メソッド
メソッドは、クラスが実行できるアクションを定義します。 メソッドは、入力データを提供するパラメータを取ることができます。 メソッドは出力を返すことができます。 メソッドによって返されるデータは、定義された任意のデータ型にすることができます。
プロパティとメソッドを持つ単純なクラスの例
Rack クラスを拡張して、デバイスを追加したり、 Rack クラスからデバイスを削除したりします。
class Device {
[string]$Brand
[string]$Model
[string]$VendorSku
[string]ToString(){
return ("{0}|{1}|{2}" -f $this.Brand, $this.Model, $this.VendorSku)
}
}
class Rack {
[int]$Slots = 8
[string]$Brand
[string]$Model
[string]$VendorSku
[string]$AssetId
[Device[]]$Devices = [Device[]]::new($this.Slots)
[void] AddDevice([Device]$dev, [int]$slot){
## Add argument validation logic here
$this.Devices[$slot] = $dev
}
[void]RemoveDevice([int]$slot){
## Add argument validation logic here
$this.Devices[$slot] = $null
}
[int[]] GetAvailableSlots(){
[int]$i = 0
return @($this.Devices.foreach{ if($_ -eq $null){$i}; $i++})
}
}
$rack = [Rack]::new()
$surface = [Device]::new()
$surface.Brand = "Microsoft"
$surface.Model = "Surface Pro 4"
$surface.VendorSku = "5072641000"
$rack.AddDevice($surface, 2)
$rack
$rack.GetAvailableSlots()
Slots : 8
Brand :
Model :
VendorSku :
AssetId :
Devices : {$null, $null, Microsoft|Surface Pro 4|5072641000, $null...}
0
1
3
4
5
6
7
クラスメソッドでの出力
メソッドには戻り値の型が定義されている必要があります。 メソッドが出力を返さない場合、出力タイプは [void]
にする必要があります。
クラス メソッドでは、 return
ステートメントで指定されているオブジェクトを除き、オブジェクトはパイプラインに送信されません。 コードからパイプラインに誤って出力されることはありません。
注
これは、PowerShell 関数が出力を処理する方法とは根本的に異なり、すべてがパイプラインに送信されます。
メソッドの出力
この例では、 return
ステートメントを除き、クラス メソッドからパイプラインへの偶発的な出力は示されていません。
class FunWithIntegers
{
[int[]]$Integers = 0..10
[int[]]GetOddIntegers(){
return $this.Integers.Where({ ($_ % 2) })
}
[void] GetEvenIntegers(){
# this following line doesn't go to the pipeline
$this.Integers.Where({ ($_ % 2) -eq 0})
}
[string]SayHello(){
# this following line doesn't go to the pipeline
"Good Morning"
# this line goes to the pipeline
return "Hello World"
}
}
$ints = [FunWithIntegers]::new()
$ints.GetOddIntegers()
$ints.GetEvenIntegers()
$ints.SayHello()
1
3
5
7
9
Hello World
コンストラクタ
コンストラクターを使用すると、クラスのインスタンスを作成するときに、既定値を設定し、オブジェクト ロジックを検証できます。 コンストラクターの名前はクラスと同じです。 コンストラクターは、新しいオブジェクトのデータ メンバーを初期化するための引数を持つ場合があります。
クラスには、0 個以上のコンストラクターを定義できます。 コンストラクターが定義されていない場合、クラスには既定のパラメーターなしのコンストラクターが指定されます。 このコンストラクターは、すべてのメンバーを既定値に初期化します。 オブジェクトの型と文字列には null 値が与えられます。 コンストラクターを定義すると、既定のパラメーターなしのコンストラクターは作成されません。 必要に応じて、パラメーターなしのコンストラクターを作成します。
コンストラクタの基本構文
この例では、Device クラスはプロパティとコンストラクターを使用して定義されています。 このクラスを使用するには、コンストラクタにリストされているパラメータの値を指定する必要があります。
class Device {
[string]$Brand
[string]$Model
[string]$VendorSku
Device(
[string]$b,
[string]$m,
[string]$vsk
){
$this.Brand = $b
$this.Model = $m
$this.VendorSku = $vsk
}
}
[Device]$surface = [Device]::new("Microsoft", "Surface Pro 4", "5072641000")
$surface
Brand Model VendorSku
----- ----- ---------
Microsoft Surface Pro 4 5072641000
複数のコンストラクターを使用する例
この例では、 Device クラスは、プロパティ、既定のコンストラクタ、およびインスタンスを初期化するコンストラクタを使用して定義されています。
デフォルトのコンストラクターは brand を Undefined に設定し、 model と vendor-sku に null 値を残します。
class Device {
[string]$Brand
[string]$Model
[string]$VendorSku
Device(){
$this.Brand = 'Undefined'
}
Device(
[string]$b,
[string]$m,
[string]$vsk
){
$this.Brand = $b
$this.Model = $m
$this.VendorSku = $vsk
}
}
[Device]$somedevice = [Device]::new()
[Device]$surface = [Device]::new("Microsoft", "Surface Pro 4", "5072641000")
$somedevice
$surface
Brand Model VendorSku
----- ----- ---------
Undefined
Microsoft Surface Pro 4 5072641000
非表示属性
hidden
属性は、プロパティまたはメソッドを目立たなくします。 プロパティまたはメソッドは引き続きユーザーからアクセスでき、オブジェクトが使用可能なすべてのスコープで使用できます。 非表示のメンバーは Get-Member
コマンドレットで非表示になり、クラス定義の外部でタブ補完や IntelliSense を使用して表示することはできません。
隠し属性の使用例
Rack オブジェクトが作成されると、デバイスのスロット数は固定値であり、いつでも変更することはできません。 この値は作成時に認識されます。
hidden属性を使用すると、開発者はスロットの数を非表示にし、ラックのサイズを意図せずに変更するのを防ぐことができます。
class Device {
[string]$Brand
[string]$Model
}
class Rack {
[int] hidden $Slots = 8
[string]$Brand
[string]$Model
[Device[]]$Devices = [Device[]]::new($this.Slots)
Rack ([string]$b, [string]$m, [int]$capacity){
## argument validation here
$this.Brand = $b
$this.Model = $m
$this.Slots = $capacity
## reset rack size to new capacity
$this.Devices = [Device[]]::new($this.Slots)
}
}
[Rack]$r1 = [Rack]::new("Microsoft", "Surface Pro 4", 16)
$r1
$r1.Devices.Length
$r1.Slots
Brand Model Devices
----- ----- -------
Microsoft Surface Pro 4 {$null, $null, $null, $null...}
16
16
Slots プロパティが出力に表示されない$r1
に注意してください。 ただし、サイズはコンストラクタによって変更されました。
静的属性
static
属性は、クラスに存在し、インスタンスを必要としないプロパティまたはメソッドを定義します。
クラスのインスタンス化に関係なく、静的プロパティは常に使用できます。 静的プロパティは、クラスのすべてのインスタンスで共有されます。 静的メソッドは常に使用できます。 すべての静的プロパティは、セッションスパン全体に対して有効です。
静的属性とメソッドの使用例
ここでインスタンス化されたラックがデータ センターに存在すると仮定します。 そのため、コード内のラックを追跡したいと考えています。
class Device {
[string]$Brand
[string]$Model
}
class Rack {
hidden [int] $Slots = 8
static [Rack[]]$InstalledRacks = @()
[string]$Brand
[string]$Model
[string]$AssetId
[Device[]]$Devices = [Device[]]::new($this.Slots)
Rack ([string]$b, [string]$m, [string]$id, [int]$capacity){
## argument validation here
$this.Brand = $b
$this.Model = $m
$this.AssetId = $id
$this.Slots = $capacity
## reset rack size to new capacity
$this.Devices = [Device[]]::new($this.Slots)
## add rack to installed racks
[Rack]::InstalledRacks += $this
}
static [void]PowerOffRacks(){
foreach ($rack in [Rack]::InstalledRacks) {
Write-Warning ("Turning off rack: " + ($rack.AssetId))
}
}
}
静的プロパティとメソッドのテストが存在する
PS> [Rack]::InstalledRacks.Length
0
PS> [Rack]::PowerOffRacks()
PS> (1..10) | ForEach-Object {
>> [Rack]::new("Adatum Corporation", "Standard-16",
>> $_.ToString("Std0000"), 16)
>> } > $null
PS> [Rack]::InstalledRacks.Length
10
PS> [Rack]::InstalledRacks[3]
Brand Model AssetId Devices
----- ----- ------- -------
Adatum Corporation Standard-16 Std0004 {$null, $null, $null, $null...}
PS> [Rack]::PowerOffRacks()
WARNING: Turning off rack: Std0001
WARNING: Turning off rack: Std0002
WARNING: Turning off rack: Std0003
WARNING: Turning off rack: Std0004
WARNING: Turning off rack: Std0005
WARNING: Turning off rack: Std0006
WARNING: Turning off rack: Std0007
WARNING: Turning off rack: Std0008
WARNING: Turning off rack: Std0009
WARNING: Turning off rack: Std0010
この例を実行するたびにラックの数が増えることに注意してください。
プロパティ検証属性
検証属性を使用すると、プロパティに指定された値が定義された要件を満たしていることをテストできます。 値が割り当てられた瞬間に検証がトリガーされます。 about_functions_advanced_parametersを参照してください。
検証属性の使用例
class Device {
[ValidateNotNullOrEmpty()][string]$Brand
[ValidateNotNullOrEmpty()][string]$Model
}
[Device]$dev = [Device]::new()
Write-Output "Testing dev"
$dev
$dev.Brand = ""
Testing dev
Brand Model
----- -----
Exception setting "Brand": "The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again."
At C:\tmp\Untitled-5.ps1:11 char:1
+ $dev.Brand = ""
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
PowerShell クラスでの継承
既存のクラスから派生する新しいクラスを作成することで、クラスを拡張できます。 派生クラスは、基本クラスのプロパティを継承します。 必要に応じて、メソッドとプロパティを追加またはオーバーライドできます。
PowerShell では、多重継承はサポートされていません。 クラスは、複数のクラスから継承することはできません。 ただし、その目的のためにインターフェイスを使用できます。
継承の実装は、 :
演算子によって定義されます。これは、このクラスを拡張するか、これらのインターフェイスを実装することを意味します。 派生クラスは、常にクラス宣言の左端に配置する必要があります。
単純な継承構文を使用した例
この例では、単純な PowerShell クラス継承構文を示しています。
Class Derived : Base {...}
この例では、基底クラスの後に来るインターフェイス宣言を使用した継承を示します。
Class Derived : Base.Interface {...}
PowerShell クラスでの単純な継承の例
この例では、前の例で使用した Rack クラスと Device クラスは、プロパティの繰り返しを回避し、共通のプロパティをより適切に配置し、共通のビジネス ロジックを再利用するように適切に定義されています。
データセンター内のほとんどのオブジェクトは会社の資産であるため、資産として追跡を開始するのは理にかなっています。 デバイスの種類は DeviceType
列挙によって定義され、列挙の詳細については about_Enum を参照してください。
この例では、Rack
クラスに対する ComputeServer
と Device
の両方の拡張を定義しています。
enum DeviceType {
Undefined = 0
Compute = 1
Storage = 2
Networking = 4
Communications = 8
Power = 16
Rack = 32
}
class Asset {
[string]$Brand
[string]$Model
}
class Device : Asset {
hidden [DeviceType]$devtype = [DeviceType]::Undefined
[string]$Status
[DeviceType] GetDeviceType(){
return $this.devtype
}
}
class ComputeServer : Device {
hidden [DeviceType]$devtype = [DeviceType]::Compute
[string]$ProcessorIdentifier
[string]$Hostname
}
class Rack : Device {
hidden [DeviceType]$devtype = [DeviceType]::Rack
hidden [int]$Slots = 8
[string]$Datacenter
[string]$Location
[Device[]]$Devices = [Device[]]::new($this.Slots)
Rack (){
## Just create the default rack with 8 slots
}
Rack ([int]$s){
## Add argument validation logic here
$this.Devices = [Device[]]::new($s)
}
[void] AddDevice([Device]$dev, [int]$slot){
## Add argument validation logic here
$this.Devices[$slot] = $dev
}
[void] RemoveDevice([int]$slot){
## Add argument validation logic here
$this.Devices[$slot] = $null
}
}
$FirstRack = [Rack]::new(16)
$FirstRack.Status = "Operational"
$FirstRack.Datacenter = "PNW"
$FirstRack.Location = "F03R02.J10"
(0..15).ForEach({
$ComputeServer = [ComputeServer]::new()
$ComputeServer.Brand = "Fabrikam, Inc." ## Inherited from Asset
$ComputeServer.Model = "Fbk5040" ## Inherited from Asset
$ComputeServer.Status = "Installed" ## Inherited from Device
$ComputeServer.ProcessorIdentifier = "x64" ## ComputeServer
$ComputeServer.Hostname = ("r1s" + $_.ToString("000")) ## ComputeServer
$FirstRack.AddDevice($ComputeServer, $_)
})
$FirstRack
$FirstRack.Devices
Datacenter : PNW
Location : F03R02.J10
Devices : {r1s000, r1s001, r1s002, r1s003...}
Status : Operational
Brand :
Model :
ProcessorIdentifier : x64
Hostname : r1s000
Status : Installed
Brand : Fabrikam, Inc.
Model : Fbk5040
ProcessorIdentifier : x64
Hostname : r1s001
Status : Installed
Brand : Fabrikam, Inc.
Model : Fbk5040
<... content truncated here for brevity ...>
ProcessorIdentifier : x64
Hostname : r1s015
Status : Installed
Brand : Fabrikam, Inc.
Model : Fbk5040
基本クラスのコンストラクタの呼び出し
サブクラスから基本クラスのコンストラクタを呼び出すには、 base
キーワードを追加します。
class Person {
[int]$Age
Person([int]$a)
{
$this.Age = $a
}
}
class Child : Person
{
[string]$School
Child([int]$a, [string]$s ) : base($a) {
$this.School = $s
}
}
[Child]$littleone = [Child]::new(10, "Silver Fir Elementary School")
$littleone.Age
10
基本クラスのメソッドを呼び出す
サブクラスの既存のメソッドをオーバーライドするには、同じ名前とシグネチャを使用してメソッドを宣言します。
class BaseClass
{
[int]days() {return 1}
}
class ChildClass1 : BaseClass
{
[int]days () {return 2}
}
[ChildClass1]::new().days()
2
オーバーライドされた実装から基底クラスのメソッドを呼び出すには、呼び出し時に基底クラス ([baseclass]$this) にキャストします。
class BaseClass
{
[int]days() {return 1}
}
class ChildClass1 : BaseClass
{
[int]days () {return 2}
[int]basedays() {return ([BaseClass]$this).days()}
}
[ChildClass1]::new().days()
[ChildClass1]::new().basedays()
2
1
インターフェイス
インターフェイスを宣言するための構文は C# と似ています。 インターフェイスは、基本型の後、または基本型が指定されていない場合はコロン (:
) の直後に宣言できます。 すべての型名はコンマで区切ります。
class MyComparable : system.IComparable
{
[int] CompareTo([object] $obj)
{
return 0;
}
}
class MyComparableBar : bar, system.IComparable
{
[int] CompareTo([object] $obj)
{
return 0;
}
}
PowerShell モジュールからのクラスのインポート
Import-Module
および #requires
ステートメントは、モジュールで定義されているモジュール関数、エイリアス、変数のみをインポートします。 クラスはインポートされません。
using module
ステートメントは、モジュールで定義されたクラスをインポートします。 モジュールが現在のセッションに読み込まれていない場合、 using
ステートメントは失敗します。