A better way to check if a path exists or not in PowerShell

I just don't like the syntax of:

if (Test-Path $path) { ... }


if (-not (Test-Path $path)) { ... }
if (!(Test-Path $path)) { ... }

especially there is too many parenthesis and not very readable when checking for "not exist" for such a common use. What is a better way to do this?

Update: My current solution is to use aliases for exist and not-exist as explained here.

Related issue in PowerShell repository: https://github.com/PowerShell/PowerShell/issues/1970

If you just want an alternative to the cmdlet syntax, specifically for files, use the File.Exists() .NET method:

    # file with path $path doesn't exist

If, on the other hand, you want a general purpose negated alias for Test-Path, here is how you should do it:

# 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 will now behave exactly like Test-Path, but always return the opposite result:

PS C:\> Test-Path -Path "C:\Windows"
PS C:\> notexists -Path "C:\Windows"
PS C:\> notexists "C:\Windows" # positional parameter binding exactly like Test-Path

As you've already shown yourself, the opposite is quite easy, just alias exists to Test-Path:

PS C:\> New-Alias exists Test-Path
PS C:\> exists -Path "C:\Windows"

A better way to check if a path exists or not in PowerShell, If you just want an alternative to the cmdlet syntax, specifically for files, use the File.Exists() .NET method: if(![System.IO.File]::Exists($path)){� How To NOT Find The Path Environment Variable. Search the registry for every instance of the word “PATH”. Open the computer case and search underneath the CPU fan. Reading tea leaves and/or chicken bones; There is a better way. Enter PowerShell. Check out this beauty: PS C:> cd env: PS Env:> ls path. And out comes the entry for the path variable

The alias solution you posted is clever, but I would argue against its use in scripts, for the same reason I don't like using any aliases in scripts; it tends to harm readability.

If this is something you want to add to your profile so you can type out quick commands or use it as a shell, then I could see that making sense.

You might consider piping instead:

if ($path | Test-Path) { ... }
if (-not ($path | Test-Path)) { ... }
if (!($path | Test-Path)) { ... }

Alternatively, for the negative approach, if appropriate for your code, you can make it a positive check then use else for the negative:

if (Test-Path $path) {
    throw "File already exists."
} else {
   # The thing you really wanted to do.

Powershell check if folder exists, How To Check If A Folder Exists With PowerShell To explicitly make sure it's a directory and not a file, use the -PathType parameter which accepts the� The PathType parameter is not strictly required, but it is useful if you want to be sure the check you are performing is actually a file, not a directory. You can check for a directory by setting PathType to “container”. Filed Under: How To Tagged With: Powershell. Reader Interactions.

Add the following aliases. I think these should be made available in PowerShell by default:

function not-exist { -not (Test-Path $args) }
Set-Alias !exist not-exist -Option "Constant, AllScope"
Set-Alias exist Test-Path -Option "Constant, AllScope"

With that, the conditional statements will change to:

if (exist $path) { ... }


if (not-exist $path)) { ... }
if (!exist $path)) { ... }

PowerShell Basics: Test-Path, PowerShell Basics: Using Test-Path to Check if a File Exists with Examples Encouraging computers to sleep when they're not in use is a great idea occurring on the network, and each tool teaches me more about how the� In a script, you would typically use it in an if statement. To negate and check if the folder or file does not exist, use either "!" or "-not", and remember to enclose the Test-Path statement in parentheses. Also remember that if the path or folder name contains a space, you need to surround the entire path in quotes.

Another option is to use IO.FileInfo which gives you so much file info it make life easier just using this type:

PS > mkdir C:\Temp
PS > dir C:\Temp\
PS > [IO.FileInfo] $foo = 'C:\Temp\foo.txt'
PS > $foo.Exists
PS > New-TemporaryFile | Move-Item -Destination C:\Temp\foo.txt
PS > $foo.Refresh()
PS > $foo.Exists
PS > $foo | Select-Object *

Mode              : -a----
VersionInfo       : File:             C:\Temp\foo.txt
                    Debug:            False
                    Patched:          False
                    PreRelease:       False
                    PrivateBuild:     False
                    SpecialBuild:     False

BaseName          : foo
Target            : {}
LinkType          :
Length            : 0
DirectoryName     : C:\Temp
Directory         : C:\Temp
IsReadOnly        : False
FullName          : C:\Temp\foo.txt
Extension         : .txt
Name              : foo.txt
Exists            : True
CreationTime      : 2/27/2019 8:57:33 AM
CreationTimeUtc   : 2/27/2019 1:57:33 PM
LastAccessTime    : 2/27/2019 8:57:33 AM
LastAccessTimeUtc : 2/27/2019 1:57:33 PM
LastWriteTime     : 2/27/2019 8:57:33 AM
LastWriteTimeUtc  : 2/27/2019 1:57:33 PM
Attributes        : Archive

More details on my blog.

Test-Path - PowerShell, Return true if the path exists, otherwise return false, determines whether all Key -Path string[] The PowerShell path (or paths) to test Wildcards are permitted. Filters are more efficient than -include/-exclude, because the provider applies the This parameter is not supported by any PowerShell core cmdlets or providers. For testing the path, you can use: Test-Path \\my_server\my_root\my_dir Note:You will get a boolean value in return from the test path. Hope it helps.

To check if a Path exists to a directory, use this one:

$pathToDirectory = "c:\program files\blahblah\"
if (![System.IO.Directory]::Exists($pathToDirectory))
 mkdir $path1

To check if a Path to a file exists use what @Mathias suggested:


[SOLVED] Test-Path and If - PowerShell, I have something behaving weird and it may be me but I am not sure. Checking to see if a directory exists and running code based on that. Powershell. $a = Test-� Alternatively, for the negative approach, if appropriate for your code, you can make it a positive check then use else for the negative: if (Test-Path $path) { throw "File already exists." } else { # The thing you really wanted to do.

PowerShell Create Folder if it does not exist, Learn how PowerShell can check if a folder exists and automatically create it if not. I'm trying to write a script to check the version (or versions) of Microsoft Office installed on a computer and then take action accordingly. Our environment is primarily Windows 7. PowerShell version is 4. We have a mix of Office 365, 2013, 2010, and 2007. I'm having trouble understanding the results of my Test-Path registry query.

Test-Path | Taking on PowerShell one cmdlet at a time, How to use Test-Path. Test a path: Test-Path -Path “C:\Documents and Settings\ AdamG”. This command checks whether all elements in the path exist, that is, the C: Test-Path does not work correctly with all PowerShell providers. Proudly powered by WordPress. ✓. Thanks for sharing! AddToAny. More… The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element. If the Path is whitespace an empty string, then $False is returned.

Powershell test path file exists, 547 total views, 80 views today In this post I will show how to create a folder or directory if not exists in the given directory or path using PowerShell code or script� In the above code, the core part that checks for OU existence is [ADSI]::Exists () static method. It returns true if OU exists, otherwise returns false. It will generate appropriate errors if it can not reach the domain you are querying. Let us see a quick demo to see how it works. My AD structure is like below.