Skip to content

Commit fc7678e

Browse files
authored
Add note of enumerateCollection in design guideline (#25465)
1 parent 1aadcf9 commit fc7678e

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

documentation/development-docs/design-guidelines/cmdlet-best-practices.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,27 @@ public class MySampleCmdlet : MyBaseCmdlet
8888
}
8989
```
9090

91+
#### Enumerate Collection When WriteObject()
92+
93+
When returning a collection of objects, the cmdlet should enumerate the collection. This ensures that the objects are written to the pipeline one at a time, which is the expected behavior for PowerShell cmdlets.
94+
95+
There are two ways to accomplish this: (a) call `WriteObject()` for each object in the collection, or (b) use `WriteObject()` with the `enumerateCollection` parameter set to `true`. The `enumerateCollection` parameter is a boolean that, when true, will enumerate the collection and write each object to the pipeline.
96+
97+
The code below shows how this should look in a cmdlet:
98+
99+
```cs
100+
var resources = Client.ListResources();
101+
102+
// option a: call WriteObject() for each object in the collection
103+
foreach (var resource in resources)
104+
{
105+
WriteObject(resource);
106+
}
107+
108+
// option b: use WriteObject() with the enumerateCollection parameter set to true
109+
WriteObject(resources, true);
110+
```
111+
91112
### `ShouldProcess`
92113

93114
If a cmdlet makes any changes to an object on the server (_e.g._, create, delete, update, start, stop a resource), the cmdlet should implement `ShouldProcess`. This property adds the `-WhatIf` and `-Confirm` parameters to the cmdlet:

0 commit comments

Comments
 (0)