今回はPowerShellでの変数宣言時の型の指定方法について説明します。
その前にちょっと実験をしてみたいと思います。
PS > $var = 3 PS > $var.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType
上記のように数値を代入すると、変数は数値型(ここではint)になります。
では、この数値型になった変数$varに文字列を代入するとどうなるでしょうか?
PS > $var ="Test" PS > $var.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object
文字列型(string)に変更されました。このようにPowerShellの変数は、そのとき代入されている値の型となります。
PowerShellではほかの言語のようにあらかじめ型を指定することができます。
変数にあらかじめ型を指定するには、[型]$変数名 とします。
次は int型の変数 $int を作成して、3を代入します。
[int]$int = 3
$intの型を確認してみると
PS > $int.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType
確かにint型になっていることを確認できます。
では、この$intへ文字列"Test"を代入しようとしたらどうでしょうか?
PS > $int = "Test" 値 "Test" を型 "System.Int32" に変換できません。エラー: "入力文字列の形式が正しくありませ ん。" 発生場所 行:1 文字:5 + $int <<<< = "Test"
このように、明示的に型を指定した場合には、その型以外のデータは代入できなくなります。
次回から演算子について説明していきたいと思います。
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