Question

Microsoft's "Required Development Guidelines" for Cmdlet development here states that a Cmdlet should not retain handles to output objects.

However when developing a cmdlet which performs a side effect on pipeline input, which may or may not modify the state of the input object, one can pipe the input object to the output pipeline via WriteObject method to promote further chaining of commands. Since pipeline input parameter is an array of input object type, it will still be retaining a reference to the object.

Will this behavior break the development contract and cause problems?

Was it helpful?

Solution

In your case, I would say you aren't actually keeping a reference to the object. PowerShell is using the InputObject property (the InputObject parameter) to pass the object to you, but PowerShell is maintaining that reference, not you.

If the rule you referred to is firing on your code, you could open a suggestion to improve the detection of this error condition.

To rephrase the rule somewhat - once you call WriteObject, you shouldn't use that object any longer. If you have a reference, you could refer to it. There are several interesting ways you might keep a reference:

  • A local variable
  • A non-static field
  • A static field

Local variables are fine if the last reference to the object is your call to WriteObject. Non-static fields should be fine if they are used to implement a parameter to the cmdlet. Static fields are probably a problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top