Geeks With Blogs
Rotten Code it can always work better - but at least it should work
So you want to determine if a folder or file exists with PowerShell? You can invoke the same scripting object you might remember from VB....


#set a var for the folder you are looking for
$folderPath = 'C:\Temp\'

#instantiate the FileSystemObject
$objFSO = New-Object -ComObject Scripting.FileSystemObject

#check to see if it is missing
if($objFSO.FileExists($folderPath -eq $FALSE))
{
     echo "The folder does not exist."
     exit
}
else
{
    echo "The folder exists."
    exit
} Posted on Wednesday, August 6, 2008 8:47 AM | Back to top


Comments on this post: How to tell if Folder Exists of File Exists with PowerShell

# re: How to tell if Folder Exists of File Exists with PowerShell
Requesting Gravatar...
A much easier way is the built-in test-path cmdlet:

if (test-path $mypath)
{
echo "The folder exists"
}
Left by Lance on Aug 06, 2008 11:32 AM

# re: How to tell if Folder Exists of File Exists with PowerShell
Requesting Gravatar...
test-path will return true for both files and directories, so you cannot tell the difference
Left by Simon on Feb 10, 2010 4:02 AM

# re: How to tell if Folder Exists of File Exists with PowerShell
Requesting Gravatar...
Just use the -PathType options to specify folders (containers) and not a file (leaf).

Test-Path -PathType Container $pathToFolder
Left by Abel on Sep 02, 2010 4:46 PM

# re: How to tell if Folder Exists of File Exists with PowerShell
Requesting Gravatar...
It is not more useful to do so with Powershell 2.

Just use 'test-path' with file or folder
Left by NP on May 19, 2011 10:48 AM

# re: How to tell if Folder Exists of File Exists with PowerShell
Requesting Gravatar...
Or you can use:

Test-Path C:\Scripts\Archive

http://technet.microsoft.com/en-us/library/ff730955.aspx
Left by Zhaph - Ben Duguid on Jun 17, 2011 10:22 AM

# re: How to tell if Folder Exists of File Exists with PowerShell
Requesting Gravatar...
Test-Path is much more efficient than using a com object and doesn't require instantiation.
Left by Matt on Nov 29, 2011 5:12 PM

# re: How to tell if Folder Exists of File Exists with PowerShell
Requesting Gravatar...
You should update the post with Lanse suggestion

if (test-path $mypath)
{
echo "The folder exists"
}
Left by Michael Freidgeim on Jan 13, 2012 1:31 AM

Your comment:
 (will show your gravatar)


Copyright © Marcus Shockley | Powered by: GeeksWithBlogs.net