Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sdoubleday/3ce8d378f47594288a77bfe22b3fdbaf to your computer and use it in GitHub Desktop.
Save sdoubleday/3ce8d378f47594288a77bfe22b3fdbaf to your computer and use it in GitHub Desktop.
Enums and CustomAttributes in PowerShell Module Manifests
<#
If you create enums and/or custom attributes and want to reuse them, you would (or at least, I did) think that they should go into psm1 module files and be included in other modules via the NestedModules line of the module manifest.
BUT YOU WOULD BE (or at least, I was) WRONG!
Instead, create them in .ps1 script files and add them to the ScriptsToProcess line of the module manifest.
And if you use the enum directly in Pester tests, you will need to run the enum script file there, too, as they do not persist between scripts (as noted here: https://tfl09.blogspot.com/2014/11/enums-in-powershell-v5.html).
That said, if you follow this advice for enums (is it that the enums are in ScriptsToProcess, or anything? I haven't tested), you may need to refactor classes into THEIR own psm1 files. But in so doing, you may break Get-Help and intellisense for functions that take objects of those classes as parameters. At which point you may wind up with all the Enums and Classes back in the main psm1 file(s).
By way of example:
#>
#So, this goes in, say, .\CustomAttributes.ps1
class MyCustomType : System.Attribute {
[string]$Name
MyCustomType ([string] $t) {
write-verbose "My Custom Attribute"
$this.Name = $t
}
}
#And this goes in, say, .\Enums.ps1
ENUM Reasons {
Because = 0
TheSkyIsFalling = 1
}
##And then you would go into the .psd1 manifest file and add them to ScriptsToProcess (yes, they DO need to be .ps1, unlike NestedModules, which takes ps1, psm1, and psd1 files without complaint):
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
ScriptsToProcess = @('.\Enums.ps1','.\CustomAttributes.ps1')
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @('Modules','.\Go\Here.psd1')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment