PowerTip: Using PowerShell to Determine if Path Is to File or Folder

Summary: Learn how to use Windows PowerShell to determine if a path is to a file or a folder.

Hey, Scripting Guy! Question How can I use Windows PowerShell to determine if a path is to a file or a folder?

Hey, Scripting Guy! Answer Use the Get-Item cmdlet to get the object represented by the path. Then use the –Is operator to see if the
           object is a [system.io.directoryinfo] object or a [system.io.fileinfo] object. Here is an example:

PS C:\> (Get-Item c:\fso) -is [System.IO.DirectoryInfo]


PS C:\> (Get-Item C:\fso\csidl.txt) -is [System.IO.DirectoryInfo]


Comments (6)

  1. jrv says:

    The previous post should be:

    PS > ([IO.FileInfo]’c:scripts’).Attributes -match ‘Directory’
    PS > ([IO.FileInfo]’c:scriptstest.txt’).Attributes -match ‘Directory’

  2. jrv says:

    I like this too:

    PS s> ([IO.FileInfo]’c:scripts’).Attributes -eq ‘Directory’
    PS > ([IO.FileInfo]’c:scriptstest.txt’).Attributes -eq ‘Directory’

  3. Anonymous says:

    Why not use Test-Path? It has -PathType parameter that makes it easy to identify item type… 🙂

  4. Keith Garner says:

    jrv – have you tested this method on a computer system running in a different language, like de-DE or zh-CN, I would avoid using text comparison operations if there is a way to compare using native methods.

    Additionally, there is the PSisContainer property:

    PS C:> (get-item c:scripts).PSIsContainer
    PS C:> (get-item c:scriptstest.txt).PSIsContainer

  5. Powershell Operator says:

    I finally understand what is is.
    PS C:> [System.IO.DirectoryInfo] -Is [System.Type]

  6. sager says:

    if(Test-Path $_ -pathType container){"Folder"}
    if(Test-Path $_ -pathType leaf){"File"}