返回集合时出现Powershell错误。泛型。列表[字符串]
我有以下代码:返回集合时出现Powershell错误。泛型。列表[字符串],powershell,Powershell,我有以下代码: [Collections.Generic.List[String]]$script:Database = New-Object Collections.Generic.List[String] [string]$script:DatabaseFile = "C:\NewFolder\database.csv" function RunProgram { $script:Database = getCurrentDatabase #errors after this li
[Collections.Generic.List[String]]$script:Database = New-Object Collections.Generic.List[String]
[string]$script:DatabaseFile = "C:\NewFolder\database.csv"
function RunProgram
{
$script:Database = getCurrentDatabase #errors after this line
}
function getCurrentDatabase
{
[string[]]$database = Get-Content -Path $script:DatabaseFile
[Collections.Generic.List[String]]$databaseAsList = $database
return $databaseAsList
}
getCurrentDatabase返回后,我得到此异常:
Cannot convert the "system.object[]" value of type "system.object[]" to type "system.collections.generic.list`1[system.string]"
要使代码正常工作,我需要执行以下操作:
[Collections.Generic.List[String]]$script:Database = New-Object Collections.Generic.List[String]
[string]$script:DatabaseFile = "C:\NewFolder\database.csv"
function RunProgram
{
getCurrentDatabase #this works fine
}
function getCurrentDatabase
{
[string[]]$database = Get-Content -Path $script:DatabaseFile
$script:Database = $database
}
为什么第一种方法会抛出该异常,而第二种方法不会
编辑:
我使用的是PS 2.0版,C:\NewFolder\database.csv包含以下一行:
Release Group,Email Address,Template ID,Date Viewed
这是人们经常去旅行的地方。。。 当您从函数输出集合时,PowerShell将枚举这些集合,并在过程中丢失原始类型。要防止这种情况发生,可以使用一元逗号:
function getCurrentDatabase
{
[string[]]$database = Get-Content -Path $script:DatabaseFile
[Collections.Generic.List[String]]$databaseAsList = $database
, $databaseAsList
}
一元逗号应防止PowerShell枚举您的集合(它实际上枚举了我们刚刚使用一元逗号创建的集合)
不久前我写了一篇关于它的文章-应该有助于更详细地理解它。你能发布你文件的内容吗?嗨,查普,请看我的编辑。我试着运行你的第一个代码片段,它运行时没有错误(包括调用
RunProgram
和将$script:Database
写入主机)。。。这就是脚本中的确切代码吗?请注意,第11行出现语法错误(缺少括号):[Collections.Generic.List[String]]$databaseAsList=$database
很抱歉,我的原始代码中没有输入错误。是的,这是全部代码。这可能与我正在使用Powershell v2.0有关吗?哇,我相信你能理解,对于从C开始的程序员来说,这是多么不直观!你知道为什么我的密码会对查普有用吗?他在我的问题下面的评论中写道,它对他有效。我猜它是PowerShell版本:当我在v3上尝试时,它工作得很好,必须使用PowerShell-version 2
进行测试,以获得与您相同的错误。