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

前端 未结 7 2185
名媛妹妹
名媛妹妹 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.
    }
    

提交回复
热议问题