internal/functions/Get-ChildScriptItem.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
function Get-ChildScriptItem {
    [CmdletBinding()]
    Param (
        [object[]]$Path
    )
    Function Get-ChildItemDepth ([System.IO.FileSystemInfo]$Item, [int]$Depth = 0, [bool]$IsAbsolute) {
        Write-PSFMessage -Level Debug -Message "Getting child items from $Item with current depth $Depth"
        foreach ($childItem in (Get-ChildItem $Item)) {
            if ($childItem.PSIsContainer) {
                Get-ChildItemDepth -Item (Get-Item $childItem.FullName) -Depth ($Depth + 1)
            }
            else {
                Add-Member -InputObject $childItem -MemberType NoteProperty -Name Depth -Value $Depth
                # if a relative path can be build to the file item, use relative paths, otherwise, use absolute
                if ($childItem.FullName -like "$(Get-Location)\*" -and !$IsAbsolute) {
                    $srcPath = Resolve-Path $childItem.FullName -Relative
                }
                else {
                    $srcPath = $childItem.FullName
                }
                Add-Member -InputObject $childItem -MemberType NoteProperty -Name SourcePath -Value $srcPath -PassThru
            }
        }
    }
    foreach ($p in $Path) {
        if ($p.GetType() -in @([System.IO.FileSystemInfo], [System.IO.FileInfo])) {
            Write-PSFMessage -Level Verbose -Message "Item $p ($($p.GetType())) is a File object"
            $stringPath = $p.FullName
            $isAbsolute = $true
        }
        else {
            Write-PSFMessage -Level Verbose -Message "Item $p ($($p.GetType())) will be treated as a string"
            $stringPath = [string]$p
            $isAbsolute = Split-Path -Path $stringPath -IsAbsolute
        }
        if (!(Test-Path $stringPath)) {
            Stop-PSFFunction -EnableException $true -Message "The following path is not valid: $stringPath"
            return
        }
        foreach ($currentItem in (Get-Item $stringPath)) {
            Get-ChildItemDepth -Item $currentItem -Depth ([int]$currentItem.PSIsContainer) -IsAbsolute $isAbsolute
        }
    }
}