79748847

Date: 2025-08-28 08:58:28
Score: 2.5
Natty:
Report link

Restating the Problem

You want:

  1. Accessor methods like get_<PropertyName>() to be hidden automatically when a class instance is created.

  2. If the accessor method is explicitly declared with the hidden keyword, the related ScriptProperty should also be hidden.

  3. To be able to toggle this "hidden" visibility programmatically at runtime (not just at design-time with hidden).

In short: Can you dynamically hide methods (e.g., from Get-Member) after class creation in PowerShell?


Direct Answer

No — you cannot dynamically hide methods on a PowerShell class once it has been compiled.

PowerShell classes are just thin wrappers over .NET types. Once the type is emitted, the metadata about its members (visibility, attributes, etc.) is fixed. Unlike C#, PowerShell does not expose any supported mechanism to rewrite or patch that metadata at runtime.


Why This Is the Case


What You Can Do Instead

Since you can’t change class methods at runtime, here are workarounds:

1. Use Add-Member / PSObject layer instead of class

If you attach script properties/methods dynamically:

$o = [PSCustomObject]@{}
$o | Add-Member -MemberType ScriptMethod -Name "MyMethod" -Value { "Hello" }

# Hide it later
$o.PSObject.Members["MyMethod"].IsHidden = $true

Now Get-Member won’t show MyMethod, because IsHidden works on PSObject members.

This gives you the runtime flexibility you’re asking for, but not within class.


2. Use hidden at design time

If you’re sticking with classes, the only supported way:

class MyClass {
    hidden [string] HiddenMethod() { "secret" }
}

This hides it from Get-Member, but you cannot toggle later.


3. Hybrid approach: wrap the class

You can keep your logic in a class, but expose accessors as PSObject script properties, which you can hide/unhide dynamically:

class MyClass {
    [string] Get_Secret() { "hidden stuff" }
}

$inst = [MyClass]::new()
$ps = [PSCustomObject]@{ Base = $inst }
$ps | Add-Member ScriptProperty Secret { $this.Base.Get_Secret() }
$ps.PSObject.Members["Secret"].IsHidden = $true

Now you have a class internally, but only expose dynamic script properties externally, where you can control visibility.


Limitations & Caveats


Final Summary

If you want, I can draft a POC “Use-ClassAccessors” helper that builds instances using PSObject + Add-Member, so you can keep the same API style but gain runtime hide/unhide capability.

Would you like me to sketch that?

Reasons:
  • Blacklisted phrase (1): Is it possible to
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (1):
Posted by: Sona Arajyan