Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/ad416c54c78469dc6474 to your computer and use it in GitHub Desktop.
Save guitarrapc/ad416c54c78469dc6474 to your computer and use it in GitHub Desktop.
PowerShell のString評価の方法と罠
# PowerShell の String中への変数埋め込みってば罠だらけね!
# 例 に示す変数をString中に表示するには5つ方法がある
$hoge = @{hoge = "hoge"}
$fuga = "fuga"
#1. 直 (Property指定がだめ
"$hoge"
'$hoge'
"$hoge.hoge"
#2. ${} でくくる。これもプロパティ指定がだめ (in-line評価 => bash スタイル)
"${hoge}"
"${fuga}"
#3. $() でくくる。部分式扱いなので、先行評価、展開される
"$($hoge.hoge)"
#4. "{0}" -f オペレータでインデックス指定
"{0}" -f $hoge.hoge
#5. [String]::Format()
[String]::Format("{0}", $hoge.hoge)
# インデックス指定の注意
#これは評価できる
"{{0}}" -f $hoge.hoge
# 問題はこれ => {}の間に改行が挟まるとパースに失敗する。つまり、json 中への埋め込みが苦手
"{
{0}
}" -f $hoge.hoge
<#
Error formatting a string: Input string was not in a correct format..
At line:1 char:5
+ "{
+ ~~
+ CategoryInfo : InvalidOperation: ({
{0}
}:String) [], RuntimeException
+ FullyQualifiedErrorId : FormatError
#>
# 対応方法
# 1. 直を使う (但し、後ろの文字が変数の一部として評価される可能性が高いのでだめだめ)
# 2. $() 部分式を使う
# ただし インデックス指定のメリット、
# 1. 繰り返し利用時に何度も書かなくていい => "{0}-{1}-{0}" -f $hoge.hoge, $fuga
# 2. 変数の変更に強い => 途中で当てる変数を変更したり、順序の変更がインデックス指定なので容易
# 結論
# 機能としては部分式最強
# だが、スクリプトなど(変更が発生しえる場合)にはインデックス指定が楽。
# ワンライナーなど単純な時は直もあり。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment