Skip to content

Instantly share code, notes, and snippets.

@jborean93
Last active December 5, 2023 10:25
Show Gist options
  • Select an option

  • Save jborean93/59ae65896c84784ff85f77cb07ce43a9 to your computer and use it in GitHub Desktop.

Select an option

Save jborean93/59ae65896c84784ff85f77cb07ce43a9 to your computer and use it in GitHub Desktop.
Example on how to use a class as a PowerShell splat value
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
@jborean93
Copy link
Copy Markdown
Author

Another option is have the class implement IDictionary and just return the hashtable enumerable for GetEnumerator() 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment