0

Following Create a wrapper for functions in powershell, I want to add an attribute that changes functions' (more precisely cmdlets) behavior. Add a certain Begin and DynamicParam scriptblock.

The attribute could act like a decorator in python. That is replacing the function with a new one that "wraps it" and calls it internally. Or it could just keep the original cmdlet object (that is keep the Process code , attributes and parameters), but it should add a "constant" begin section to every function(maybe depends on the function's name alone).

Is it possible to do it natively in powershell?

The question can be divided to 2:

  1. Is it possible to dynamically generate a function?
  2. Is it possible to do it in an attribute?

An example

function My
 {
[WrapperFor(Other)]  
[CmdLetBinding()] 

Process {  Other @newparams }  
} 

Which causes My to support all params of Other and parse them. Practically adds code sections.

user2679290
  • 144
  • 9
  • 1
    Can you expand on what you mean by "Is it possible to dynamically generate a function?"? Based on what? – Mathias R. Jessen Jan 19 '23 at 10:51
  • I did. Let me know if it is not clear. – user2679290 Jan 19 '23 at 11:01
  • You can see an example for the added code in the solution there (Let function). – user2679290 Jan 19 '23 at 11:10
  • Can you show some example code that shows this hypothetical attribute being used? – mclayton Jan 19 '23 at 11:13
  • The output of a powershell script is a string or object. So you wrapper can be a powershell method that filters the string output or the object output. I often use Format-Table to get list of powershell object inside a variable. – jdweng Jan 19 '23 at 11:15
  • 1
    Gotcha. No such attribute exists, and even if you implement one, PowerShell's parser and compiler wouldn't know what to do with it. You _could_ write a script that parses and generates the resulting function based on presence of a custom attribute, but nothing natively in PowerShell – Mathias R. Jessen Jan 19 '23 at 12:20

0 Answers0