LoginSignup
4
2

More than 3 years have passed since last update.

PowerShell で与えられたパスがフォルダかどうか判定する方法

Last updated at Posted at 2021-02-08

PowerShell で、与えられたパスが存在するか否かの判定は Test-Path で行えるが、
与えられたパスがフォルダなのかファイルなのか判定する方法について書く。

(Get-Item $path) -is [System.IO.DirectoryInfo]

ref: https://devblogs.microsoft.com/scripting/powertip-using-powershell-to-determine-if-path-is-to-file-or-folder/

Get-Item にフォルダを指定した場合、System.IO.DirectoryInfo のオブジェクトが返ってくることを利用した方法。

PS C:\pstest> ls
    ディレクトリ: C:\pstest
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        2021/02/08     12:09                testFolder
-a----        2021/02/08     12:10              0 testFile.txt
PS C:\pstest> (Get-Item .\testFolder) -is [System.IO.DirectoryInfo]
True
PS C:\pstest> (Get-Item .\testFile.txt) -is [System.IO.DirectoryInfo]
False

ファイルの場合は System.IO.FileInfo のオブジェクトが返るため、ファイルを判定する場合は -is [System.IO.FileInfo] を指定すればよい。

(Get-Item $path).PSIsContainer

ref: https://bayashita.com/p/entry/show/229

ファイルシステムオブジェクトは PSIsContainer というプロパティを持っており、これは フォルダ(container) の場合に true になる。

PS C:\pstest> (Get-Item .\testFolder).PSIsContainer
True
PS C:\pstest> (Get-Item .\testFile.txt).PSIsContainer
False
4
2
3

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