编写 PowerShell cmdlet 时,WriteObject(x, true) 和多个 writeobject 有什么区别?
我想编写一个 cmdlet,从数据库读取多条记录并将它们放入管道中。
我想我可以执行单个 WriteObject(Enumerable
或者我可以循环自己并多次调用 WriteObject
。
这两者有什么区别?
I want to write a cmdlet that reads multiple records from a database and puts them onto the pipeline.
I think I can do either a single WriteObject(Enumerable<rec>, true)
or I can loop myself and call WriteObject
multiple times.
What's the difference between these two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是文档: Cmdlet.WriteObject 方法 ( Object, Boolean)
下面是示例:
输出:
因此,为集合中的每个项目调用
WriteObject(item)
基本上与WriteObject(items, true)
;在这两种情况下,收藏品本身都消失了。WriteObject(items, false)
是不同的;它返回对集合的引用,调用者可以根据场景有效地使用它。例如,如果集合是DataTable
对象(不是展开的DataRow
项集),则调用者可以对返回的DataTable
成员进行操作目的。Here is the documentation: Cmdlet.WriteObject Method (Object, Boolean)
And here is the example:
Output:
Thus, calling
WriteObject(item)
for each item in a collection is basically the same asWriteObject(items, true)
; in both cases the collection itself has gone.WriteObject(items, false)
is different; it returns a reference to the collection and the caller can use that effectively depending on a scenario. For example, if a collection is aDataTable
object (not unrolled set ofDataRow
items) then a caller can operate onDataTable
members of the returned object.那么,
WriteObject(Object, boolean)
将允许您输出一个集合并使其保持完整(如果使用第二个参数“false”调用)。通常,PowerShell 会枚举放入管道的所有集合。因此,您可以输出一个字符串数组,结果将是 [String[]] 类型。而如果让 PowerShell 解开它,它将是 [Object[]] 中的字符串数组。
您还可以使用“true”来调用该重载,它就像调用
WriteObject(Object)
的循环一样。Well,
WriteObject(Object, boolean)
will allow you to output a collection and have it stay intact (if called with "false" for the second argument). Normally PowerShell will enumerate any collections that get put on the pipeline.So you could output a string array and the result would be of type [String[]]. While if you let PowerShell unwrap it, it will be an array of strings in a [Object[]].
You can also call that overload with "true" and it will be just like a loop calling
WriteObject(Object)
.