Jeśli potrzebujesz tylko alternatywy dla składni cmdlet, szczególnie dla plików, użyj File.Exists()
.Metoda netto:
if(![System.IO.File]::Exists($path)){
# file with path $path doesn't exist
}
Jeśli, z drugiej strony, chcesz ogólnego przeznaczenia zanegowane alias Test-Path
, tu jest jak należy to zrobić:
# 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ędzie teraz zachowywać dokładnie jak Test-Path
, ale zawsze zwracamy przeciwny wynik:
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
Jak już pokazano siebie, przeciwnie jest bardzo proste, wystarczy alias exists
do Test-Path
:
PS C:\> New-Alias exists Test-Path
PS C:\> exists -Path "C:\Windows"
True
Można użyć 'try {Test-Path -EA Zatrzymaj $ path; #stuff do zrobienia, jeśli znaleziono} catch {# rzeczy do zrobienia, jeśli nie znaleziono} ' – Eris
Pokrewny problem: https://github.com/PowerShell/PowerShell/issues/1970 – orad
Ty, mój przyjacielu, używasz niewłaściwego narzędzia, jeśli chcą czytelności. – GenuineRex