Skip to content

Instantly share code, notes, and snippets.

@markwragg
Last active August 2, 2023 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markwragg/867686b70e9a0cb6a95dd111248bd95a to your computer and use it in GitHub Desktop.
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…
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