【问题标题】:Powershell: Turn list output into an array of objects or something similar using PowershellPowershell:使用 Powershell 将列表输出转换为对象数组或类似的东西
【发布时间】:2013-05-29 15:38:53
【问题描述】:

我知道如何通过 PSObjects 将哈希表、数组等从 Powershell 返回到 c#。为了使用它,我需要从 Powershell 脚本返回一个对象 - 而不仅仅是列出输出。

但是如何从 Powershell 中的列表中获取可以从 Powershell 脚本返回的结构化内容?

想想这个简单的场景(例如目的):

Get-ChildItem C:\Test

我得到类似这样的输出:

PS C:\test> Get-ChildItem

Directory: C:\test

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        03.06.2013     14:59          6 test1.txt
-a---        03.06.2013     14:59          5 test2.txt

现在我想获取每个文件的 Name 和 Length 属性,并将其作为某种对象从 powershell 脚本中返回,我可以使用 C# 进行处理。

我可以用 C# 处理的一个例子是:

$a = New-Object psobject -Property @{
   Name = "test1.txt"
   Age = 6
}

$b = New-Object psobject -Property @{
    Name = "test2.txt"
    Age = 5
}

$myarray = @()

$myarray += $a
$myarray += $b

Return $myarray

如何从 Get-ChildItem(或提供列表的类似内容)获取对象数组或类似内容?

请注意,这不是专门针对 Get-ChildItem,它只是用作输出列表的示例。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    应该这样做:

    $arr = Get-ChildItem | Select-Object Name,Length
    return $arr
    

    如果由于某种原因它不起作用,请尝试将数组嵌套在一个数组元素中(使用逗号运算符)

    return ,$arr
    

    【讨论】:

    • 我喜欢轮子。所以...$arr = (Get-ChileItem | % {[PSCustomObject]@{Name=$_.Name;Lenght=$_.Length}})
    • 您正在走更长的路线,但这是一条有效的路线:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 2016-08-06
    • 2017-03-12
    相关资源
    最近更新 更多