0

How can you use Test-Path (or any other function) to test if a folder exists - ignoring any trailing file names?

I need this to test if the target folder exists in order to write an output file to it. My script accepts a "full path" parameter like "C:\Temp\myexport.csv", and I only need to know that C:\Temp exists in order to be able to create the file.

Thank you

2 Answers 2

2

try this :

$OutFile = "C:\Temp\myexport.csv"
$Dir=[System.IO.Path]::GetDirectoryName($OutFile)

if(!(Test-Path $Dir)) { 
    Write-Host "Invalid path" 
}
Sign up to request clarification or add additional context in comments.

Comments

2

Nevermind.. I didn't Google hard enough:

$OutFile = "C:\Temp\myexport.csv"
if(!Test-Path -Path (Split-Path -Path $OutFile)) { 
    Write-Host "Invalid path" 
}

1 Comment

As a slight alternative, you could use, If(!(Test-Path -Path (Split-Path -Path $OutFile -Parent))) { Throw "$(Split-Path -Path $OutFile -Parent) does not exist." }, you could even continue on from there with Else { If(Test-Path -Path $OutFile) { Throw "$OutFile already exists." } }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.