PowerShell Tips

PowerShellの基本

  • コマンドレット(Cmdlet) : “動詞-名詞” のペアで構成されたPowerShellコマンド

PowerShellを探索するための4つのコマンド

Get-Verb動詞の一覧
Get-Commandコマンドの一覧
Get-Memberコマンドで使用できるオブジェクト、プロパティ、メソッド
Get-Helpコマンドの詳細に関するヘルプページ
コマンドレットを知るための4コマンド

配列について

PowerShellの配列は、Javaのような配列の要素数を決めているものではなく、リストのように要素数の変更が可能なものになっている。Pythonのリストと同じような使い方が可能

配列の作成

PS /> $arry = @('John', 'Steve', 'Mark', 'Nick')
PS /> $arry
John
Steve
Mark
Nick
PS > 

PS /> $arry =@(
>> 'John'
>> 'Steve'
>> 'Mark'
>> 'Nick'
>> 
PS /> $arry    
John     
Steve     
Mark     
Nick     
PS /> 

 下段のような、複数に分けた記載が望ましい書き方とされている。※でも、行は増えちゃうんですが。。。

配列のインデックスとスライスのサポート

PS /> $arry[0]
John
PS /> $arr[1]  
Steve
PS /> $arry[-1]
Nick
PS /> $arry[-2]
Mark

PS /> $arry
John
Steve
Mark
Nick
PS /> $arry[1..3]   ※pythonの場合はコロン " : " 
Steve
Mark
Nick
PS /> 

配列の中身の数

PS /> $arry      
John
Steve
Mark
Nick
PS /> $arry.count  ※pythonなら、len(arry)
4
PS /> 

文字列はimmutable(不変体)

PS /> $string[2..4] = 3,4,5
InvalidOperation: Unable to index into an object of type "System.String".
PS /> $string[2..4] = 'C','D','E'
InvalidOperation: Unable to index into an object of type "System.String".
PS /> $string[2] = 'C'           
InvalidOperation: Unable to index into an object of type "System.String".

配列の結合、追加、変更

PS /> $first = @(      
>> 'John'
>> 'Steve'
>> )
PS /> $second = @(
>> 'Mark'
>> 'Nick'
>> )
PS /> $first + $second
John
Steve
Mark
Nick
PS /> $third = $first + $second
PS /> $third
John     
Steve
Mark
Nick

PS /> $third += 'Kent'
PS /> $third          
John
Steve
Mark
Nick
Kent

PS /> $third[5] = 'Rick'  ※リストの外を指定するとエラー発生する
OperationStopped: Index was outside the bounds of the array.
PS /> $third[4] = 'Rick'
PS /> $third            
John
Steve
Mark
Nick
Rick

厳密な型指定をした配列

PS /> [int[]] $numbers = 1,2,3
PS /> [int[]] $numbers2 = 'one','two','three'
MetadataError: Cannot convert value "one" to type "System.Int32". Error: "Input string was not in a correct format."

配列のネスト構造

PS /> $data = @(@(1,2,3),@(4,5,6),@(7,8,9))
PS /> 
PS /> $data2 = @(
>>     @(1,2,3),
>>     @(4,5,6),
>>     @(7,8,9)
>> )
PS /> 
PS /> $data
1
2
3
4
5
6
7
8
9
PS /> $data[0]
1
2
3
PS /> $data[0][2]
3
PS />