Projects Level: Advanced Chapter 18: PowerShell Automation Projects
Build a report module
A module is a package of functions you can load and reuse. In this project you build a small module with a report function that shapes results as custom objects and writes them to a CSV file.
Lesson 2 of 4 in Chapter 18: PowerShell Automation Projects. Previous step in this path: From functions to a tool. 3 learning objectives, 5 examples, and a knowledge check.
Start: what you will learn
A module is a package of functions you can load and reuse. In this project you build a small module with a report function that shapes results as custom objects and writes them to a CSV file.
Learning objectives
- Build a small module with a report function
- Shape results with PSCustomObject
- Export results with Export-Csv and describe a manifest
Concept in simple words
What it is: A module is a file or a set of files that holds functions you can load into PowerShell and reuse. In this project, the module file ends in .psm1, and it holds your functions. A report function is a function whose job is to gather facts and shape them into a clear result. A manifest is a small description file for a module, and it ends in .psd1. It names the module, its version, and which functions it exports, which means makes available to the user.
Why it works
Why it exists: A script file runs from top to bottom, every time, in one fixed order. That is fine for a single run, but it is awkward for reuse. A module solves a different problem. It lets you load only the functions you need, call them by name, in any order, and use them again in a fresh session. When you fix a function in the module file, every future session that loads the module gets the fix, instead of you having to copy the fix into many scripts.
What PowerShell does behind Import-Module: When you run Import-Module with a module file or manifest, PowerShell reads the file, runs the code that defines the functions, and makes the exported functions available in your session. Functions that are not listed for export stay hidden from the caller. That split is useful. You can keep small helper functions inside the module for your own use, and export only the functions that other people should call.
What a custom object really is: A custom object is an object you build yourself, with properties you choose, in an order you choose. In [PSCustomObject]@{ Computer = "srv1"; Service = "Spooler"; Status = "Running" }, each name before the equals sign becomes a property, and each value after it becomes the value of that property. The object is one row of your report. When you build many such objects with the same property names, you get a tidy table, where each row has the same columns.
What Export-Csv does behind the command: Export-Csv takes objects from the pipeline and turns them into text lines. The first line holds the property names, and those names become the column headers in the CSV file. Each following line holds one object, with its values separated by commas. A CSV file, which is a text file with values separated by commas, is easy to open in a spreadsheet, easy to share, and easy to check by eye, so it is a good output for a report.
What a manifest does, key by key: The manifest is a description, not the code itself. RootModule names the main module file that holds the code. ModuleVersion names the version, and it is the one key that must be present, so PowerShell always knows which version it is loading. FunctionsToExport lists the functions the module makes available. If that list does not match the real function names in the module file, the caller will not find the function, even though the code is present.
Think of it like this
Think of it like this: A script is like a single letter. A module is like a small handbook of useful letters you can open again and again. A manifest is like the title page of that handbook, with the name, the version, and a list of what is inside. If the title page lists a chapter that is not in the book, the reader will look for it and fail, so the title page must match the book exactly.
How it works, step by step
How it works, step by step, in order: First, plan the report. Decide what one row means, and which columns every row must have. Second, write a report function that gathers one fact at a time and builds a custom object for each result with [PSCustomObject]. Third, test the function in your session and read the objects on screen, before you save anything. Fourth, send the objects to Export-Csv with a file path, so the report is saved as a CSV file. Fifth, open the CSV file and check it. Sixth, describe the module in a manifest, with a name, a version such as 1.0.0, and the exported functions. Seventh, import the module in a fresh session and call the exported function, to prove the package works on its own.
How to shape good rows: Use the same property names in every row, in the same order. If one row uses Service and the next row uses ServiceName, the CSV will not line up cleanly, and the reader will struggle to compare rows. Put the most useful fact first, such as the computer name, then the item, then the result. Keep values short and plain. A report row should be readable at a glance, without needing to decode it.
How to choose a safe file path: A relative path such as .\report.csv means the file goes into your current folder. That is handy for a quick test, but it can surprise you later, because your current folder changes. For a tool you will run again, use a full path, or build the path from a folder you choose on purpose, and check that the folder exists before you export. If the folder does not exist, the export will fail, and that failure is easier to fix before the run than after it.
How to choose a version number: A version such as 1.0.0 is a starting version for a first finished tool. When you change the tool, raise the version, so people can tell the new copy from the old copy. Write a short note for each version, saying what changed and why. That note is small, but it saves a lot of confusion later, when someone asks why the report looks different from last week.
Let us walk through the first example, part by part: In [PSCustomObject]@{ Computer = "srv1"; Service = "Spooler"; Status = "Running" } | Export-Csv -Path .\report.csv -NoTypeInformation, the custom object builds one row with three facts. The pipe sends that row on. Export-Csv writes it to a file. -Path names the file. -NoTypeInformation leaves out an extra type header line, so the CSV starts cleanly with your column names. In older PowerShell, that type line was added by default, and in newer PowerShell it is not added by default, but keeping the flag keeps the file clean across versions.
What to look for in the CSV output, and what changes if you change one part: The first line should read Computer,Service,Status, and the second line should read srv1,Spooler,Running. If you change srv1 to another computer name, only that value changes, and the headers stay the same. If you add a new property, such as Checked, a new header appears, and every row should then carry that property too, or the new column will look uneven. If you forget -NoTypeInformation in older PowerShell, an extra type line appears at the top, and a spreadsheet reader may treat it as data.
Let us walk through the manifest example, part by part: In New-ModuleManifest -Path .\MyReport.psd1 -RootModule MyReport.psm1 -ModuleVersion "1.0.0" -FunctionsToExport "Get-Report", -Path names the manifest file to create. -RootModule names the module file that holds the code. -ModuleVersion sets the version. -FunctionsToExport lists the function the module makes available. If you change the version to 1.0.1, the manifest describes the newer copy. If you list a function name that does not exist in the module file, the manifest promises something the module cannot deliver, so check the spelling against the real function.
Let us walk through the import example, part by part: Import-Module .\MyReport.psd1 loads the module described by the manifest, and it loads the root module named in that manifest. Get-Command -Module MyReport then lists the commands that came from that module, so you can confirm that Get-Report is really available. If the list is empty or the name is missing, the import did not expose the function you expected, and the manifest or the module file needs a check, before you trust the tool.
Let us walk through the manifest check example, part by part: Test-ModuleManifest -Path .\MyReport.psd1 reads the manifest and checks that it is valid and that it points to real content. It shows the module name and version, so you can compare them with what you intended. If the manifest names a root module file that is missing, or a version that looks wrong, the check will reveal the problem here, in a safe test, instead of later, when someone tries to use the tool for a real report.
Let us walk through the multiple row example, part by part: The first custom object builds a row for one service, and the second builds a row for another service, with the same three properties. Both objects flow through the pipe to Export-Csv, which writes two data rows under one header line. Import-Csv -Path .\report.csv then reads the file back, so you can prove the file is readable and complete. Note that Import-Csv reads every value as text, so a number in the CSV will come back as text, not as a number, and that is fine for a report you read by eye.
When to use it
When to use it, and when not to: Use a module when functions should be reused, shared, or loaded on demand. Use a CSV report when the result should be opened in a spreadsheet or checked by someone else. Do not turn a check you will run once into a module just for show. Do not export functions that are unfinished or untested, because an exported function is a promise to the caller that it works.
Safety and sharing checks: Test the module on small, safe data first, on your own computer, before you point it at anything important. Back up any report file you are about to overwrite, or write the new report to a new file name, so the old report is not lost. Open the CSV and read it before you share it. Check that it holds only facts you are happy to share, and that no private detail slipped into a column by accident.
Worked examples
Read each example in order. Each one explains its parts, then shows what to look for in the output.
Syntax
[PSCustomObject]@{ Property = value } | Export-Csv -Path <path> -NoTypeInformationExample 1
This builds one custom object row, then pipes it to Export-Csv. The -Path parameter names the output file, and -NoTypeInformation keeps the CSV clean by leaving out the extra type header. Look for the header line first, then the data row, to confirm the columns and the values line up.
[PSCustomObject]@{
Computer = "srv1"
Service = "Spooler"
Status = "Running"
} | Export-Csv -Path .\report.csv -NoTypeInformationIllustrative output: Computer,Service,Status srv1,Spooler,Running
Example 2
New-ModuleManifest creates a manifest file. The -Path parameter names the manifest, -RootModule names the module file, -ModuleVersion sets the version, and -FunctionsToExport lists the function the module makes available. Compare the listed name with the real function name in the module file, letter by letter.
New-ModuleManifest -Path .\MyReport.psd1 -RootModule MyReport.psm1 -ModuleVersion "1.0.0" -FunctionsToExport "Get-Report"Illustrative output: MyReport.psd1 created with version 1.0.0 and exported function Get-Report.
Example 3
Import-Module loads the module described by the manifest, including its root module file. Get-Command with -Module MyReport lists the commands from that module, so you can confirm Get-Report is available. If the name is missing, check the manifest export list and the function name in the module file.
Import-Module .\MyReport.psd1
Get-Command -Module MyReportIllustrative output: CommandType Name Module ----------- ---- ------ Function Get-Report MyReport
Example 4
Test-ModuleManifest checks the manifest for problems before you share the module. The -Path parameter names the manifest to check. Look for the module name and version in the result, and compare them with what you intended. A mismatch here is a warning to fix the manifest, not a reason to guess.
Test-ModuleManifest -Path .\MyReport.psd1Illustrative output: Name Version ---- ------- MyReport 1.0.0
Example 5
This builds two rows with the same three properties, exports them to one CSV file, and then reads the file back with Import-Csv. The read back step proves the file is complete and readable. If you add a third row, a third data line should appear. Note that Import-Csv returns values as text.
[PSCustomObject]@{ Computer = "srv1"; Service = "Spooler"; Status = "Running" }
[PSCustomObject]@{ Computer = "srv1"; Service = "BITS"; Status = "Stopped" } | Export-Csv -Path .\report.csv -NoTypeInformation
Import-Csv -Path .\report.csvIllustrative output: Computer Service Status -------- ------- ------ srv1 Spooler Running srv1 BITS Stopped
Nothing on this page executes PowerShell code. The outputs above are illustrative only.
Common mistakes and troubleshooting
Read these before you try the examples, so you can spot the same problems in your own work.
- Using a plain hash table instead of PSCustomObject, so the report does not display or export as neat rows.
- Forgetting -NoTypeInformation, so the CSV starts with an extra header line that confuses readers in older PowerShell.
- Writing a manifest with a function name that does not match the real function in the module.
- Using different property names or a different property order in different rows, so the CSV columns do not line up.
- Using a relative path and then looking for the report in the wrong folder, or overwriting a file you meant to keep.
- Leaving the export list as a wildcard, so small helper functions also become visible to callers who should not need them.
- Never opening the CSV after the export, so a blank file or wrong columns are found by the reader, not by you.
- Sharing a module without testing it in a fresh session, so an old version still loaded in your session hides a mistake in the new file.
Knowledge check
Knowledge check
What does a module manifest describe?
Pick one answer. Feedback appears right away, and you can try again.
Remember this and next step
Remember this: A module packages reusable functions, a report function shapes facts into custom objects with the same properties in every row, Export-Csv saves them as a readable file with clean headers, a manifest names the module, its version, and its exported functions, and you prove the package by importing it in a fresh session and reading the report back. A finished module is one you can load, run, check, and share, without guessing.
Next step: Schedule and run it safely