2009-03-11 9 views
11

Ahora estoy empezando a usar PowerShell y después de mucho tiempo usando las shells de Unix y quiero saber cómo verificar la existencia de un archivo o directorio.Cómo usar el objeto FileInfo de Powershell

En Powershell ¿por qué Exist devuelve falso en la siguiente expresión?

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

Y es que hay una mejor manera de comprobar si un archivo es un directorio que:

PS H:\> ([System.IO.FileInfo]"C:\").Mode.StartsWith("d") 
True 

Respuesta

20

Uso 'prueba de ruta' en lugar de System.IO.FileInfo.Exists

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

puede utilizar PSIsContainer para determinar si un archivo es un directorio:

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

PS C:\Users\m> (get-item 'c:\windows\system32\notepad.exe').PSIsContainer 
False 
7
Help Test-Path 

Test-Path Determines whether all elements of a path exist 

Test-Path -PathType Leaf C:\test.txt 
Test-Path -PathType Container C:\ 
Test-Path C:\ 
10

Además de Michael's answer también se puede probar usando:

PS H:> ([System.IO.DirectoryInfo]"C:\").Exists 
True 
7

En Powershell ¿Por qué existe return false en la siguiente expresión?

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

Debido a que no hay un archivo llamado "C: \" - es un directorio.

+0

Estoy acostumbrado a Unix en un directorio es un archivo también. – BeWarned

1

Puede usar Get-Item para permitir que PowerShell seleccione entre FileInfo y DirectoryInfo. Lanzará una excepción si la ruta no se resuelve en una ubicación.

PS> $(Get-Item "C:\").GetType() 

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

sólo lo usaría esta Test-Path sobre si va a necesitar la entrada DirectoryInfo o FileInfo si existe.

0

Ambos dan como resultado true

$(Get-Item "C:\").GetType() -eq [System.IO.DirectoryInfo] 
$(Get-Item "C:\test.txt").GetType() -eq [System.IO.FileInfo] 
Cuestiones relacionadas