Home > Enterprise >  Rename Powershell object property names but keep value
Rename Powershell object property names but keep value

Time:09-27

I have a Powershell Object[] ($myObject), I am looking to trim off sci_ from any object property name that begins with sci_ but keep the value of the properties

$myObject

$myObject.psobject.Properties does not seem to reveal the property names but found $myObject | Get-Member -MemberType Properties | Select-Object Name does, but havent worked out a way to rename or trim off the sci_ from the property names?

CodePudding user response:

The $myObject variable contains an array of objects, so loop over each object in the array to be able to inspect its properties via .psobject:

$myArray = $myObject |ForEach-Object {
    # prepare dictionary to hold the (renamed) properties
    $newProperties = [ordered]@{}
    foreach($property in $_.psobject.Properties){
        # remove any `sci_` prefix
        $newName = $property.Name -replace '^sci_'
        $newProperties[$newName] = $property.Value
    }

    # create new object based on the renamed properties
    [pscustomobject]$newProperties
}

$myArray now contains an array of objects just like $myObject, except all the objects have had the sci_ prefix removed from all relevant property names

  • Related