PowerShell Project: Reporting Tool
A reporting tool is a script that gathers numbers from files and builds a summary. It reads the raw data, totals it, and writes one readable summary file.
Total the numbers in one file
Read the numbers and add them up. Print the total as one labelled line.
Set-Content -Path "north.txt" -Value @("10", "20", "30")
$values = Get-Content -Path "north.txt" | ForEach-Object { [int]$_ }
$total = ($values | Measure-Object -Sum).Sum
"North total: " + $totalBuild a summary file from a total
Put the total into a short list of lines. Write the lines to a summary file and read the file back.
Set-Content -Path "north.txt" -Value @("10", "20", "30")
$values = Get-Content -Path "north.txt" | ForEach-Object { [int]$_ }
$total = ($values | Measure-Object -Sum).Sum
$lines = @()
$lines += "Region: north"
$lines += "Total: " + $total
Set-Content -Path "summary.txt" -Value $lines
Get-Content -Path "summary.txt"Add group totals into a grand total
Total two groups separately. Add the two totals together for the grand total.
Set-Content -Path "north.txt" -Value @("10", "20", "30")
Set-Content -Path "south.txt" -Value @("5", "15")
$north = (Get-Content -Path "north.txt" | ForEach-Object { [int]$_ } | Measure-Object -Sum).Sum
$south = (Get-Content -Path "south.txt" | ForEach-Object { [int]$_ } | Measure-Object -Sum).Sum
"Grand total: " + ($north + $south)Example
Set-Content -Path "north.txt" -Value @("10", "20", "30")
Set-Content -Path "south.txt" -Value @("5", "15")
$north = (Get-Content -Path "north.txt" | ForEach-Object { [int]$_ } | Measure-Object -Sum).Sum
$south = (Get-Content -Path "south.txt" | ForEach-Object { [int]$_ } | Measure-Object -Sum).Sum
$grand = $north + $south
$northCount = (Get-Content -Path "north.txt").Count
$southCount = (Get-Content -Path "south.txt").Count
$report = @()
$report += "North total: " + $north
$report += "South total: " + $south
$report += "Grand total: " + $grand
$report += "North items: " + $northCount
$report += "South items: " + $southCount
Set-Content -Path "summary.txt" -Value $report
Get-Content -Path "summary.txt"Key points
- Gather data: Gathering data means reading the numbers stored in data files.
- Total: A total is the sum of a group of numbers.
- Summary file: A summary file is a text file that holds the totals in readable lines.
- Item count: An item count is how many numbers a data file holds.
- Grand total: A grand total is the sum of all the group totals.
In this example, the script first creates two data files with known numbers. It totals each file and adds the totals into a grand total. It also counts the items in each file. Then it writes all five results as lines in a summary file and prints the summary.
Note
The summary prints totals only, so a reader sees the result without the raw rows.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A reporting tool totals a north file at 60 and a south file at 20. What is the grand total it should print?