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

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s