Skip to content

Instantly share code, notes, and snippets.

Last active November 8, 2022 12:29
What would you like to do?
A PowerShell function to convert an object instance into a PowerShell class definition.
Function ConvertTo-PSClass {
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[Parameter(Mandatory, HelpMessage = "Enter the name of your new class")]
[Parameter(HelpMessage = "Specify properties to include from the reference inputput object. The default is all properties.")]
[Parameter(HelpMessage = "Specify properties to exclude from the reference inputput object.")]
[Parameter(HelpMessage = "Provide a brief description of the class. It will be inserted into the class definition.")]
Begin {
Write-Verbose "Starting $($myinvocation.MyCommand)"
#initialize a counter
$c = 0
} #begin
Process {
#only need a single instance of the object
if ($c -eq 0) {
Write-Verbose "Converting existing type $($InputObject.getType().Fullname)"
#create a list to hold properties
$prop = [system.collections.generic.list[object]]::new()
#define the class here-string
$myclass = @"
# This class is derived from $($InputObject.getType().Fullname)
# $Description
class $Name {
#get the required properties
if ($Properties) {
(${ $Properties -contains $ }) |
Select-Object -Property Name, TypeNameOfValue |
ForEach-Object {
Write-Verbose "Adding $($"
} #forEach
} #if Properties
else {
Write-Verbose "Adding all properties"
$ | Select-Object -Property Name, TypeNameOfValue |
ForEach-Object {
Write-Verbose "Adding $($"
} #foreach
} #else all
if ($Exclude) {
foreach ($item in $Exclude) {
Write-Verbose "Excluding $item"
#remove properties that are tagged as excluded from the list
[void]$prop.remove($($prop.where({ $ -like $item })))
Write-Verbose "Processing $($prop.count) properties"
foreach ($item in $prop) {
#add the property definition name to the class
#e.g. [string]$Name
$myclass += "`t[{0}]`${1}`n" -f $item.TypeNameOfValue, $
#add placeholder content to the class definition
$myclass += @"
# Methods can be inserted here.
# Don't forget to use the RETURN key word unless the returntype is [void]
[returntype] MethodName(<parameters>) {
return value
#constructor placeholder
$Name() {
#insert code here
} #close class definition
#if running VS Code or the PowerShell ISE, copy the class to the clipboard
#this code could be modified to insert the class into the current document
if ($ -match "ISE|Visual Studio Code" ) {
$myClass | Set-Clipboard
Write-Host "The class definition has been copied to the clipboard." -ForegroundColor green
else {
} #if first object
else {
Write-Verbose "Skipping next object"
} #process
End {
Write-Verbose "Ending $($myinvocation.MyCommand)"
} #end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment