Пакетный файл для подсчета символов в именах файлов - PullRequest
0 голосов
/ 06 сентября 2018

Я довольно новичок в создании пакетных файлов (и в программировании в целом) и хотел попросить некоторую помощь относительно этой задачи. Мне нужно создать командный файл, который я могу поместить в сетевую папку и запустить, чтобы подсчитать все символы каждого файла PDF, TIF и TIFF, с которым он сталкивается. Я хотел бы, чтобы он выполнял поиск по каталогу, из которого он запускается, а также по любым подпапкам внутри, а затем возвращался с общим счетчиком в конце.

Пока что он считает каждый файл, но я бы хотел настроить его таким образом, чтобы исключить специальные символы (в основном подчеркивания) из числа символов. Я также не смог успешно получить его, чтобы дать мне общий счет в конце. Мне удалось кое-что изменить, когда я изучал учебники в Интернете, но, к сожалению, я сейчас нахожусь в такой точке, когда у меня заканчивается время для работы. Буду очень признателен за любую помощь или руководство.

@ECHO OFF
SETLOCAL
PUSHD %~dp0
FOR /R %%G in (*.PDF *.TIF *.TIFF) DO (
 SET FileName=%%~nG
 SETLOCAL ENABLEDELAYEDEXPANSION
 FOR /l %%L IN (2048,-1,0) DO IF NOT DEFINED CH (
 SET CH=!FileName:~%%L,1!
 IF DEFINED CH SET /a CH=1+%%L & ECHO !FileName!: !CH! Characters
 )
 ENDLOCAL
)
POPD
ECHO:
ECHO Total Number of Characters: %Total%
REM Not yet sure where to put Set /a Total=%Total%+%CH%
ECHO:
PAUSE
GOTO :EOF

РЕДАКТИРОВАТЬ: Для всех, кто может наткнуться на эту тему. Я не смог понять, как полностью выполнить это с помощью Batch, но я смог сделать это в PowerShell. Вот сценарий PS, который я придумал.

# This script looks through all folders and subfolders that are sitting next to or below the powershell file. It gives the total file and character count of all PDFs, TIFFs, and TIFs that it finds.

# Clear all default PowerShell messages and remove from view.
Clear-Host


# Make the view more orderly.
Write-Output "" "---Processing Files---" ""


# Look through the current directory and all sub-folders for the names of .pdfs, .tifs, and .tiffs and show them as a list.
Get-ChildItem -Recurse -Name -Include *.pdf,*.tif,*.tiff


# Get the total number of files.
$LineCount = (Get-ChildItem -Recurse -Name -Include *.pdf,*.tif,*.tiff | Measure-Object -Line).Lines

# Set ChracterCount to the complete list of files and select ONLY the name portion so that no folder names are shown.
$CharacterCount = (Get-ChildItem -Recurse -Include *.pdf,*.tif,*.tiff | Select -ExpandProperty Name)

# Replace all of the extensions and underscores in the filenames with nothing so that we only have the characters that were manually typed by someone.
$CharacterCount = $CharacterCount -Replace ".pdf","" -Replace ".tiff","" -Replace ".tif","" -Replace "_",""

# Gives us the final character count as a single number.
$CharacterCount = ($CharacterCount | Measure-Object -Character).Characters


# Show the viewer the final counts.
Write-Output "" "---All Files Processed---" "" "" "Total File Count: $LineCount" "" "" "Total Character Count: $CharacterCount" "" ""


# Gives the final closing message to the viewer so that they can exit with any key. Does not show message when script is run from ISE.
if ($Host.Name -eq "ConsoleHost")
{
    Write-Host "Press Any Key to Exit."
    $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
...