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

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

  • Comments 6
  • Likes

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]

True

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

False

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • I like this too:

    PS s> ([IO.FileInfo]'c:\scripts').Attributes -eq 'Directory'
    True
    PS > ([IO.FileInfo]'c:\scripts\test.txt').Attributes -eq 'Directory'
    False

  • Why not use Test-Path? It has -PathType parameter that makes it easy to identify item type... :)

  • The previous post should be:

    PS > ([IO.FileInfo]'c:\scripts').Attributes -match 'Directory'
    True
    PS > ([IO.FileInfo]'c:\scripts\test.txt').Attributes -match 'Directory'
    False

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

  • 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
    True
    PS C:\> (get-item c:\scripts\test.txt).PSIsContainer
    False

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