Notice: Due to size constraints and loading performance considerations, scripts referenced in blog posts are not attached directly. To request access, please complete the following form: Script Request Form Note: A Google account is required to access the form.
Disclaimer: I do not accept responsibility for any issues arising from scripts being run without adequate understanding. It is the user's responsibility to review and assess any code before execution. More information

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

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