Nếu bạn chỉ muốn thay thế cho cú pháp lệnh ghép ngắn, cụ thể cho các tệp, hãy sử dụng File.Exists()
phương thức .NET:
if(![System.IO.File]::Exists($path)){
# file with path $path doesn't exist
}
Mặt khác, nếu bạn muốn có một bí danh bị phủ định với mục đích chung Test-Path
, thì đây là cách bạn nên thực hiện:
# 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
bây giờ sẽ hoạt động giống hệt như vậy Test-Path
, nhưng luôn trả về kết quả ngược lại:
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
Như bạn đã thể hiện chính mình, điều ngược lại khá dễ dàng, chỉ cần bí danh exists
là Test-Path
:
PS C:\> New-Alias exists Test-Path
PS C:\> exists -Path "C:\Windows"
True
try{ Test-Path -EA Stop $path; #stuff to do if found } catch { # stuff to do if not found }