Forum Discussion
Select-Object Substring Blank
- May 23, 2022
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
Thisisit I couldn't get it to work nicely in one line so.. a bit larger script:
#Set total variable to null
$total = @()
#Set directory to scan
$directory = 'D:\test'
#Get all txtfiles from $directory path and put them in $variable
#If length of directory name is greater than 10, select last ten characters
#If length is shorter, just add it to the list
foreach ($txtfile in Get-ChildItem -filter *.txt -Recurse -Path $directory | Where-Object { -not $_.PSISContainer }) {
if ($txtfile.Directory.name.length -gt 10) {
$data = [PSCustomObject]@{
Directory = $txtfile.DirectoryName.substring($txtfile.DirectoryName.length - 10, 10)
Name = $txtfile.Name
}
}
else {
$data = [PSCustomObject]@{
Directory = $txtfile.Directory.Name
Name = $txtfile.Name
}
}
$total += $data
}
#output found items
$total
This will result in a output like this:
Directory Name
--------- ----
test x.txt
1234567890 y.txt
qrstuvwxyz z.txt
Test directories were like this: