Используйте select string для рекурсивного поиска строк

I am using powershell to delete files in folders that are last modified older than 30 days. (LastWriteTime).
My script works if the files are in the path specified but not if they are in a subfolder of that root path. It seems the folder has been considered in the script and I am at a loss as to why.
I get one file returned out of 2000 files that were created, modified, accessed 4 months ago.

My folder structure is: P:\Root/SubFolderRoot/SubFolder1/SubFolder1 ..-.. SubFolder9
There are multiple subs and any of them can contain files older than 30 days.. I am only interested in the files older than 30 days regardless of the Folder Modified, Accessed, Created Times. I have searched on stack and can provide several almost exact code examples to mine but they do not work.

$folderTree = 'P:\Root\SubFolderRoot'
$refDate = (Get-Date).AddDays(-30)
Get-ChildItem -Path $folderTree -File -Recurse | 
    Where-Object {-not $_.PSIsContainer -and $_.LastWriteTime -lt $refDate } 
    | foreach-object { Write-Host  $_.FullName }

# Where-Object { $_.LastWriteTime -lt $refDate } 
# Select-Object FullName

asked Dec 13, 2023 at 16:12

Ken's user avatar

$folderTree = 'P:\Root\SubFolderRoot'
$refDate = (Get-Date).AddDays(-30).Date
Get-ChildItem -Path $folderTree -Filter * -File -Recurse | 
    Where-Object { $_.LastWriteTime -lt $refDate } |
    Remove-Item -WhatIf

Should do what you want.
Using the -WhatIf switch will cause the code to not delete anything, just output in the console what would happen.
Once you are satisfied the correct files are listed, take off the -WhatIf switch and run again.

answered Dec 14, 2023 at 15:33

Theo's user avatar

8 gold badges26 silver badges43 bronze badges

Используйте select string для рекурсивного поиска строк

Как магией: Мгновенное извлечение файлов из глубин папок одной волшебной строкой.

Использование командной строки – это как невидимая магия, доступная лишь избранным. Но сегодня мы раскрыли лишь краешек завесы тайны. Перед вами открывается безграничный мир возможностей, где одна строка кода обладает мощью всей программы. Добро пожаловать в мир, где каждая задача решается мгновенно, а каждая проблема уходит как на взмах магической палочки.

Часто перед нами стоит задача, казалось бы, простая и одновременно трудоёмкая: вытащить файлы конкретного формата из многочисленных папок и подпапок. Задача упрощается, если знать, куда именно залезть. Но что делать, когда папок слишком много, а времени на изыскания – как на марсианский песок? Вариантов масса: от ввода бесконечного ряда команд до попыток освоения нового языка программирования на лету. Однако, к счастью, есть более элегантное решение. И мы склоняемся перед могуществом командной строки – инструмента, несущего в себе силу простоты и эффективности.

Сегодня подарим два секретных ключа к закрытым дверям папок, чтобы раскрыть их содержимое единственным заклинанием.

Заклинание Первое: Извлечение сокровищ формата CSV

Представим, что вам необходимо собрать все файлы с расширением .csv в одну папку. Никаких сложностей, только ваша командная строчка и следующее заклинание:

for /R "C:\ИсходнаяПапка\" %f in (*.csv) do copy "%f" "C:\ЦелеваяПапка\"

Давайте пошагово расшифруем эту магию:

  • for – начало нашего волшебства, знакомит нас с циклом команд.

  • /R – рассыпая волшебный порошок рекурсии, дает команде мощь проникать в каждую подпапку.

  • "C:\ИсходнаяПапка\" – та самая пещера, в глубинах которой скрыты наши сокровища.

  • %f – волшебный мешочек, в который будут собираться найденные драгоценности (пути к файлам).

  • in (*.csv) – волшебное заклинание, определяющее, что мы собираемся искать лишь те сокровища, что сияют расширением .csv.

  • do – слово-ключ, начинающее исполнение заклинания сбора.

  • copy – команда, заботливо переносящая наши сокровища в новое место.

  • "%f" – указание на наш мешочек с собранными путями к файлам.

  • "C:\ЦелеваяПапка\" – сокровищница, где будут храниться извлеченные файлы.

:/>  Как удалить все данные пользователя в Windows 7 отключение учетной записи? Как создать и удалять администратора на Win 10

Таким образом, мы легко и просто, словно по мановению волшебной палочки, собираем все файлы формата .csv в одном месте.

Заклинание Второе: Мудрость сохранения редких файлов с одинаковыми названиями

Путешествуя дальше по лабиринтам наших многослойных папок, мы нередко сталкиваемся с тайными копиями сокровищ – файлами, имена которых повторяются, словно отголоски в пещере. В таких случаях, без умной магии идентификации и переименования, мы рискуем потерять часть своих находок, ведь в одном месте не может уживаться два сокровища с одинаковыми именами. Отважно шагая на помощь, второе заклинание преображает сложность ситуации в великолепную простоту:

for /R "C:\ИсходнаяПапка\" %f in (*.csv) do @for %p in ("%~dpf.") do @copy "%f" "C:\ЦелеваяПапка\%~nxp_%~nxf"

Рассмотрим этот алхимический рецепт под микроскопом магии:

  • **for /R “C:\ИсходнаяПапка\”%f in (*.csv)** – вызывает духи рекурсии, отправляясь в поиски файла с расширением .csv на всех уровнях исходной папки.

  • **do** – начало исполнения воли мага для каждого обнаруженного тайного свитка.

  • **”C:\ЦелеваяПапка\%~nxp_%~nxf”** – формула создания уникального имени сокровища, объединяющая его прошлое (папку-хранительницу) и сущность (оригинальное имя и расширение), защищая таким образом от забвения.

Так, наше второе заклинание несёт в себе мудрость древних магов, позволяя сохранить каждый файл, окутанный аурой уникальности, благодаря чарующему соединению его корней и сути.

Завершение путешествия по миру файловой магии

Прокладывая пути сквозь густые заросли папок и извилистые тропы подпапок, мы открыли для себя волшебство, доступное лишь единицам. От первого заклинания, собирающего разбросанные по империи файлы в одно царство, до второго, охраняющего их уникальность в библиотеке времени – мы научились управлять хаосом с помощью строк кода.

Теперь, когда каждый желающий может стать магом в своем царстве файлов, уготовано место чудесам. С этих пор, всякий, кто осмелится применить изученные заклинания, сможет с легкостью вызывать и управлять данными, как волшебник – стихиями, доказывая, что истинная магия заключается в знании.

Открывая двери в этот новый мир, помните: сила лежит не в сложности заклинаний, а в их применении. В ваших руках лежит ключ к пониманию тайного языка, способного превращать беспорядок в гармонию, и каждый файл, каждая папка теперь – подданные вашей воли. Добро пожаловать в мир, где магия кода открывает безграничные возможности создавать, исследовать и преображать.

:/>  Ping Test - Online проверка пинга интернета - бесплатно измерить пинг до сервера | SPEEDTEST

You might encounter situations where you need to count the number of files present in a folder using PowerShell. In this tutorial, I will explain how to count files in a folder using PowerShell.

To count files in a folder using PowerShell, you can use the Get-ChildItem cmdlet combined with the Measure-Object cmdlet. For example, to count all files in a specific folder, you would use $fileCount = (Get-ChildItem -Path “C:\Your\Target\Directory” -File).Count. This command will return the number of files in the specified directory, excluding subdirectories and non-file items.

One of the easiest ways to count files in a folder using PowerShell is to use the Count function. Here is a complete PowerShell example.

$folderPath = "C:\MyFolder"
$fileCount = (Get-ChildItem -Path $folderPath).Count
Write-Host "There are $fileCount files in $folderPath"

This script sets the target directory path to a variable and then uses the Get-ChildItem cmdlet to retrieve the items in the directory. The .Count method is then used to count the items. The result is displayed using Write-Host.

You can see the screenshot below after I executed the script using VS code.

Count Files in a Folder Using PowerShell

Counting Files Recursively

If you need to count all files within a folder and its subfolders (recursively) using PowerShell, you can add the -Recurse parameter.

$folderPath = "C:\MyFolder"
$fileCount = (Get-ChildItem -Path $folderPath -Recurse | Measure-Object).Count
Write-Host "There are $fileCount files in $folderPath and its subfolders"

Here, Get-ChildItem is piped to Measure-Object, which counts all objects passed to it, providing the total file count, including subdirectories.

You can see the output in the screenshot below, and it shows me exactly how many files there are in the folder and subfolders.

how to Count Files in a Folder Using PowerShell

Count Specific File Types in a folder

To count the number of a specific file type, you can use the -Filter parameter. For example, to count .txt files in a folder using PowerShell, you can write the script like below:

$folderPath = "C:\MyFolder"
$fileType = "*.txt"
$fileCount = (Get-ChildItem -Path $folderPath -Filter $fileType -Recurse | Measure-Object).Count
Write-Host "There are $fileCount text files in $folderPath and its subfolders"

This script will count all .txt files in the specified folder and its subfolders.

Exclude Folders in the Count

You might just want to count files inside a folder and you want to exclude the subfolders. You can do this by using the -Exclude parameter in PowerShell.

$folderPath = "C:\MyFolder"
$excludeFolders = @("Subfolder1", "Subfolder2")
$fileCount = (Get-ChildItem -Path $folderPath -Recurse -Exclude $excludeFolders | Measure-Object).Count
Write-Host "There are $fileCount files in $folderPath excluding certain subfolders"

This script will count all files in the directory and its subdirectories, excluding “Subfolder1” and “Subfolder2”.

Find Files larger than X MB in the Folder

$folderPath = "C:\MyFolder"
$fileCount = (Get-ChildItem -Path $folderPath -Recurse | Where-Object { $_.Length -gt 1MB } | Measure-Object).Count
Write-Host "There are $fileCount files larger than 1MB in $folderPath and its subfolders"

The Where-Object cmdlet is used here to filter files based on size before counting them with Measure-Object.

Performance Considerations

When working with large directories, performance can be an issue. To improve performance, you can use the -File switch with Get-ChildItem to only retrieve files (skipping directories), which can speed up the command:

$folderPath = "C:\MyFolder"
$fileCount = (Get-ChildItem -Path $folderPath -Recurse -File | Measure-Object).Count
Write-Host "There are $fileCount files in $folderPath and its subfolders"

PowerShell count files in folder and subfolders

To count files in both a folder and its subfolders using PowerShell, you’ll want to use the Get-ChildItem cmdlet with the -Recurse parameter, which instructs PowerShell to include all subdirectories in its search. The -File parameter can be used to ensure that only files are counted, excluding directories from the count.

:/>  Удаленный доступ mstsc

Here’s a detailed explanation of how to perform this task:

  1. Open PowerShell: You can do this by searching for PowerShell in the Start menu or by right-clicking the Start button and selecting “Windows PowerShell” from the context menu.
  2. Use Get-ChildItem: The Get-ChildItem cmdlet retrieves the files and folders in the specified path. When used with the -Recurse parameter, it will recursively search through all the subdirectories.
  3. Filter for Files: The -File parameter ensures that only files are considered, excluding directories from the results.
  4. Count the Results: Pipe the output of Get-ChildItem to the Measure-Object cmdlet, which will count the objects that have been passed to it.

Here’s the complete PowerShell script to count files in a folder and its subfolders:

$folderPath = "C:\MyFolder"
$fileCount = (Get-ChildItem -Path $folderPath -Recurse -File | Measure-Object).Count
Write-Host "There are $fileCount files in $folderPath and its subfolders"

In this script:

  • $folderPath stores the path to the target directory.
  • Get-ChildItem -Path $folderPath -Recurse -File retrieves all files in the target directory and its subdirectories.
  • Measure-Object is piped (|) the list of files and uses its .Count property to count them.
  • Write-Host is used to output the result to the console.

This command is efficient and straightforward for counting files across a directory tree. Remember to replace "C:\MyFolder" with the actual path to the directory you want to analyze.

Conclusion

PowerShell provides different cmdlets for counting files in a folder, such as recursive counts, filtering by file type, excluding directories, and more.

In this PowerShell tutorial, I have explained how to count files in a folder in PowerShell using various methods.

You may also like:

Оставьте комментарий