Jika Anda hanya ingin alternatif sintaks cmdlet, khusus untuk file, gunakan File.Exists()
metode .NET:
if(![System.IO.File]::Exists($path)){
# file with path $path doesn't exist
}
Jika, di sisi lain, Anda menginginkan alias negasi untuk tujuan umum Test-Path
, berikut adalah cara melakukannya:
# 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
sekarang akan berperilaku persis seperti Test-Path
, tetapi selalu mengembalikan hasil yang berlawanan:
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
Seperti yang sudah Anda tunjukkan pada diri Anda sendiri, sebaliknya cukup mudah, alias hanya exists
untuk 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 }