且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在PowerShell中递归检索具有特定扩展名的任何文件?

更新时间:2022-11-28 13:12:59

如果不需要按长度排序,您可以使用 -Name 参数让 Get-ChildItem 只返回名称,然后使用 [System.IO.Path]::GetFileNameWithoutExtension() 去掉路径和扩展名:

If sorting by Length is not a necessity, you can use the -Name parameter to have Get-ChildItem return just the name, then use [System.IO.Path]::GetFileNameWithoutExtension() to remove the path and extension:

Get-ChildItem -Path .\ -Filter *.js -Recurse -File -Name| ForEach-Object {
    [System.IO.Path]::GetFileNameWithoutExtension($_)
}

如果需要按长度排序,请删除 -Name 参数并输出每个 FileInfo 对象的 BaseName 属性.您可以将输出(在两个示例中)通过管道传输到 clip,以将其复制到剪贴板:

If sorting by length is desired, drop the -Name parameter and output the BaseName property of each FileInfo object. You can pipe the output (in both examples) to clip, to copy it into the clipboard:

Get-ChildItem -Path .\ -Filter *.js -Recurse -File| Sort-Object Length -Descending | ForEach-Object {
    $_.BaseName
} | clip

如果您想要完整路径,但没有扩展名,请将 $_.BaseName 替换为:

If you want the full path, but without the extension, substitute $_.BaseName with:

$_.FullName.Remove($_.FullName.Length - $_.Extension.Length)