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

Bac*_*ave 6 powershell

我有这个代码:

    $csvUserInfo = @([IO.File]::ReadAllLines($script:EmailListCsvFile))
    $x = $csvUserInfo.ToList()
Run Code Online (Sandbox Code Playgroud)

当它运行时,我收到此错误:

Method invocation failed because [System.String] does not contain a method named 'ToList'.
Run Code Online (Sandbox Code Playgroud)

为什么$ csvUserInfo类型为String?

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

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

iCo*_*dez 13

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

相反,我会告诉你如何解决问题.要在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 >
Run Code Online (Sandbox Code Playgroud)

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

$csvUserInfo = [IO.File]::ReadAllLines($script:EmailListCsvFile)
[Collections.Generic.List[String]]$x = $csvUserInfo
Run Code Online (Sandbox Code Playgroud)