Bjørn H. Sandvik
Bjørn H. Sandvik

Reputation: 543

PowerShell - Test-Path ignoring file name

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

Upvotes: 0

Views: 344

Answers (2)

Esperento57
Esperento57

Reputation: 17472

try this :

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

if(!(Test-Path $Dir)) { 
    Write-Host "Invalid path" 
}

Upvotes: 2

Bjørn H. Sandvik
Bjørn H. Sandvik

Reputation: 543

Nevermind.. I didn't Google hard enough:

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

Upvotes: 2

Related Questions