-
-
Save disco0/96f1dfee54e9ccf1b42fa32284961e5b to your computer and use it in GitHub Desktop.
A Powershell Class with Mandatory Properties by Default
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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