Powershell将String []转换为List <string> </string>

时间:2014-02-13 01:27:49

标签: powershell

我有这段代码:

    $csvUserInfo = @([IO.File]::ReadAllLines($script:EmailListCsvFile))
    $x = $csvUserInfo.ToList()

运行时,我收到此错误:

Method invocation failed because [System.String] does not contain a method named 'ToList'.

为什么$ csvUserInfo类型为String?

不是[IO.File] :: ReadAllLines返回字符串[]?

我已经尝试过/没有@,它没有任何区别。

2 个答案:

答案 0 :(得分:12)

不,你是对的。如图here所示,[IO.File]::ReadAllLines确实返回String[]个对象。您正在看到的令人困惑的错误在@ mjolinor的answer中解释(我在此不再重复)。

相反,我会告诉你如何解决问题。要在PowerShell中将String[]对象转换为List<String>对象,您需要将其明确地转换为:

PS > [string[]]$array = "A","B","C"
PS > $array.Gettype()

IsPublic IsSerial Name                                     BaseType                                      
-------- -------- ----                                     --------                                      
True     True     String[]                                 System.Array                                  


PS > 
PS > [Collections.Generic.List[String]]$lst = $array
PS > $lst.GetType()

IsPublic IsSerial Name                                     BaseType                                      
-------- -------- ----                                     --------                                      
True     True     List`1                                   System.Object                                 

PS >

在您的具体情况下,代码将是:

$csvUserInfo = [IO.File]::ReadAllLines($script:EmailListCsvFile)
[Collections.Generic.List[String]]$x = $csvUserInfo

答案 1 :(得分:3)

它返回[string []],但该类型没有tolist()方法。我相信你所看到的是V3中引入的自动成员枚举。 V2抛出相同的错误,但对于[System.String []]。

它在数组上查找了该方法,并没有找到它,因此它尝试了成员枚举,以查看它是否是数组成员的方法。它也没有找到它,这就是它放弃了所以你得到了数组成员对象的错误。

相关问题