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

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

    If you just want an alternative to the cmdlet syntax, specifically for files, use the File.Exists() .NET method:

    if(![System.IO.File]::Exists($path)){
        # file with path $path doesn't exist
    }
    

    If, on the other hand, you want a general purpose negated alias for Test-Path, here is how you should do it:

    # Gather command meta data from the original Cmdlet (in this case, Test-Path)
    $TestPathCmd = Get-Command Test-Path
    $TestPathCmdMetaData = New-Object System.Management.Automation.CommandMetadata $TestPathCmd
    
    # Use the static ProxyCommand.GetParamBlock method to copy 
    # Test-Path's param block and CmdletBinding attribute
    $Binding = [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($TestPathCmdMetaData)
    $Params  = [System.Management.Automation.ProxyCommand]::GetParamBlock($TestPathCmdMetaData)
    
    # Create wrapper for the command that proxies the parameters to Test-Path 
    # using @PSBoundParameters, and negates any output with -not
    $WrappedCommand = { 
        try { -not (Test-Path @PSBoundParameters) } catch { throw $_ }
    }
    
    # define your new function using the details above
    $Function:notexists = '{0}param({1}) {2}' -f $Binding,$Params,$WrappedCommand
    

    notexists will now behave exactly like Test-Path, but always return the opposite result:

    PS C:\> Test-Path -Path "C:\Windows"
    True
    PS C:\> notexists -Path "C:\Windows"
    False
    PS C:\> notexists "C:\Windows" # positional parameter binding exactly like Test-Path
    False
    

    As you've already shown yourself, the opposite is quite easy, just alias exists to Test-Path:

    PS C:\> New-Alias exists Test-Path
    PS C:\> exists -Path "C:\Windows"
    True
    
    0 讨论(0)
提交回复
热议问题