LoginSignup
0

More than 5 years have passed since last update.

Get-ChildItemの出力形式はパラメータによって変わるという話

Last updated at Posted at 2019-03-14

趣味でPowershellを触っているのですが、もっともよく使うコマンドレットのひとつであろうGet-ChildItemで最近得た知見がありました。-Name パラメータを使うと出力オブジェクトが変わるというものです。

オンラインヘルプには以下とあります。

Get-ChildItem

Outputs
System.Object
The type of object that Get-ChildItem returns is determined by the objects in the provider drive path.

System.String
If you use the Name parameter, Get-ChildItem returns the object names as strings.

確かに「-Nameを付けるとSystem.Stringで出力するよ」と書いてあります。これはつまりGetChildItemの情報を名前でフィルタして出力したい場合に
Get-ChildItem -Name "*hoge*"

Get-ChildItem | Where-Object {$_.Name -match "hoge"}
で結果が異なるということです。知らないと嵌りそう…。

確認する

-Name無し = DirectoryInfo

PS C:\Users\Public> Get-ChildItem


    ディレクトリ: C:\Users\Public


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-r---       2019/03/12      8:19                Documents
d-r---       2019/01/26     10:22                Downloads
d-r---       2019/01/26     10:22                Music
d-r---       2019/01/26     10:22                Pictures
d-r---       2019/01/26     10:22                Videos


PS C:\Users\Public>
PS C:\Users\Public> (Get-ChildItem)[0].GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DirectoryInfo                            System.IO.FileSystemInfo


PS C:\Users\Public>

-Name有り = String

PS C:\Users\Public> Get-ChildItem -Name "Do*"
Documents
Downloads
PS C:\Users\Public>
PS C:\Users\Public> (Get-ChildItem -Name "Do*")[0].GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object


PS C:\Users\Public>

実際に確認することができました。

出力内容がパラメータによって変わるということは
- Get-Help Get-ChildItem -Full のように-Fullパラメータ付きでGet-Helpする
- オンラインヘルプ 見る
- 自力で気付く
しかない気がしています。なんでこんな仕様になってるんや…
オンラインヘルプを読むことの重要性を感じた一件でした。


なお上記の検証は以下の条件で行いました

PS C:\Users\Public> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.17763.316
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.316
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1


PS C:\Users\Public>

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
0