パイプライン入力 2 - ByPropertyName
概要
CommandletA | CommandletB
- PowerShellでパイプで値を渡す方法は2つある。ByValue と ByPropertyName。
- ByValueがデフォルトで、PowerShellはパイプからByValueな値がないか調べて、ない場合はByPropertyNameな値を調べる。どちらもない場合はエラーになる。
- ここではByPropertyNameについて説明する。
例
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で調べる
PS> dir A | gm
TypeName: System.IO.FileInfo
New-Itemがどんなパイプライン入力を受け取るかHelpで調べる
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で調べる
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
参考
https://blogs.technet.microsoft.com/heyscriptingguy/2013/03/25/learn-about-using-powershell-value-binding-by-property-name/