powershellpsps1psobject

Powershell: remove value from property by its value


There is a JSON like:

{ a: 
   {  
      a1 : { a11:{}; a12:{}; a13:{};}; 
      a2 : {some other values}; 
    } 
  b: 
    { 
      b1:  {another values} 
    }
}

so then I converted it using powershell with command and put it into a variable $test

$test = Get-Content $some_file_path | ConvertFrom-Json

and then I'd like to get this JSON with some excluding from "a1". result should be like ( so I remove a13):

{ a: 
   {  
      a1 : { a11: {} a12: {}}; 
    } 
  b: 
    { 
      b1:  {another values} 
    }
}

so, if I use:

$test.a.PSObject.Properties["a1"].Remove("a13") 

returns me an error:

Method invocation failed because [System.Management.Automation.PSNoteProperty] does not contain a method named 'Remove'.

so, I clearly don't understand what should I do. could anyonne help me to understand?


Solution

  • .Remove() is a method on the properties collection (.psobject.Properties), not on the individual entries in that collection (which explains the error you saw).

    A simplified example:

    $obj = [pscustomobject] @{ one = 1; two = 2; three = 3 }
    
    # Remove property .two
    $obj.psobject.Properties.Remove('two')