Sort-Object cmdlet 的 -InputObject 参数如何工作? [英] How does -InputObject parameter of the Sort-Object cmdlet work?

查看:44
本文介绍了Sort-Object cmdlet 的 -InputObject 参数如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PowerShell 4.0

PowerShell 4.0

我在此处阅读了Sort-Object cmdlet(TechNet 页面).我不明白如何使用 -InputObject 参数.该页面没有示例.我也没有在互联网上找到这个信息.我将非常感谢它的使用示例,或者包含该信息的 Internet 页面的链接.

I read about Sort-Object cmdlet here (TechNet page). I don't understand how to use -InputObject parameter. That page hasn't examples for it. Also I didn't find this info in Internet. I would be very grateful for the examples of its using, or for the links to Internet pages with that info.

我尝试使用它我如何理解它的目的(根据文档):

I have tried to use it how I understand its purpose (according documentation):

$items = ('a','b','c','d')
$result = sort -InputObject $items -Descending

但是 result 变量具有与 items 相同的值,而不是其下降版本.

But the result variable has the same value like it has items instead of its descended version.

谢谢.

推荐答案

InputObject 是用于接受管道输入的参数的通用名称.这是内部 PowerShell 命名约定的一部分,没有什么特别之处.

InputObject is a generic name used for a parameter that takes pipeline input. It's part of internal PowerShell naming convention and there is nothing special about it.

您的示例不像您认为的那样工作,因为当您将集合传递给 InputObject 参数时,它被视为单个项目而不是展开为单个元素,因此它不会得到排序.这允许您对集合进行排序.

Your example doesn't work as you think it should, because when you pass a collection to the InputObject parameter it's treated as a single item and not unwrapped to individial elements, so it doesn't get sorted. This allows you to sort a collection of collections.

考虑以下示例:

Sort-Object 是这样工作的:

function Add-Quotes
{
    Param
    (
        [Parameter(ValueFromPipeline = $true)]
        $InputObject
    )

    Process
    {
        "'$InputObject'"
    }
}

请注意,管道会自动解包数组,然后在每次迭代中将idvidial项分配给$InputObject变量,然后在Process块中进行处理:

Note that array is automatically unwrapped by the pipeline, then idividial items are assigned the $InputObject variable in each iteration and then processed in Process block:

PS> $items | Add-Quotes
'a'
'b'
'c'
'd'

但是当你将一个集合传递给 InputObject 时,它不会被迭代,因为没有管道来解包它:

But when you pass a collection to the InputObject it's not iterated over, because there is no pipeline to unwrap it:

PS> Add-Quotes -InputObject $items
'a b c d'

有时这是一种理想的行为,有时您需要解开集合,无论它们来自何处.在这种情况下,您使用内部 foreach 循环来执行此操作:

Sometimes it's a desired behavior, sometimes you need to unwrap collections no matter where they came from. In this case you use internal foreach loop to do so:

function Add-Quotes
{
    Param
    (
        [Parameter(ValueFromPipeline = $true)]
        [string[]]$InputObject
    )

    Process
    {
        foreach($item in $InputObject)
        {
            "'$item'"
        }
    }
}

PS > $items | Add-Quotes
'a'
'b'
'c'
'd'

PS > Add-Quotes -InputObject $items
'a'
'b'
'c'
'd'

希望这能让你清楚.

这篇关于Sort-Object cmdlet 的 -InputObject 参数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆