LoginSignup
4
2

More than 3 years have passed since last update.

Write-OutputでFormatした文字列を出力したいのだけど

Last updated at Posted at 2019-09-06

事の顛末

Write-OutputやWrite-Hostで書式化した文字列を簡単に指定したかったのだけれども、やり方がわからなかったのです。検索しても出てくるのは、String.Formatの書式指定方法やFormat-Tableの解説ばかり。仕方がないので、こういう風に書いてみた。

sample1.ps1
$weather = "a sunny"
Write-Output [String]::Format("It's {0} day.", $weather)

ちなみに、これだとちゃんと動かない。
出力される内容は、こうなってしまう。

[String]:: Format
It's {0} day. a sunny

PowerShellさんは、こんな感じに構文解釈してしまっているみたい。

Write-Output  [String]::Format  ("It's {0} day, $weather)
|---Method---|---1st param----|-----2nd param (array)----|

あきらめて、こう書いてた

sample2.ps1
$weather = "a sunny"
Write-Output ([String]::Format("It's {0} day.", $weather))

Write-Outputに引き渡す部分全体を( )でくくってあげれば、[String]::Format()が先に実行されるようなので、これでも一応動く。でも、こんなので終わりなことは無いハズだ。言語設計した人はもっとちゃんと考えているハズ。

結論

参考文献のところに挙げてある zaki-lknr さんのリンク先の記事で紹介されていたのを偶然見つけました。zaki-lknr さん、ありがとうございます!!!

conclusion.ps1
$weather = "a sunny"
Write-Output ("It's {0} day." -f $weather)

そうだよね、こういうのあるハズだよね。と思いつつ、Microsoft Docsの公式(?) Reference検索しても、解説ドキュメントにたどりつけないのだけれど。。。皆さん、こういうのどこで覚えてくるんでしょうか? 関心してしまいます。

参考文献

[PowerShell / Python]フォーマット文字列ざっくりまとめ

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2