Last active
August 2, 2023 11:16
-
-
Save markwragg/867686b70e9a0cb6a95dd111248bd95a to your computer and use it in GitHub Desktop.
Function to convert an object into HashTable PowerShell code, with name values optionally anonymized. This was written to quickly create the contents of Pester Mocks, by taking real output and converting it to Hashtables or PsCustomObject output for declaring within the Mock in Pester. The function can anonymize the name strings in the objects a…
This file contains 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
function Format-HashTable { | |
[CmdletBinding()] | |
param( | |
[parameter(, ValueFromPipeline)] | |
$InputObject, | |
[switch] | |
$AnonymizeNames, | |
[switch] | |
$AsPSCustomObject | |
) | |
Begin { | |
filter isNumeric($x) { | |
return $x -is [byte] -or $x -is [int16] -or $x -is [int32] -or $x -is [int64] ` | |
-or $x -is [sbyte] -or $x -is [uint16] -or $x -is [uint32] -or $x -is [uint64] ` | |
-or $x -is [float] -or $x -is [double] -or $x -is [decimal] | |
} | |
$i = 1 | |
} | |
process { | |
if ($AsPSCustomObject) { | |
"[pscustomobject]@{" | |
} | |
else { | |
"@{" | |
} | |
$Properties = ($InputObject | Get-Member -MemberType Property).Name | |
$NameProperties = $Properties | Where-Object { $_ -match 'Name' } | |
foreach ($Property in $Properties) { | |
$Value = $InputObject.$Property | |
$PropertyValue = switch ($Value) { | |
{ $_ -eq $null } { '$null' } | |
{ $_ -is [string] } { "'" + $Value + "'" } | |
{ $_ | IsNumeric } { $Value } | |
} | |
if ($AnonymizeNames) { | |
foreach ($NameProperty in $NameProperties) { | |
$PropertyValue = $PropertyValue -replace $InputObject.$NameProperty,('somerandomname' + $i) | |
} | |
} | |
if ($PropertyValue) { | |
" " + $Property + " = " + $PropertyValue | |
} | |
} | |
$i++ | |
"}" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment