Comprobar si existe un archivo en Windows PowerShell
- 
          
            Use Test-Pathpara verificar si existe un archivo en PowerShell
- 
          
            Utilice [System.IO.File]::Exists()para comprobar si existe un archivo en PowerShell
- 
          
            Use Get-Itempara verificar si existe un archivo en PowerShell
- 
          
            Utilice Get-ChildItempara comprobar si existe un archivo en PowerShell
 
A veces, recibe un mensaje de error que dice que el archivo no existe en PowerShell. Este tutorial presentará cuatro métodos para comprobar si existe un archivo en PowerShell.
Use Test-Path para verificar si existe un archivo en PowerShell
    
El primer método es el cmdlet Test-Path. Determina si existe la ruta completa. Devuelve $True si existe la ruta y $False si falta algún elemento. El parámetro -PathType Leaf busca un archivo y no un directorio.
Test-Path -Path "C:/New/test.txt" -PathType Leaf
Producción :
True
Si no hay un archivo llamado file.txt en el directorio New, devuelve $False.
Test-Path -Path "C:/New/file.txt" -PathType Leaf
Producción :
False
Utilice [System.IO.File]::Exists() para comprobar si existe un archivo en PowerShell
Otro método para comprobar si existe un archivo es [System.IO.File]::Exists(). Proporciona un resultado booleano, True si el archivo existe o False si el archivo no existe.
[System.IO.File]::Exists("C:/New/test.txt")
Producción :
True
Use Get-Item para verificar si existe un archivo en PowerShell
El cmdlet Get-Item se usa para obtener el elemento en la ruta especificada. Puede usarlo para verificar si existe un archivo especificando la ruta del archivo. Imprime el modo (atributos), la última hora de escritura, la longitud y el nombre de un archivo, si existe. Muestra un mensaje de error si un archivo no existe.
Get-Item C:/New/test.txt
Producción :
Directory: C:\New
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        12/11/2021   2:59 PM              5 test.txt
A continuación se muestra la salida cuando el archivo no existe.
Get-Item : Cannot find path 'C:\New\test10.txt' because it does not exist.
At line:1 char:1
+ Get-Item C:/test/test10.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\New\test10.txt:String) [Get-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
Utilice Get-ChildItem para comprobar si existe un archivo en PowerShell
El último método es usar el cmdlet Get-ChildItem. Obtiene los elementos y los elementos secundarios en una o más rutas especificadas. Muestra los detalles del archivo si el archivo existe en la ruta especificada.
Get-ChildItem -Path C:/New/test.txt
Producción :
Directory: C:\New
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        12/11/2021   2:59 PM              5 test.txt
Imprime un mensaje de error que dice Cannot find path '$path' because it does not exist. cuando no se encuentra un archivo.
 Get-ChildItem -Path C:/New/test
Producción :
Get-ChildItem : Cannot find path 'C:\New\test' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path C:/New/test
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\New\test:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Artículo relacionado - PowerShell File
- Cómo crear un archivo de texto usando Windows PowerShell
- Cómo obtener la versión del archivo en PowerShell
- Cómo subir archivos con FTP en PowerShell
- Cómo agregar datos a un archivo usando PowerShell
- Cómo almacenar el contenido de un archivo de texto en una variable usando PowerShell
- Consulta de la última hora de escritura del archivo en PowerShell
