functions/utility/Join-PSFPath.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function Join-PSFPath
{
<#
    .SYNOPSIS
        Performs multisegment path joins.
     
    .DESCRIPTION
        Performs multisegment path joins.
     
    .PARAMETER Path
        The basepath to join on.
     
    .PARAMETER Child
        Any number of child paths to add.
     
    .PARAMETER Normalize
        Normalizes path separators for the path segments offered.
        This ensures the correct path separators for the current OS are chosen.
     
    .EXAMPLE
        PS C:\> Join-PSFPath -Path 'C:\temp' 'Foo' 'Bar'
     
        Returns 'C:\temp\Foo\Bar'
     
    .EXAMPLE
        PS C:\> Join-PSFPath -Path 'C:\temp' 'Foo' 'Bar' -Normalize
     
        Returns 'C:\temp\Foo\Bar' on a Windows OS.
        Returns 'C:/temp/Foo/Bar' on most non-Windows OSes.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $Path,
        
        [Parameter(ValueFromRemainingArguments = $true)]
        [string[]]
        $Child,
        
        [switch]
        $Normalize
    )
    
    process
    {
        $resultingPath = $Path
        
        foreach ($childItem in $Child)
        {
            $resultingPath = Join-Path -Path $resultingPath -ChildPath $childItem
        }
        
        if ($Normalize)
        {
            $defaultSeparator = [System.IO.Path]::DirectorySeparatorChar
            $altSeparator = [System.IO.Path]::AltDirectorySeparatorChar
            # Alt Directory Separator Char is not reliable on all platforms
            if ($defaultSeparator -eq $altSeparator)
            {
                if ($defaultSeparator -eq '\') { $altSeparator = '/' }
                else { $altSeparator = '\' }
            }
            $resultingPath = $resultingPath.Replace($altSeparator, $defaultSeparator)
        }
        
        $resultingPath
    }
}