我有以下代码:
$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不返回字符串[]吗?
我也尝试过/不使用@,这没有什么区别。
不,你是对的。如图所示这里,[IO.File]::ReadAllLines
确实返回一个String[]
对象。@mjolinor的答案中说明了您所看到的令人困惑的错误(在此不再赘述)。
相反,我将告诉您如何解决该问题。要将String[]
对象转换为List<String>
PowerShell中的对象,需要将其显式转换为:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句