A better way to check if a path exists or not in PowerShell

前端 未结 7 2195
名媛妹妹
名媛妹妹 2020-11-29 20:32

I just don\'t like the syntax of:

if (Test-Path $path) { ... }

and

if (-not (Test-Path $path)) { ... }
if (!(Test-Path $pa         


        
7条回答
  •  感动是毒
    2020-11-29 21:25

    Another option is to use IO.FileInfo which gives you so much file info it make life easier just using this type:

    PS > mkdir C:\Temp
    PS > dir C:\Temp\
    PS > [IO.FileInfo] $foo = 'C:\Temp\foo.txt'
    PS > $foo.Exists
    False
    PS > New-TemporaryFile | Move-Item -Destination C:\Temp\foo.txt
    PS > $foo.Refresh()
    PS > $foo.Exists
    True
    PS > $foo | Select-Object *
    
    
    Mode              : -a----
    VersionInfo       : File:             C:\Temp\foo.txt
                        InternalName:
                        OriginalFilename:
                        FileVersion:
                        FileDescription:
                        Product:
                        ProductVersion:
                        Debug:            False
                        Patched:          False
                        PreRelease:       False
                        PrivateBuild:     False
                        SpecialBuild:     False
                        Language:
    
    BaseName          : foo
    Target            : {}
    LinkType          :
    Length            : 0
    DirectoryName     : C:\Temp
    Directory         : C:\Temp
    IsReadOnly        : False
    FullName          : C:\Temp\foo.txt
    Extension         : .txt
    Name              : foo.txt
    Exists            : True
    CreationTime      : 2/27/2019 8:57:33 AM
    CreationTimeUtc   : 2/27/2019 1:57:33 PM
    LastAccessTime    : 2/27/2019 8:57:33 AM
    LastAccessTimeUtc : 2/27/2019 1:57:33 PM
    LastWriteTime     : 2/27/2019 8:57:33 AM
    LastWriteTimeUtc  : 2/27/2019 1:57:33 PM
    Attributes        : Archive
    

    More details on my blog.

提交回复
热议问题