2009-03-11 8 views
11

Ora sto iniziando a utilizzare PowerShell e dopo un sacco di tempo con le shell Unix e voglio sapere come verificare l'esistenza di un file o di una directory.Come utilizzare l'oggetto FileInfo da PowerShell

In Powershell perché Exist restituisce falso nella seguente espressione?

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

E c'è un modo migliore per controllare se un file è una directory di:

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

risposta

20

Usa 'test-path' invece di System.IO.FileInfo.Exists

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

è possibile utilizzare PSIsContainer per determinare se un file è una directory:

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

Oltre a Michael's answer si potrebbe anche provare utilizzando:

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

in PowerShell perché esiste return false nel seguente espressione?

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

Perché non c'è nessun file denominato "C: \" - si tratta di una directory.

+0

io sono abituato a Unix, dove una directory è un file troppo. – BeWarned

1

È possibile utilizzare Get-Item per consentire a PowerShell di selezionare tra FileInfo e DirectoryInfo. Genera un'eccezione se il percorso non si risolve in una posizione.

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

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

Vorrei usare solo questo oltre Test-Path se è necessario l'ingresso DirectoryInfo o FileInfo se esiste.

0

Entrambi questi restituiscono true

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