在 PowerShell 中检查路径是否存在的更好方法 [英] A better way to check if a path exists or not in PowerShell

查看:45
本文介绍了在 PowerShell 中检查路径是否存在的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是不喜欢以下语法:

I just don't like the syntax of:

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

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

特别是在检查不存在"以用于这种常见用途时,括号太多且可读性不强.有什么更好的方法可以做到这一点?

especially there is too many parenthesis and not very readable when checking for "not exist" for such a common use. What is a better way to do this?

更新:我目前的解决方案是对 existnot-exist 使用别名,如此处.

Update: My current solution is to use aliases for exist and not-exist as explained here.

PowerShell 存储库中的相关问题:https://github.com/PowerShell/PowerShell/issues/1970年

Related issue in PowerShell repository: https://github.com/PowerShell/PowerShell/issues/1970

推荐答案

如果您只想使用 cmdlet 语法的替代方案,特别是针对文件,请使用 File.Exists() .NET 方法:

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
}

<小时>

另一方面,如果您想要 Test-Path 的通用否定别名,您应该这样做:


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 现在将完全Test-Path 一样,但总是返回相反的结果:

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

正如您已经向自己展示的那样,相反很容易,只需将 exists 别名为 Test-Path:

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

这篇关于在 PowerShell 中检查路径是否存在的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆