问题描述
我想编写一个 cmdlet,从数据库中读取多条记录并将它们放入管道中.
I want to write a cmdlet that reads multiple records from a database and puts them onto the pipeline.
我想我可以执行单个 WriteObject(Enumerable, true)
或者我可以循环自己并多次调用 WriteObject
.
I think I can do either a single WriteObject(Enumerable<rec>, true)
or I can loop myself and call WriteObject
multiple times.
这两者有什么区别?
推荐答案
这里是文档:Cmdlet.WriteObject 方法(对象,布尔值)
这是一个例子:
# Writes objects one by one
function Test1
{
[CmdletBinding()]param()
$data | %{ $PSCmdlet.WriteObject($_) }
}
# Writes the collection and allows the core to enumerate it one level.
# Numbers of written objects is the collection item count.
function Test2
{
[CmdletBinding()]param()
$PSCmdlet.WriteObject($data, $true)
}
# Writes the collection as a single object.
# Numbers of written objects is 1.
function Test3
{
[CmdletBinding()]param()
$PSCmdlet.WriteObject($data, $false)
}
function Test
{
(Test1).GetType().Name
(Test2).GetType().Name
(Test3).GetType().Name
}
$data = New-Object System.Collections.ArrayList
Write-Host "1 item"
$null = $data.Add('hello')
Test
Write-Host "2+ items"
$null = $data.Add('world')
Test
输出:
1 item
String
String
ArrayList
2+ items
Object[]
Object[]
ArrayList
因此,为集合中的每个项目调用WriteObject(item)
与WriteObject(items, true)
基本相同;在这两种情况下,集合本身都消失了.
Thus, calling WriteObject(item)
for each item in a collection is basically the same as WriteObject(items, true)
; in both cases the collection itself has gone.
WriteObject(items, false)
不同;它返回对集合的引用,调用者可以根据场景有效地使用它.例如,如果集合是 DataTable
对象(不是展开的 DataRow
项集),则调用者可以对返回的 DataTable
成员进行操作对象.
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 a DataTable
object (not unrolled set of DataRow
items) then a caller can operate on DataTable
members of the returned object.
这篇关于编写 PowerShell cmdlet 时 WriteObject(x, true) 和多个 writeobjects 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!