5

How do I make members readonly when I use Add-Member cmdlet in Powershell?

Basically, I want to add-member to a System.Diagnostic.Process which has a readonly property.

Anthony Neace
  • 25,013
  • 7
  • 114
  • 129
Bill
  • 5,263
  • 6
  • 35
  • 50

1 Answers1

8

Like so:

 $p = new-object System.Diagnostics.Process
 $p | Add-member -Name thisisreadonly -membertype scriptproperty -value { 6}
 $p.thisisreadonly #gives 6
 $p.thisisreadonly = 5 #error- Set accessor for property "thisisreadonly" is unavailable.

So basically you create a ScriptProperty, with a getter but no setter.

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • 3
    It's worth mentioning that the -secondvalue parameter of add-member is used to provide the "setter". – Mike Shepard Aug 09 '11 at 03:27
  • Also worth mentioning the `-MemberType` is `ScriptProperty` **not** `-ScriptMethod`, an oversight that lost at least one skimmer of this answer for a few too many minutes. – ruffin Jan 06 '15 at 19:39