The goal I'm trying to achieve is to write a PowerShell function that accepts an object of any type and outputs PowerShell statements that may be used to re-create the object.
Example:
# Get-PSCode is the function I'm looking for, it doesn't exist
Get-PSCode -InputObject @(1..5) # -> outputs @(1,2,3,4,5)
The most straightforward solution I've come up with includes multiple type checking conditions, e.g.
function Get-PSCode() {
param(
$InputObject
)
if ($InputObject -is [array]) {
[string]$s = ""
foreach ($i in $InputObject) {
if ($s) { $s += ","}
$s += $i
}
Write-Output "@($s)"
} #elseif ($InputObject -is [hashtable]) etc.etc.
}
The less straightforward solution is to fallback to .NET reflection capabilities, e.g. Function to clone an arbitrary object
Is there a better way to achieve the goal?
Aucun commentaire:
Enregistrer un commentaire