Last active
December 5, 2023 10:25
-
-
Save jborean93/59ae65896c84784ff85f77cb07ce43a9 to your computer and use it in GitHub Desktop.
Example on how to use a class as a PowerShell splat value
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
| class SplatClass : System.Collections.IEnumerable { | |
| SplatClass() {} | |
| [System.Collections.IEnumerator] GetEnumerator() { | |
| # This can be any hashtable stored or derived from the class. This is | |
| # just an example | |
| $params = @{ | |
| Path = '/tmp' | |
| } | |
| $splat = $params.GetEnumerator().ForEach{ | |
| # The pipe to Write-Output is key to add a NoteProperty for a str | |
| # "<CommandParameterName>" is used by pwsh in an array splat to | |
| # identify parameter names from values. | |
| $key = "-" + $_.Key | Write-Output | |
| $key.PSObject.Properties.Add( | |
| [System.Management.Automation.PSNoteProperty]::new( | |
| "<CommandParameterName>", | |
| $_.Key) | |
| ) | |
| $key | |
| $_.Value | |
| } | |
| return $splat.GetEnumerator() | |
| } | |
| } | |
| $obj = [SplatClass]::new() | |
| Get-Item @obj |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another option is have the class implement
IDictionaryand just return the hashtable enumerable forGetEnumerator()but that requires a few more methods to be implemented. Instead this takes advantage of a an array splat and the<CommandParameterName>note property to differentiate between parameter names and their values.