Se desideri solo un'alternativa alla sintassi del cmdlet, in particolare per i file, utilizza il File.Exists()
metodo .NET:
if(![System.IO.File]::Exists($path)){
# file with path $path doesn't exist
}
Se, d'altra parte, vuoi un alias negato per scopi generali Test-Path
, ecco come dovresti farlo:
# 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
ora si comporterà esattamente come Test-Path
, ma restituirà sempre il risultato opposto:
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
Come hai già dimostrato, l'opposto è abbastanza facile, solo alias exists
per 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 }