Список файлов в папке, которые соответствуют виду

281
Greedo

В Windows Search я могу использовать kind:=music OR kind:=videoвсе результаты в папке / подпапках, которые относятся к этому типу мультимедиа.

Есть ли способ повторить это с помощью команды, как dirв командной строке, или мне нужно будет сделать какие-то необычные манипуляции с моей экспортированной картой вида, Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\KindMap чтобы получить список расширений файлов для поиска. Тогда что - то вроде этого

В конечном итоге я после CSV или эквивалентных со всеми файлами, соответствующими критериям поиска

1

2 ответа на вопрос

2
LotPings

Первая пакетная попытка работает только наполовину, так как findstr капитулирует над большим количеством расширений в документах Kinds, музыке, изображениях и видео.

РЕДАКТИРОВАТЬ 2-ую рабочую версию с (некрасивым) временным файлом, содержащим расширения Kinds

:: Q:\Test\2018\07\20\SU_1341778.cmd :: DirKind.cmd music x:\path\folder @Echo off  :: Possible Kind_ type strings Set "Kinds=calendar communication contact document email link music picture" Set "Kinds=%Kinds% playlist program recordedtv searchfolder video"  Echo=%Kinds%|Findstr /i "%~1" 2>&1>Nul ||(Echo invalid Kind:%1 &TimeOut 5&Exit /B 1)  Set "TempFile=%temp%\Kind_%~1.ext" :: Build Kind_ string enumerating extensions Set "Key=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\KindMap" ( For /f "tokens=1,3" %%A in ( 'reg query "%Key%"^|find "%~1"' ) do Echo=%%A ) > "%TempFile%"  Echo Dir all files of Kind %1 in folder "%~2" Call Set "Kind=%%Kind_%1%%" For /f "delims=" %%A in ( 'Dir /B /A-d "%~2\*" ^| Findstr /i /E /G:"%TempFile%" ' ) Do Echo %%A 

Образец вывода

> Q:\Test\2018\07\20\SU_1341778.cmd link "%USERPROFILE%\Desktop" Dir all files of Kind link in folder "C:\Users\LotPings\Desktop" Access 2016.lnk ClassicStartMenu.exe - Verknüpfung.lnk Excel 2016.lnk FreeCommander XE.lnk Microsoft Edge.lnk OneNote 2016.lnk Outlook 2016.lnk PowerPoint 2016.lnk Publisher 2016.lnk shutdown.exe.lnk UltraVNC Server.lnk UltraVNC Settings.lnk UltraVNC Viewer.lnk WinDirStat.lnk Windows 10-Update-Assistent.lnk Word 2016.lnk 
1
saniboy

Всякий раз, когда я ищу что-то конкретное в моих каталогах, мне нравится этот лайнер

Get-ChildItem -Recurse -ErrorAction SilentlyContinue -Path C:\Users\ -Include*.ext 

так что пример в вашем случае будет

Get-ChildItem -Recurse -ErrorAction SilentlyContinue -Path C:\Users\[Uname]\Downloads -Include *.mp3,*.mov; # etc 

Из текста справки

-Path <String[]> Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).  -Recurse [<SwitchParameter>] Indicates that this cmdlet gets the items in the specified locations and in all child items of the locations.  -Include <String[]> Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt. Wildcards are permitted.  The Include parameter is effective only when the command includes the Recurse parameter or the path leads to the contents of a directory, such as C:\Windows\*, where the wildcard character specifies the contents of the C:\Windows directory. 

Я проведу поиск по папке сценариев, ища файлы PowerShell и Bash в качестве примера:

Get-ChildItem -Recurse -ErrorAction SilentlyContinue -Path .\Desktop\scripts\ -Include *.ps1,*.sh 

Результат:

 Directory: C:\Users\[user]\Desktop\scripts\Bash   Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 1/22/2018 8:03 PM 84 runit.sh   Directory: C:\Users\[user]\Desktop\scripts\PS   Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 4/19/2018 9:04 PM 173 pass_d.ps1 -a---- 9/7/2017 4:45 PM 345 refresh.ps1 -a---- 5/11/2018 9:05 PM 1589 test.ps1 -a---- 4/20/2018 8:55 PM 273 wifi_list.ps1 

Это не будет принимать kind:=music,kind:=videoаргумент, но вы можете предоставить звездочки с расширениями файлов в виде массива для -Include *.mp3,*.movаргумента и аналогичным образом выполнять поиск в нескольких каталогах -Path /some/directory,some/directory2. Выполнение этой же однострочной команды | Export-Csv [filename].csvсохранит ваши результаты в виде файла .csv.

Совет : в PowerShell доступно завершение табуляции, поэтому вам не нужно вводить каждый аргумент. get-ch<tab>> Get-ChildItem, Get-ChildItem -i<tab>> Get-ChildItem -Includeи т. д.