Jump to page sections
- How To Check If A Folder Exists With PowerShell
- Screenshot Example
- Script Usage
- Create A Directory If It Does Not Exist
- Enumerating Possible PathType Values
- Using The .NET System.IO.Directory Class Method "Exists"
In this little article, I describe how to use the cmdlet Test-Path to check whether a folder exists. Type "Get-Help Test-Path" for built-in information. I also briefly demonstrate how to use the .NET class method Exists() from the class System.IO.Directory. The Test-Path cmdlet returns a boolean for whether or not the folder exists. True if it exists and False if it does not exist.
How To Check If A Folder Exists With PowerShell
PS C:\> Test-Path C:\Windows True
Remember that you need single or double quotes around the path if it contains a space. Single quotes are recommended, since they don't expand/substitute/interpolate variables.
To explicitly make sure it's a directory and not a file, use the -PathType parameter which accepts the following values:
- Any
- Leaf (file)
- Container (directory/folder)
PS C:\> Test-Path C:\Windows -PathType Any True PS C:\> Test-Path C:\Windows -PathType Container True PS C:\> Test-Path C:\Windows -PathType Leaf False
Screenshot Example
Script Usage
Also remember that if the path or folder name contains a space, you need to surround the entire path in quotes. Single quotes or double quotes will work the same if there are no "expandable" parts in the path or folder name, but the slightly safer choice is single quotes. This is what PowerShell defaults to when you auto-complete names with tab at the prompt.
PS C:\> if (Test-Path -Path 'C:\Windows' -PathType Container) { "It's a container/folder/directory" }It's a container/folder/directory
PS C:\> if ( -not (Test-Path -LiteralPath 'C:\Windows' -PathType Leaf) ) { "It's not a leaf/file" }It's not a leaf/file
You should also be made aware of the parameter -LiteralPath to Test-Path, that you can see in the second example above. This also works if your file contains characters like brackets that causes the -Path parameter to expand the path since it supports wildcard syntax by default. Use -LiteralPath if you don't need expansion from -Path, as it's the safer choice for oddly named files.
Create A Directory If It Does Not Exist
To create a directory if it does not exist, this is a very robust example of how you might want to handle it. Adapt to suit your needs.
This code was put in the file "NewDirDemo.ps1" that you see me using below.[CmdletBinding()] Param( [Parameter(Mandatory = $True)] [String] $DirectoryToCreate) if (-not (Test-Path -LiteralPath $DirectoryToCreate)) { try { New-Item -Path $DirectoryToCreate -ItemType Directory -ErrorAction Stop | Out-Null #-Force } catch { Write-Error -Message "Unable to create directory '$DirectoryToCreate'. Error was: $_" -ErrorAction Stop } "Successfully created directory '$DirectoryToCreate'." } else { "Directory already existed" }
Demonstration of use in the following screenshot.
Enumerating Possible PathType Values
PS C:\> Test-Path C:\Windows -PathType foo Test-Path : Cannot bind parameter 'PathType'. Cannot convert value "foo" to type "Microsoft.PowerShell.Commands.TestPathType" due to invalid enumeration values. Specify one of the following enumeration values and try again. The possible enumeration values are "Any, Container, Leaf". At line:1 char:31 + Test-Path C:\Windows -PathType <<<< foo + CategoryInfo : InvalidArgument: (:) [Test-Path], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.TestPathCommand
Using The .NET System.IO.Directory Class Method "Exists"
PS E:\temp> [System.IO.Directory]::Exists('E:\temp\') True PS E:\temp> [System.IO.Directory]::Exists('E:\temp') True
If you want to check if the directory the script/program is currently in contains a subdirectory, you can use the trick I demonstrate below - where I check if there's a subdirectory called "Windows".
In PowerShell, the namespace "System" doesn't have to be typed in explicitly, so you can omit it.PS C:\> [IO.Directory]::Exists( (Join-Path (Get-Location) 'Windows') ) TruePowershell WindowsPS C:\> cd E:\temp
PS E:\temp> [IO.Directory]::Exists( (Join-Path (Get-Location) 'Windows') ) False
Blog articles in alphabetical order
A
- A Look at the KLP AksjeNorden Index Mutual Fund
- A primitive hex version of the seq gnu utility, written in perl
- Accessing the Bing Search API v5 using PowerShell
- Accessing the Google Custom Search API using PowerShell
- Active directory password expiration notification
- Aksje-, fonds- og ETF-utbytterapportgenerator for Nordnet-transaksjonslogg
- Ascii art characters powershell script
- Automatically delete old IIS logs with PowerShell
C
- Calculate and enumerate subnets with PSipcalc
- Calculate the trend for financial products based on close rates
- Check for open TCP ports using PowerShell
- Check if an AD user exists with Get-ADUser
- Check when servers were last patched with Windows Update via COM or WSUS
- Compiling or packaging an executable from perl code on windows
- Convert between Windows and Unix epoch with Python and Perl
- Convert file encoding using linux and iconv
- Convert from most encodings to utf8 with powershell
- ConvertTo-Json for PowerShell version 2
- Create cryptographically secure and pseudorandom data with PowerShell
- Crypto is here - and it is not going away
- Crypto logo analysis ftw
D
G
- Get rid of Psychology in the Stock Markets
- Get Folder Size with PowerShell, Blazingly Fast
- Get Linux disk space report in PowerShell
- Get-Weather cmdlet for PowerShell, using the OpenWeatherMap API
- Get-wmiobject wrapper
- Getting computer information using powershell
- Getting computer models in a domain using Powershell
- Getting computer names from AD using Powershell
- Getting usernames from active directory with powershell
- Gnu seq on steroids with hex support and descending ranges
- Gullpriser hos Gullbanken mot spotprisen til gull
H
- Have PowerShell trigger an action when CPU or memory usage reaches certain values
- Historical view of the SnP 500 Index since 1927, when corona is rampant in mid-March 2020
- How to check perl module version
- How to list all AD computer object properties
- Hva det innebærer at særkravet for lån til sekundærbolig bortfaller
I
L
M
P
- Parse openssl certificate date output into .NET DateTime objects
- Parse PsLoggedOn.exe Output with PowerShell
- Parse schtasks.exe Output with PowerShell
- Perl on windows
- Port scan subnets with PSnmap for PowerShell
- PowerShell Relative Strength Index (RSI) Calculator
- PowerShell .NET regex to validate IPv6 address (RFC-compliant)
- PowerShell benchmarking module built around Measure-Command
- Powershell change the wmi timeout value
- PowerShell check if file exists
- Powershell check if folder exists
- PowerShell Cmdlet for Splitting an Array
- PowerShell Executables File System Locations
- PowerShell foreach loops and ForEach-Object
- PowerShell Get-MountPointData Cmdlet
- PowerShell Java Auto-Update Script
- Powershell multi-line comments
- Powershell prompt for password convert securestring to plain text
- Powershell psexec wrapper
- PowerShell regex to accurately match IPv4 address (0-255 only)
- Powershell regular expressions
- Powershell split operator
- Powershell vs perl at text processing
- PS2CMD - embed PowerShell code in a batch file
R
- Recursively Remove Empty Folders, using PowerShell
- Remote control mom via PowerShell and TeamViewer
- Remove empty elements from an array in PowerShell
- Remove first or last n characters from a string in PowerShell
- Rename unix utility - windows port
- Renaming files using PowerShell
- Running perl one-liners and scripts from powershell
S
- Sammenlign gullpriser og sølvpriser hos norske forhandlere av edelmetall
- Self-contained batch file with perl code
- Simple Morningstar Fund Report Script
- Sort a list of computers by domain first and then name, using PowerShell
- Sort strings with numbers more humanely in PowerShell
- Sorting in ascending and descending order simultaneously in PowerShell
- Spar en slant med en optimalisert kredittkortportefølje
- Spre finansiell risiko på en skattesmart måte med flere Aksjesparekontoer
- SSH from PowerShell using the SSH.NET library
- SSH-Sessions Add-on with SCP SFTP Support
- Static Mutual Fund Portfolio the Last 2 Years Up 43 Percent
- STOXR - Currency Conversion Software - Open Exchange Rates API