PowerShell for Windows Admins

Jun 29 2017   2:56PM GMT

Joining and Testing folder paths

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: