【问题标题】:Print counting before the names of the files在文件名之前打印计数
【发布时间】:2019-03-07 13:40:55
【问题描述】:

我想显示某个文件夹的文件名,该文件夹前面有一个计数器。例如,如果文件夹有以下文件:

file1.txt
file2.txt
file3.txt

我想在 powershell 屏幕中显示以下内容:

1 - file1.txt
2 - file 2.txt
3 - file3.txt

为此,我编写了以下代码:

$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 
}

它以我想要的方式完美运行,但是当文件很多时,运行它需要相当长的时间。我是 powershell 新手,想知道是否有更直接的方法。

【问题讨论】:

  • Get-ChildItem 'C:\Directory'|%{$i=0}{"{0,3} - {1}" -f ++$i,$_}

标签: powershell file count get-childitem


【解决方案1】:

为什么这么难?我认为这已经可以满足您的要求了:

$Folder = 'C:\Directory'
$i = 1
Get-ChildItem -Path $Folder -File | Sort-Object Name | ForEach-Object {
    "{0:D3} - {1}" -f $i++, $_.Name
}

结果:

001 - file1.txt
002 - file2.txt
003 - file3.txt
...

您可以省略| Sort-Object Name

这将添加一个带有前导零的计数器。我选择显示 3 位数字,因此最多显示 999 个项目,但欢迎您在 {0:D3} 中增加该数字

【讨论】:

  • 谢谢!我最近开始使用 powershell 并且不知道这是可能的。效果很好。
  • @Edson 不客气。如果您发现它解决了您的问题,请考虑accepting the answer,以帮助其他人更轻松地找到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 2019-07-07
  • 2014-10-03
  • 2014-08-21
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多