Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, September 15, 2011 7:08 AM
Hi,
I am trying to make a script that will get a list of files and then manipulate the results to just take the first 8 characters.
$List = get-childitem "C:\windows"
$List |Format-Wide -Column 1 -property name
ForEach($File In $List)
{
write-host $File
$First8=$File.substring(0,7)
write-host $First8
}
When I run the script I get the error
Method invocation failed because [System.IO.FileInfo] doesn't contain a method
named 'substring'.
At ListFiles003.ps1:12 char:27
- $First8=$Package.substring <<<< (0,7)
+ CategoryInfo : InvalidOperation: (substring:String) [], Runtime
Exception
+ FullyQualifiedErrorId : MethodNotFound
I understand that the object $package is not a string which is why the .substring method is failing.
I don't know how to convert each $file to a string so that I can use the substring method.
Any ideas?
All replies (4)
Thursday, September 15, 2011 7:44 AM ✅Answered | 1 vote
Try this: $First8 = $file.Name.Substring(0,7)
Note that this will fail if the name is shorter then 8 characters.
Thursday, September 15, 2011 7:59 AM ✅Answered | 1 vote
I'll try to explain whats wrong.
The line "$First8=$File.substring(0,7)" will not work, because $File is a type file item, not a string. You can only use 'substring' on strings. In addition to this, not all filenames have 8 characters, so a filename like 1234.txt would not be changed.
The answer lies in using the basename property, as such:
$List = get-childitem "C:\windows"
$List |Format-Wide -Column 1 -property name
foreach ($File in $List)
{
Write-Host $File
$First8 = $File.basename
Write-Host $First8
}
[string](0..9|%{[char][int](32+("39826578840055658268").substring(($_*2),2))})-replace "\s{1}\b"
Thursday, September 15, 2011 9:08 AM
You can also use the join parameter. Then it doesn't matter if the string isn't long enough.
$First8 = $File.Name[0..7] -join ""
[0..7] will return an array with all chars as an seperate record.
-Join "" will make a string of this array.
Thursday, September 15, 2011 10:14 AM
Thanks a lot BigTeddy and VincentK!