クラスについて
簡単な説明
クラスを使用して独自のカスタム型を作成する方法について説明します。
長い説明
PowerShell 5.0 では、クラスとその他のユーザー定義型を定義するための正式な構文が追加されています。 クラスを追加することで、開発者と IT プロフェッショナルは、幅広いユース ケースに PowerShell を採用できます。 これにより、PowerShell 成果物の開発が簡素化され、管理サーフェスのカバレッジが高速化されます。
クラス宣言は、実行時にオブジェクトのインスタンスを作成するために使用されるブループリントです。 クラスを定義する場合、クラス名は型の名前です。 たとえば、Device という名前のクラスを宣言し、Device の新しいインスタンスに変数$dev
を初期化する場合、 $dev
は Device 型のオブジェクトまたはインスタンスです。 Device の各インスタンスのプロパティには、異なる値を指定できます。
サポートされるシナリオ
- クラス、プロパティ、メソッド、継承などの使い慣れたオブジェクト指向プログラミング セマンティクスを使用して、PowerShell でカスタム型を定義します。
- PowerShell 言語を使用して型をデバッグします。
- 正式なメカニズムを使用して例外を生成して処理します。
- PowerShell 言語を使用して、DSC リソースとその関連する型を定義します。
構文
クラスは、次の構文を使用して宣言されます。
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 クラスを拡張して、デバイスの追加と削除を行います。
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 値が指定されます。 コンストラクターを定義すると、既定のパラメーターなしのコンストラクターは作成されません。 必要に応じて、パラメーターなしのコンストラクターをCreateします。
コンストラクターの基本的な構文
この例では、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 クラスは、プロパティ、既定のコンストラクター、およびインスタンスを初期化するためのコンストラクターで定義されています。
既定のコンストラクターは ブランド を 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
しています。両方とも クラスの拡張ですDevice
。ComputeServer
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
基底クラス コンストラクターの呼び出し
サブクラスから基底クラス コンストラクターを呼び出すには、キーワード (keyword)を追加します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
失敗します。