Skip to content

Instantly share code, notes, and snippets.

@disco0
Forked from JustinGrote/MandatoryProperties.ps1
Created October 23, 2021 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disco0/96f1dfee54e9ccf1b42fa32284961e5b to your computer and use it in GitHub Desktop.
Save disco0/96f1dfee54e9ccf1b42fa32284961e5b to your computer and use it in GitHub Desktop.
A Powershell Class with Mandatory Properties by Default
using namespace System.Collections
using namespace System.Management.Automation
using namespace System.ComponentModel.DataAnnotations
using namespace System.Runtime.Serialization
class MandatoryProperties {
MandatoryProperties([IDictionary]$properties) {
$this.GetType().GetProperties([System.Reflection.BindingFlags]'Instance,Public') | ForEach-Object {
$propertyName = $PSItem.Name
[bool]$isOptional = $PSItem.GetCustomAttributes([OptionalFieldAttribute], $true).count -gt 0
if (
-not $properties.Contains($propertyName) -and
-not $isOptional
) {
throw [ArgumentNullException]::new($propertyName, 'A Mandatory property was not specified')
}
$this.$propertyName = $properties[$propertyName]
}
}
}
# A group that includes all users in the org with a particular title
class GlobalGroup : MandatoryProperties {
# The name of the list. Additional information may be added based on this name
[string]$Name
# Which user titles should be included in the group
[string[]]$JobTitle
# An additional description of the group, maybe including the full address
[OptionalField()][string]$Description
GlobalGroup([IDictionary]$properties) : base($properties) {}
}
#This will fail
[GlobalGroup]@{}
#This will fail and warn you jobtitle is mandatory
[GlobalGroup]@{Name='test'}
#This is fine because description is flagged as optional
[GlobalGroup]@{Name='test',JobTitle='manager'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment