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

前端 未结 7 2048
名媛妹妹
名媛妹妹 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:11

    The alias solution you posted is clever, but I would argue against its use in scripts, for the same reason I don't like using any aliases in scripts; it tends to harm readability.

    If this is something you want to add to your profile so you can type out quick commands or use it as a shell, then I could see that making sense.

    You might consider piping instead:

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

    Alternatively, for the negative approach, if appropriate for your code, you can make it a positive check then use else for the negative:

    if (Test-Path $path) {
        throw "File already exists."
    } else {
       # The thing you really wanted to do.
    }
    
    0 讨论(0)
  • 2020-11-29 21:11
    if (Test-Path C:\DockerVol\SelfCertSSL) {
        write-host "Folder already exists."
    } else {
       New-Item -Path "C:\DockerVol\" -Name "SelfCertSSL" -ItemType "directory"
    }
    
    0 讨论(0)
  • 2020-11-29 21:14

    This is my powershell newbie way of doing this

    if ((Test-Path ".\Desktop\checkfile.txt") -ne "True") {
        Write-Host "Damn it"
    } else {
        Write-Host "Yay"
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 21:28

    Add the following aliases. I think these should be made available in PowerShell by default:

    function not-exist { -not (Test-Path $args) }
    Set-Alias !exist not-exist -Option "Constant, AllScope"
    Set-Alias exist Test-Path -Option "Constant, AllScope"
    

    With that, the conditional statements will change to:

    if (exist $path) { ... }
    

    and

    if (not-exist $path) { ... }
    if (!exist $path) { ... }
    
    0 讨论(0)
  • 2020-11-29 21:31

    To check if a Path exists to a directory, use this one:

    $pathToDirectory = "c:\program files\blahblah\"
    if (![System.IO.Directory]::Exists($pathToDirectory))
    {
     mkdir $path1
    }
    

    To check if a Path to a file exists use what @Mathias suggested:

    [System.IO.File]::Exists($pathToAFile)
    
    0 讨论(0)
提交回复
热议问题