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.
To do this, we use the Set-ItemProperty command with the property name of IsReadOnly and set the Value to $true. Doing so produces no output, but we can confirm it's set to read-only now by using Get-ItemProperty and checking on the IsReadOnly property again. Now you can see the IsReadOnly property is set to True.
Although Powershell doesn't have real readonly class properties, we can mimic them in two elegant ways: Class methods as getter and setter functions. Script properties with getter and setter functions.
To get file attributes in PowerShell, you can use Get-ChildItem or Get-Item cmdlets. It returns the file attributes or properties available on the specified files. To get the list of all properties available, use the Get-Member cmdlet.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With