Substring from object Get-ChildItem Name PSParentPath Table Output

84 views Asked by At

Acknowledged that I am a Powershell Rookie ...

Get-ChildItem -Recurse |
    select-object -property Name, Attributes, PSParentPath

Gives table format output and data as desired, but looking to so-called substring the PSParentPath property output to truncate / remove the first 38 characters from 0 index (starting character) with resultant table view of and or "Export-Csv" file.

I have tried assigning a string VAR to the PSParentPath and manipulate the output - which I am able to redact / remove the first 38 characters of the resultant PSParentPath string value. But the output of all values (Name, Attributes, $PSParentPath.substring(38)) are returned / displayed as individual line items in the CMD Prompt instead of in the following desired table format;

Name                 Attributes            PSParentPath
---------           -----------            -----------
Filename1               Archive            C:\temp\
DirectoryName1          Directory          C:\temp\DirectoryName1

Versus not desired result: (seemingly random order from my limited understanding)

Filename1
DirectoryName1
Archive
C:\temp\
Directory
C:\temp\DirecotryName1
1

There are 1 answers

1
Santiago Squarzon On

You can use a calculated property in this case:

Get-ChildItem -Recurse |
    Select-Object Name, Attributes, @{ N = 'PSParentPath'; E= { $_.PSParentPath.SubString(38) }}

Another approach that doesn't require string manipulation:

$expression = {
    if ($_ -is [System.IO.FileInfo]) {
        return $_.DirectoryName
    }

    $_.Parent.FullName
}

Get-ChildItem -Recurse |
    Select-Object Name, Attributes, @{ N = 'ParentPath'; E = $expression }