1

Hi I am new to powershell.

I have a folder 2017 which has 12 subfolders( from Jan to Dec). Inside the subfolders, there are many more folders(Eg Jan will have 31 folders, Feb will have 28 folders, March will have 31 folder and so on). Inside these folders there will be 10 files. I need to write a script wherein I have to loop inside these folders,subfolders and check if these 10 files are present. Can anyone please guide me?

I will need to add conditions like: If the 2017 folder does not have 12 files then fail, if the Jan folder does not have 31 folders then fail, if the files within these 31 folders are not present then again a failure(there will be 10 files inside each of the 31 folders). Any suggestions on how this can be implemented?

Please let me know if there is any information that is required.

Thank you.

1 Answers1

2

Code to to meet the specification is pretty simple in PowerShell -- if you really only need to "FAIL".

Though the simplest version (shown first) doesn't indicate the failure location, there's a simple enhancement suggestion at the bottom for filtering for the failing directories:

$BasePath = 'C:\'   # Parent of the 2017 directory
#  *\*\*  --> MONTHS\DAYS\FILES 
$totals = dir "$BasePath\2017\*\*\*" -file      | 
          Group-Object directoryname -noElement | 
          measure count -minimum -maximum -sum 

IF ($Totals.Sum -ne 3650 -or $Totals.Maximum -ne 10 -or $Totals.Minimum -ne 10) { 
  "FAIL" 
} else {
  "Succeed"
}
$Totals  # just show the totals if you wish

The 3 asterisks in the search Path are wildcards for the three directory levels: : MONTH level, DAY level, and FILES. 2017***

Many PowerShell cmdlets allow full wildcarding in multiple 'directory' elements of a a path specification.

  1. MONTH level (the 12 months of the year)
  2. DAY level (28-31 depending on month)
  3. FILE level (should be 10 each)

The final file pattern could be changed to something like "*.log" or whatever will match a correctly added file.

Each 'day' directory should have 10 files, and in 2017 there were 365 days * 10 files per days so the total expected is 3650 (easy to add a check for leap year if you need to check 2016 or 2020 etc.)

If shown, Group-Object output (for my 'C:\Program Files' directory) looks like this:

Count Name
----- ----
  203
   12 C:\Program Files\7-Zip
    3 C:\Program Files\Appli...
   18 C:\Program Files\Beyon...
    4 C:\Program Files\Bonjour
   20 C:\Program Files\Class...
   ...

Measure-Object output (stored in $Totals) looks like this:

Count    : 41
Average  :
Sum      : 747
Maximum  : 203
Minimum  : 1
Property : Count

Since every directory must have 10 files, each should have exactly 10 DIRECTORY names (in the GROUP-OBJECT count) therefore the MINIMUM and MAXIMUM must both be 10.

You could identify the failing directories by filtering the Group-Object results with

| Where-Object Count -ne 10

Enjoy.

HerbM
  • 521
  • 6
  • 14