Rotten Code

it can always work better - but at least it should work

  Home  |   Contact  |   Syndication    |   Login
  18 Posts | 0 Stories | 12 Comments | 2 Trackbacks

News



Archives

Recommended Podcasts

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
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Wednesday, August 06, 2008 8:47 AM

Feedback

# re: How to tell if Folder Exists of File Exists with PowerShell 8/6/2008 11:32 AM Lance
A much easier way is the built-in test-path cmdlet:

if (test-path $mypath)
{
echo "The folder exists"
}

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

# re: How to tell if Folder Exists of File Exists with PowerShell 9/2/2010 4:46 PM Abel
Just use the -PathType options to specify folders (containers) and not a file (leaf).

Test-Path -PathType Container $pathToFolder

# re: How to tell if Folder Exists of File Exists with PowerShell 5/19/2011 10:48 AM NP
It is not more useful to do so with Powershell 2.

Just use 'test-path' with file or folder

# re: How to tell if Folder Exists of File Exists with PowerShell 6/17/2011 10:22 AM Zhaph - Ben Duguid
Or you can use:

Test-Path C:\Scripts\Archive

http://technet.microsoft.com/en-us/library/ff730955.aspx

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

# re: How to tell if Folder Exists of File Exists with PowerShell 1/13/2012 1:31 AM Michael Freidgeim
You should update the post with Lanse suggestion

if (test-path $mypath)
{
echo "The folder exists"
}


Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: