How to resolve the algorithm Find common directory path step by step in the PowerShell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Find common directory path step by step in the PowerShell programming language

Table of Contents

Problem Statement

Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths: Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'. If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Find common directory path step by step in the PowerShell programming language

Source code in the powershell programming language

<#
.Synopsis
    Finds the deepest common directory path of files passed through the pipeline.
.Parameter File
    PowerShell file object.
#>
function Get-CommonPath {
[CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [System.IO.FileInfo] $File
    )
    process {
        # Get the current file's path list
        $PathList =  $File.FullName -split "\$([IO.Path]::DirectorySeparatorChar)"
        # Get the most common path list
        if ($CommonPathList) {
            $CommonPathList = (Compare-Object -ReferenceObject $CommonPathList -DifferenceObject $PathList -IncludeEqual `
                -ExcludeDifferent -SyncWindow 0).InputObject
        } else {
            $CommonPathList = $PathList
        }
    }
    end {
        $CommonPathList -join [IO.Path]::DirectorySeparatorChar
    }
}


"C:\a\b\c\d\e","C:\a\b\e\f","C:\a\b\c\d\x" | Get-CommonPath
C:\a\b


  

You may also check:How to resolve the algorithm Prime conspiracy step by step in the Perl programming language
You may also check:How to resolve the algorithm Determine if a string is numeric step by step in the True BASIC programming language
You may also check:How to resolve the algorithm Factorial step by step in the Scala programming language
You may also check:How to resolve the algorithm Count occurrences of a substring step by step in the BASIC programming language
You may also check:How to resolve the algorithm Maze solving step by step in the D programming language