Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FileInfo object from Powershell

I am now starting to use PowerShell and after a lot of time using the Unix shells and want to know how to check for the existence of a file or directory.

In Powershell why does Exist return false in the following expression?

PS H:\> ([System.IO.FileInfo]"C:\").Exists
False

And is there a better way to check if a file is a directory than:

PS H:\> ([System.IO.FileInfo]"C:\").Mode.StartsWith("d")
True
like image 839
BeWarned Avatar asked Mar 11 '09 23:03

BeWarned


People also ask

How do I get file attributes in PowerShell?

To get file attributes in PowerShell, you can use Get-ChildItem or Get-Item cmdlets. It returns the file attributes or properties available on the specified files. To get the list of all properties available, use the Get-Member cmdlet.


2 Answers

Use 'test-path' instead of System.IO.FileInfo.Exists

PS C:\Users\m> test-path 'C:\'
True

You can use PSIsContainer to determine if a file is a directory:

PS C:\Users\m> (get-item 'c:\').PSIsContainer
True

PS C:\Users\m> (get-item 'c:\windows\system32\notepad.exe').PSIsContainer
False
like image 97
Michael Avatar answered Sep 20 '22 05:09

Michael


In Powershell why does Exist return false in the following expression?

  PS H:> ([System.IO.FileInfo]"C:\").Exists
  

Because there is no file called "C:\" - it's a directory.

like image 27
Jay Bazuzi Avatar answered Sep 20 '22 05:09

Jay Bazuzi