Kae Travis

Use Test-Path with PowerShell

Tags:

When we want to check for the existence of files, folders and registry entries we can use Test-Path with PowerShell to return ‘true’ if it exists and ‘false’ if it doesn’t exist.

Using Test-Path with Files and Folders

Here we test against the following folder structure:

c:\alkane (folder)
c:\alkane\alkane.txt (file)
c:\alkane\alkane.ps1 (file)

And provide the following quick-start examples:

#does folder exist
write-host (Test-Path -Path c:\alkane)
#returns true
#does file exist
write-host (Test-Path -Path c:\alkane\alkane.txt)
#returns true
#is c:\alkane\alkane.txt a file?
write-host (Test-Path -Path c:\alkane\alkane.txt -PathType Leaf)
#returns true
#is c:\alkane\alkane.txt a folder?
write-host (Test-Path -Path c:\alkane\alkane.txt -PathType Container)
#returns false
#is c:\alkane\alkane.txt newer than August 20, 2022 (today is September 13, 2022!)
write-host (Test-Path -Path c:\alkane\alkane.txt -NewerThan "August 20, 2022") 
#returns true
#is c:\alkane\alkane.txt newer than September 20, 2022 (today is September 13, 2022!)
write-host (Test-Path -Path c:\alkane\alkane.txt -NewerThan "September 20, 2022") 
#returns false
#does the folder contain any ps1 (PowerShell) file
write-host (Test-Path -Path c:\alkane\*.ps1)
#returns true
#does the folder contain any file with the letters 'ane' in it
write-host (Test-Path -Path c:\alkane\*ane*)
#returns true
#does c:\alkane contain any files other than ps1 files?
write-host (Test-Path -Path c:\alkane\* -exclude *.ps1)
#returns true

Using Test-Path with the Registry

Here we test against the following registry structure:

HKLM\SOFTWARE\Alkane (registry key)
HKLM\SOFTWARE\Alkane\AlkaneValue (registry value)

And provide the following quick-start examples:

#does registry key exist
write-host (Test-Path -Path HKLM:\SOFTWARE\Alkane)
#returns true
#does registry value AlkaneValue exist
write-host (Test-Path -Path HKLM:\SOFTWARE\Alkane\AlkaneValue)
#returns false - WRONG BECAUSE IT DOES EXIST!  Test-Path does not work with registry values.  
#We must work a bit harder to see if a registry value exists.
#Use the below example instead
#does registry value AlkaneValue exist
write-host $(if ((Get-ItemProperty -Path HKLM:\SOFTWARE\Alkane\ | Select-Object -ExpandProperty AlkaneValue -ErrorAction SilentlyContinue) -eq $null) { $false } else { $true })
#returns true
Use Test-Path with PowerShell
Use Test-Path with PowerShell

Leave a Reply