Forum Discussion

Thisisit's avatar
Thisisit
Copper Contributor
May 21, 2022
Solved

Select-Object Substring Blank

Hello, thank you for you assistance in advance.  I'm trying to grab the last 10 characters of the Directory.  For some reason it's returning blank, and I'm not able to figure out why.  Below is what ...
  • LainRobertson's avatar
    May 23, 2022

    Thisisit 

     

    Hi.

     

    You're likely getting a blank because there's not such function named "Substring" in PowerShell. What does exist is the Substring() method on a string object, but you're not referencing that, hence the blank result.

     

    Secondly, the property "Directory" is of type [System.IO.FileSystemInfo], not [System.String]. PowerShell can and does do various kind of implicit conversions but it's inefficient, occasionally ambiguous and therefore hard to debug for the uninitiated. Instead of "Directory", use the "DirectoryName" property, as it is of type [System.String].

     

    You do not need the "Where" clause in this example. Get-ChildItem provides a parameter named "-File" which does what your "Where" clause does, just more efficiently.

     

    Lastly, you need to perform some bounds checking as a call .Substring() cannot have a negative number for the starting position, else it will throw a .NET exception.

     

    With those considerations in mind, here's an adjusted version of your command that does what you've asked.

     

    Get-ChildItem -File -Filter *.txt -Recurse -Path "C:\SamIam\Listings" | Select-Object @{Name='Directory2';e={ if ($_.DirectoryName.Length -ge 10) { $_.DirectoryName.Substring($_.DirectoryName.Length - 10) } else { $_.DirectoryName } }},Name,DirectoryName

     

     

    Cheers,

    Lain

Resources