Powershell : Count File Names and provide report


In this example I had run another script (also on this blog) to output files using the following format:

<device-name>_compliant.txt
<device-name>_noncompliant.txt

The job of this script was simple, it needed to count all the compliant names and non compliant names then then where none compliant report the device name, this means that if a device called "Honeypot" was "non-complaint" it should report this device name as a complaint device when the filename was:

Honeypot_noncompliant.txt

This is result of the execution of the script and the result is positive:


Script : FileNameCounter.ps1

# Define the folder path
$folderPath = "\\smbshare\Audit"

# Initialize counters
$compliantCount = 0
$nonCompliantCount = 0

# Initialize an array to store non-compliant device names
$nonCompliantDevices = @()

# Get all files in the folder
$files = Get-ChildItem -Path $folderPath -File

# Iterate through each file
foreach ($file in $files) {
    $fileName = $file.Name
    
    # Check if the filename contains 'compliant' or ends with '_noncompliant.txt'
    if ($fileName -match "(?i)compliant") {
        $compliantCount++
    } 
    if ($fileName -match "_noncompliant\.txt$") {
        $nonCompliantCount++
        
        # Extract the device name (everything before the last underscore)
        $deviceName = $fileName -replace '_noncompliant\.txt$', ''
        $nonCompliantDevices += $deviceName
    }
}

# Output the results
Write-Host "Number of compliant files: $compliantCount"
Write-Host "Number of non-compliant files: $nonCompliantCount"

# Output non-compliant device names
if ($nonCompliantDevices.Count -gt 0) {
    Write-Host "`nNon-compliant devices:"
    foreach ($device in $nonCompliantDevices) {
        Write-Host $device
    }
}
Previous Post Next Post

نموذج الاتصال