* パイプライン入力 2 - ByPropertyName [#c9b2d75a]

** 概要 [#h7cbafb9]

 CommandletA | CommandletB

- PowerShellでパイプで値を渡す方法は2つある。ByValue と ByPropertyName。
- ByValueがデフォルトで、PowerShellはパイプからByValueな値がないか調べて、ない場合はByPropertyNameな値を調べる。どちらもない場合はエラーになる。
- ここではByPropertyNameについて説明する。

** 例 [#y50b813f]

 PS> dir A
  
 Mode       LastWriteTime  FileSize Name
 ----       -------------  -------- ----
 -a----  2018/07/10  9:08      0 B  1.txt
 -a----  2018/07/10  9:08      0 B  2.txt
 -a----  2018/07/10  9:08      0 B  3.txt

- Aというディレクトリに1.txtや2.txtなどがある。
- これらのtxtファイルと同じファイル名のファイルをカレントディレクトリにNew-Itemで作る場合を考える。

** dir Aがどんな値を出力するかGet-Memberで調べる [#r0eeaa09]

 PS> dir A | gm
 
 TypeName: System.IO.FileInfo

- 型がFileInfoなのがわかる。

*** New-Itemがどんなパイプライン入力を受け取るかHelpで調べる [#j9fc0e06]

 PS> help New-Item -Full
 
 構文
    New-Item [[-Path] <String[]>] [-Confirm] [-Credential <PSCredential>] [-Force] [-ItemType <String>] 
             -Name <String> [-UseTransaction] [-Value <Object>] [-WhatIf] [<CommonParameters>]
 
 -Name <String>
     Specifies the name of the new item.
 
     You can specify the name of the new item in the Name or Path parameter value, and you can specify the path of the new item in Name or Path value.
 
     必須                         true
     位置                         named
     既定値                       None
     パイプライン入力を許可する   True (ByPropertyName)
     ワイルドカード文字を許可する false

- Nameというプロパティ(型はString)をByPropertyNameで受け取ることがわかる。

*** dirが出力する値がどんなプロパティを持っているか、helpで調べる [#z9ed1693]

 PS> help dir -Full
 
 LastWriteTimeUtc          Property       datetime LastWriteTimeUtc {get;set;}
 Length                    Property       long Length {get;}
 Name                      Property       string Name {get;}

- dirが出力する値、つまりFileInfo型にNameプロパティが存在しているのがわかる。その型はString。よって、New-ItemのByPropertyNameに渡せる。

 PS> dir A\*.txt | New-Item
 PS> dir
 
 Mode       LastWriteTime  FileSize Name
 ----       -------------  -------- ----
 d-----  2018/07/10  9:08           A
 -a----  2018/07/10  9:14      0 B  1.txt
 -a----  2018/07/10  9:14      0 B  2.txt
 -a----  2018/07/10  9:14      0 B  3.txt

- したがって、このパイプ処理は正常に終了する。

** 参考 [#n0b806c2]

https://blogs.technet.microsoft.com/heyscriptingguy/2013/03/25/learn-about-using-powershell-value-binding-by-property-name/


トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS