Monthly Archive

Categories

Joining and Testing folder paths

Last time I showed how to split folder paths to just leave the path – no filenames or drive information. What about the opposite task – joining and testing folder paths.

Here’s an example

$basepath = 'C:\Scripts'

$pathsTotest = 'Containers','HyperV', 'NanoServer', 'NoSuchFolder'

$pathsToTest | foreach { 
    $path = Join-Path -Path $basepath -ChildPath $psitem 
    Test-Path -Path $path 
 }

When you run this the paths to test are joined to the base path and then tested.

The output is

True 
True 
True 
False

which isn’t the most informative you’ll ever see.

The output can easily be made more friendly

$basepath = 'C:\Scripts'

$pathsTotest = 'Containers','HyperV', 'NanoServer', 'NoSuchFolder'

$pathsToTest | foreach { 
    $path = Join-Path -Path $basepath -ChildPath $psitem 
    
    $props = @{ 
      Path = $path 
      Found = Test-Path -Path $path 
    }

    New-Object -TypeName psobject -Property $props 
      
 }

Create an object for the output using the full path you’re testing and the result

The output looks like this

Path                     Found 
 ----                    ----- 
 C:\Scripts\Containers    True 
 C:\Scripts\HyperV        True 
 C:\Scripts\NanoServer    True 
 C:\Scripts\NoSuchFolder False

You could save the output as a CSV for later work if required

Comments are closed.