Wenn Sie nur eine Alternative zur Cmdlet-Syntax speziell für Dateien wünschen, verwenden Sie die File.Exists()
.NET-Methode:
if(![System.IO.File]::Exists($path)){
# file with path $path doesn't exist
}
Wenn auf der anderen Seite wollen Sie ein Allzweck-Alias für Test-Path
negiert wird, ist hier, wie Sie es tun sollten:
# 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
wird nun verhalten genau wie Test-Path
, aber immer das umgekehrte Ergebnis zurück:
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
Wie Sie bereits selbst gezeigt hat, ist das Gegenteil ganz einfach, nur alias exists
zu Test-Path
:
PS C:\> New-Alias exists Test-Path
PS C:\> exists -Path "C:\Windows"
True
Sie verwenden könnten 'try {Test-Path -EA Stopp $ Pfad; #stuff zu tun, wenn gefunden} catch {# Sachen zu tun, wenn nicht gefunden} ' – Eris
Related Problem: https://github.com/PowerShell/PowerShell/issues/1970 – orad
Sie, mein Freund, verwenden das falsche Werkzeug, wenn Sie will Lesbarkeit. – GenuineRex