PowerShellでスクリプトブロックを作成して実行する方法について紹介したいと思います。
スクリプトブロックとは?
まず、スクリプトブロックとは何か? ですが、ほかの言語で言うと匿名関数やラムダ式に相当するものです。
名前のない関数ともいえるでしょうか。
PowerShellにおいては中括弧 {} で囲まれたスクリプトコードに過ぎません。
たとえば
PS > 1..10 | foreach { Write-Host $_ }
と記述したときの、{ Write-Host $_ } はスクリプトブロックです。
スクリプトブロックを変数に代入する
スクリプトブロックは、変数に代入することもできます。
PS > $s = { $a * 3 }
上記は、変数$aを3倍するというスクリプトブロックを変数$sに代入したことになります。
スクリプトブロックを実行する
では、スクリプトブロックを実行するにはどうすれば良いでしょうか?
PS > $s
上記のように変数名を入力して[Enter]を押すだけでは実行数することができません。
スクリプトブロックを実行するには、下記のように &演算子を使用します。(&とスクリプトブロックが代入された変数との間にはスペースが必要です)
PS > $a =2 PS > & $s 6
次回、スクリプトブロックでのパラメータの受け取り方法について説明したいと思います。
Theme design by Jelle Druyts
Pick a theme: BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2 BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2
Powered by: newtelligence dasBlog 2.0.7226.0
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2009, HIRO
E-mail