I want to show the names of the files of some folder showing a counter before it. For example, if the folder has the following files:
file1.txt
file2.txt
file3.txt
I want to show in the powershell screen the folowing:
1 - file1.txt
2 - file 2.txt
3 - file3.txt
I wrote the following code to do that:
$maxfile=Get-ChildItem -Path C:\directory | Measure-Object | %{$_.Count}
For ($i=0; $i -le $maxfile-1; $i++){
$j=$i+1
Write-Host -NoNewline "$j "
Get-ChildItem -Path C:\directory -name | Select-Object -First 1 -Skip $i
}
It worked the way I wanted perfectly, but when there's a lot of files it takes quite a while to run it. I'm new with powershell and wonder if there is there some more direct way of doing this.
Why so difficult? I think this will already do what you want:
$Folder = 'C:\Directory'
$i = 1
Get-ChildItem -Path $Folder -File | Sort-Object Name | ForEach-Object {
"{0:D3} - {1}" -f $i++, $_.Name
}
Result:
001 - file1.txt 002 - file2.txt 003 - file3.txt ...
You can leave out the | Sort-Object Name
.
This will add a counter with leading zeroes. I chose to display 3 digits, so maximum is 999 items, but you're welcome to increase that number in {0:D3}